2012-04-22 90 views
2

與標題一樣,我想更改用戶通過表單上傳的文件的文件名。這裏是代碼更改通過表單上傳的tmp文件的文件名

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的VAR和它仍然無法正常工作...
代碼

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'勞倫斯...

+0

你就不能調用move_uploaded_file($ tmp_name的值,$位置\ $ username) – 2012-04-22 08:12:17

+0

'move_uploaded_file($ move_to,$ _ FILES ['myfile'] ['tmp_name']); 'thos vars需要互換 – 2012-04-22 09:31:53

+0

@ThatBenderGuy你需要添加像我的第一個if語句 – 2012-04-22 09:34:58

回答

1

繼承人它,POST請求需要檢查,只檢查$name是不夠安全的&安全的方式待辦事項,$username需要剝離的任何特殊字符,$id需要檢查其設置是數字,文件的特定類型的擴展需要尋找,也允許MIME類型需要交叉匹配,加上寬度和高度尺寸需要檢查,很多想法,上傳可以是非常不安全的,更不用說圖像可以有PHP注入到文件註釋,如果處理不當可能會得到執行:

<?php 

if($_SERVER['REQUEST_METHOD']=='POST' && isset($username) && is_numeric($id) 
&& isset($_FILES['myfile']['error']) && $_FILES['myfile']['error']=='UPLOAD_ERR_OK'){ 

    $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']); 

    //not more then 200px 
    if($info[0]>200 || $info[1] > 200){ 
     //file too large 
    } 

    $allowed = array('image/png','image/jpg','image/gif'); 
    if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){ 
     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{ 
     //Not allowed 
    } 
} 
?> 

<form action="" method="POST" enctype="multipart/form-data"> 
    <!--1 MB = 1048576 bytes--> 
    <input type="hidden" name="MAX_FILE_SIZE" value="1048576" /> 

    <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> 


UPDATE編輯 這裏是上載過程中的OOP版本,也許你會發現它很有趣,我添加了所有可能出現的錯誤太多,P

<?php 
Class updateUserAvatar{ 
    public $upload_path; 
    public $full_path; 
    public $name; 
    public $size; 
    public $ext; 
    public $output; 
    public $input; 
    public $prefix; 
    private $allowed; 

    function upload(){ 
     if($_SERVER['REQUEST_METHOD'] == 'POST'){ 
      if(isset($_FILES[$this->input]['error'])){ 
       if($_FILES[$this->input]['error'] == 0){ 
        $this->name  = basename($_FILES[$this->input]['name']); 
        $file_p   = explode('.', $this->name); 
        $this->ext  = end($file_p); 
        $this->full_path = rtrim($this->upload_path,'/').'/'.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $this->prefix).'.'.$this->ext; 
        $info   = getimagesize($_FILES[$this->input]['tmp_name']); 
        $this->size  = filesize($_FILES[$this->input]['tmp_name']); 

        if($info[0]>$this->allowed['dimensions']['width'] || $info[1] > $this->allowed['dimensions']['height']){ 
         $this->output = 'File dimensions too large!'; 
        }else{ 
         if($info[0] > 0 && $info[1] > 0 && in_array($info['mime'],$this->allowed['types'])){ 
          move_uploaded_file($_FILES[$this->input]['tmp_name'],$this->full_path); 
          $this->output = 'Upload success!'; 
         }else{ 
          $this->output = 'File not supported!'; 
         } 
        } 
       }else{ 
        if($_FILES[$this->input]['error']==1){$this->output = 'The uploaded file exceeds the upload_max_filesize directive!';} 
        if($_FILES[$this->input]['error']==2){$this->output = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in our HTML form!';} 
        if($_FILES[$this->input]['error']==3){$this->output = 'The uploaded file was only partially uploaded!';} 
        if($_FILES[$this->input]['error']==4){$this->output = 'No file was uploaded!';} 
        if($_FILES[$this->input]['error']==6){$this->output = 'Missing a temporary folder!';} 
        if($_FILES[$this->input]['error']==7){$this->output = 'Failed to write uploaded file to disk!';} 
        if($_FILES[$this->input]['error']==8){$this->output = 'A PHP extension stopped the file upload!';} 
       } 
      } 
     } 
    } 

    function setPath($var){ 
     $this->upload_path = $var; 
    } 
    function setAllowed($var=array()){ 
     $this->allowed = $var; 
    } 
    function setFilePrefix($var){ 
     $this->prefix = preg_replace('/[^a-zA-Z0-9.-]/s', '_', $var); 
    } 
    function setFormInput($var){ 
     $this->input = $var; 
    } 
}//END CLASS 


if($_POST['type'] != "defaultDot"){ 
    //Setup 
    $upload = new updateUserAvatar(); 
    $upload->setPath('./images/avatars/'); 
    $upload->setFilePrefix($username); 
    $upload->setAllowed(array('dimensions'=>array('width'=>200,'height'=>200), 
           'types'=>array('image/png','image/jpg','image/gif'))); 
    $upload->setFormInput('myfile'); 
    $upload->upload(); 

    if($upload->output == 'Upload success!'){ 
     //do query 
     $updateURL = mysql_query("UPDATE users SET avatar='$upload->full_path' WHERE id=$id"); 
    } 
    //message 
    $avaMessage = $upload->output; 
}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>'; 
} 
?> 
+0

此代碼唯一的問題是我得到這個警告**警告:getimagesize()[function.getimagesize]:文件名不能爲空在C:\ xampp \ htdocs \ mainwebsite \ editprofile.php在線83 ** - - - ** 83行代碼** '$ info = getimagesize($ _ FILES ['myfile'] ['tmp_name']);' – ThatBenderGuy 2012-04-22 09:12:07

+0

檢查$ _FILES ['myfile'] ['tmp_name']'是組。如果它是空的,它甚至不會使用該函數,所以你不能使用包括'$ _SERVER ['REQUEST_METHOD']' – 2012-04-22 09:15:44

+0

'的所有代碼。我將編輯主要問題以向你展示我擁有的東西。我忽略了一些,並保留了一些原始代碼以使其工作。我在頁面上有幾種形式,所以這就是爲什麼'isset($ _ POST ['updateAvatar'])'有 – ThatBenderGuy 2012-04-22 09:20:32