PHP文件上傳的具體思路及實現

最近一段時間對PHP文件處理方面很感興趣,因此在許多站點上看瞭許多的文件處理的文章,但是國內許多的站點上的PHP文件處理方面的知識大多數是你抄我的我抄你的,用baidu.com或者是google.com搜索出來的東西多是重復的。最近在國外一個站點上盾瞭一篇文章感覺很不錯,因此推薦給大傢閱讀。

首先我們有必要說明一下文件上傳的操作流程及用到的知識點:

文件上傳我們需要用到HTML裡面表單的type=”file”類型,及其enctype屬性。這是我們大傢必須要用的。當然瞭PHP函數庫當中的FILE函數庫,字符串類型函數庫,目錄函數庫及$_FILES[]的使用是我們必須要用到的。

也許每一個站點都可能會對上傳文件有許多的限制,這些限制會包括 文件類型,文件大小,擴展名,以及上傳目錄的存在與否,上傳文件的存在與否,目錄的可寫性,可讀性,上傳文件的改名及怎樣把文件從緩存當中復制到你所需要的目錄當中。

當然出錯的預處理也是我們不容忽視的!如果再深一步的討論我們還可以對文件的操作起用事件日志的記錄。

下面我們通過一段程序來實現這些功能:

——————————————————————————————–


首先是我們預設的變量值,它包括文件大小,文件擴展名類型,MIMI類型,及是否刪除的開關變量

$MAX_SIZE = 2000000;
$FILE_MIMES = array(image/jpeg,image/jpg,image/gif
                   ,image/png,application/msword);

$FILE_EXTS  = array(.zip,.jpg,.png,.gif);

$DELETABLE  = true;                               


下一部就是設置瀏覽器訪問變量及目錄訪問變量:

$site_name = $_SERVER[HTTP_HOST];
$url_dir = “http://”.$_SERVER[HTTP_HOST].dirname($_SERVER[PHP_SELF]);
$url_this =  “http://”.$_SERVER[HTTP_HOST].$_SERVER[PHP_SELF];

$upload_dir = “files/”;
$upload_url = $url_dir.”/files/”;
$message =””;


建立上傳目錄並相應改變權限:

if (!is_dir(“files”)) {
  if (!mkdir($upload_dir))
   die (“upload_files directory doesnt exist and creation failed”);
  if (!chmod($upload_dir,0755))
   die (“change permission to 755 failed.”);
}



用戶請求的處理:

if ($_REQUEST[del] && $DELETABLE)  {
  $resource = fopen(“log.txt”,”a”);
  fwrite($resource,date(“Ymd h:i:s”).”DELETE – $_SERVER[REMOTE_ADDR]”.”$_REQUEST[del]
“);
  fclose($resource);
  
  if (strpos($_REQUEST[del],”/.”)>0);                  //possible hacking
  else if (strpos($_REQUEST[del],”files/”) === false); //possible hacking
  else if (substr($_REQUEST[del],0,6)==”files/”) {
    unlink($_REQUEST[del]);
    print “<script>window.location.href=$url_this?message=deleted successfully</script>”;
  }
}
else if ($_FILES[userfile]) {
  $resource = fopen(“log.txt”,”a”);
  fwrite($resource,date(“Ymd h:i:s”).”UPLOAD – $_SERVER[REMOTE_ADDR]”
            .$_FILES[userfile][name].” “
            .$_FILES[userfile][type].”
“);
  fclose($resource);

$file_type = $_FILES[userfile][type];
  $file_name = $_FILES[userfile][name];
  $file_ext = strtolower(substr($file_name,strrpos($file_name,”.”)));

  //文件大小的檢查:


  if ( $_FILES[userfile][size] > $MAX_SIZE)
     $message = “The file size is over 2MB.”;
  //File Type/Extension Check
  else if (!in_array($file_type, $FILE_MIMES)
          && !in_array($file_ext, $FILE_EXTS) )
     $message = “Sorry, $file_name($file_type) is not allowed to be uploaded.”;
  else
     $message = do_upload($upload_dir, $upload_url);
  
  print “<script>window.location.href=$url_this?message=$message</script>”;
}
else if (!$_FILES[userfile]);
else
$message = “Invalid File Specified.”;

列出我們上傳的文件:

$handle=opendir($upload_dir);
$filelist = “”;
while ($file = readdir($handle)) {
   if(!is_dir($file) && !is_link($file)) {
      $filelist .= “<a href=$upload_dir$file>”.$file.”</a>”;
      if ($DELETABLE)
        $filelist .= ” <a href=?del=$upload_dir$file title=delete>x</a>”;
      $filelist .= “<sub><small><small><font color=grey>  “.date(“d-m H:i”, filemtime($upload_dir.$file))
                   .”</font></small></small></sub>”;
      $filelist .=”<br>”;
   }
}

function do_upload($upload_dir, $upload_url) {

$temp_name = $_FILES[userfile][tmp_name];
$file_name = $_FILES[userfile][name];
  $file_name = str_replace(“\”,””,$file_name);
  $file_name = str_replace(“”,””,$file_name);
$file_path = $upload_dir.$file_name;

//File Name Check
  if ( $file_name ==””) {
   $message = “Invalid File Name Specified”;
   return $message;
  }

  $result  =  move_uploaded_file($temp_name, $file_path);
  if (!chmod($file_path,0777))
    $message = “change permission to 777 failed.”;
  else
    $message = ($result)?”$file_name uploaded successfully.” :
            “Somthing is wrong with uploading a file.”;
  return $message;
}

?>

<center>
   <font color=red><?=$_REQUEST[message]?></font>
   <br>
   <form name=”upload” id=”upload” ENCTYPE=”multipart/form-data” method=”post”>
     Upload File <input type=”file” id=”userfile” name=”userfile”>
     <input type=”submit” name=”upload” value=”Upload”>
   </form>
   
   <br><b>My Files</b>
   <hr width=70%>
   <?=$filelist?>
   <hr width=70%>
   <small><sup>Developed By
   <a style=”text-decoration:none” href=”http://tech.citypost.ca”>CityPost.ca</a>
   </sup></small>
</center>

發佈留言