就像标题一样,我想更改用户通过表单上传的文件的文件名。这是代码
HTML
<form action="editprofile.php" method="POST" enctype="multipart/form-data">
<p>Upload your image:<p /><input type="file" name="myfile"></p><br />
<p><input type="radio" name="type" value="defaultDot">Use Default</p>
<p><input type="submit" name="updateAvatar"></p>
</form>
这是我的 php 脚本,它将上传的文件移动到正确的目录
PHP
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$size = getimagesize($_FILES['myfile']['tmp_name']);
if($name){
//start upload process
if($size != FALSE){
$location = "images/avatars/$name";
move_uploaded_file($tmp_name, $location);
$query = mysql_query("UPDATE users SET avatar='$location' WHERE id=$id");
$avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Updated - Uploaded Image!.</font></p>';
}else{
$avaMessage = '<p><font size=2 color=red face=Tahoma>Please only submit image files!</font></p>';
}
}
我怎样才能给图像一个自定义名称?例如,我有一个名为$username的变量,它存储用户名的会话变量。如果我想将图像命名为具有相同文件扩展 名的$username变量怎么办?
编辑:编辑:编辑:
添加了你的 if 语句劳伦斯,我交换了 move_upload_files 中的变量,但它仍然不起作用......
代码
if($_SERVER['REQUEST_METHOD']=='POST' && isset($username) && is_numeric($id)
&& isset($_FILES['myfile']['error']) && $_FILES['myfile']['error']=='UPLOAD_ERR_OK'){
if($_POST['type'] != "defaultDot"){
//$avaURL = $_POST['url'];
//$updateURL = mysql_query("UPDATE users SET avatar='$avaURL' WHERE id=$id");
//$avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Uploaded!</font></p>';
$name = basename($_FILES['myfile']['name']);
$ext = end(explode('.', $name));
$move_to = "images/avatars/".preg_replace('/[^a-zA-Z0-9.-]/s', '_',$username).'.'.$ext;
$info = getimagesize($_FILES['myfile']['tmp_name']);
if($name){
//start upload process
$allowed = array('image/png','image/jpg','image/gif');
if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
if($info[0]>200 || $info[1] > 200){
//File dimensions too large
$avaMessage = '<p><font size=2 color=red face=Tahoma>File dimensions too large.</font></p>';
}else{
//File put contents will over write if file exsist
move_uploaded_file($_FILES['myfile']['tmp_name'], $move_to);
mysql_query("UPDATE users
SET avatar='".mysql_real_escape_string($move_to)."'
WHERE id=".$id." AND owner='".$_SESSION['username']."'");
$avaMessage = 'Avatar Updated - Uploaded Image!.';
}
}else{
$avaMessage = '<p><font size=2 color=red face=Tahoma>Please only submit image files!</font></p>';
}
}else{
$avaMessage = '<p><font size=2 color=red face=Tahoma>Please select a file!</font></p>';
}
}else{
$avaURL = 'images/avatars/default.png';
$updateURL = mysql_query("UPDATE users SET avatar='$avaURL' WHERE id=$id");
$avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Updated - Default.</font></p>';
}
}
即使使用固定的“POST”劳伦斯仍然无法工作......