PHP文件上傳小程序 適合初學者學習!

這篇文章主要爲大家詳細介紹了PHP文件上傳小程序,給初學者提供的PHP文件上傳小程序,具有一定的參考價值,感興趣的小夥伴們可以參考一下

本文實例爲大家分享了PHP文件上傳小程序的具體代碼,供大家參考,具體內容如下

廢話略過,直接上代碼:

首先前端代碼:index.html

<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 <title>文件上傳Demo</title>
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">  
 <table border=0 cellspacing=0 cellpadding=0 align=center width="100%">  
 <tr>  
  <td width=55 height=20 align="center">
  <input type="hidden" name="MAX_FILE_SIZE" value="2000000">文件: 
  </td>  
  <td height="16">  
  <input name="file" type="file" value="瀏覽" />       
  <input type="submit" value="上傳" name="submit" />  
  </td>  
 </tr>  
 </table>  
</form>
</body>
</html>

接下來是重點:upload.php

<?php
/**
 * @title 文件上傳示例
 * @author FeoniX
 */
header("Content-Type:text/html; charset=utf-8");
if($_POST['submit']){
 $upfiles = new Upload();
 $upfiles->upload_file();
}
class Upload{
 public $upload_name; //上傳文件名
 public $upload_tmp_name; //上傳臨時文件名
 public $upload_final_name; //上傳文件的最終文件名
 public $upload_target_dir; //文件被上傳到的目標目錄
 public $upload_target_path; //文件被上傳到的最終路徑
 public $upload_filetype ; //上傳文件類型
 public $allow_uploadedfile_type;//允許的上傳文件類型
 public $upload_file_size; //上傳文件的大小
 public $allow_uploaded_maxsize=10000000;//允許上傳文件的最大值
 //構造函數
 public function __construct()
 {
 $this->upload_name = $_FILES["file"]["name"]; //取得上傳文件名
 $this->upload_filetype = $_FILES["file"]["type"];
 $this->upload_tmp_name = $_FILES["file"]["tmp_name"];
 $this->allow_uploadedfile_type = array('jpeg','jpg','png','gif','bmp','doc','xls','csv','zip','rar','txt','wps');
 $this->upload_file_size = $_FILES["file"]["size"];
 $this->upload_target_dir="./upload";
 }
 //文件上傳
 public function upload_file()
 {
 $upload_filetype = $this->getFileExt($this->upload_name);//獲取文件擴展名
 if(in_array($upload_filetype,$this->allow_uploadedfile_type))//判斷文件類型是否符合要求
 {
  if($this->upload_file_size < $this->allow_uploaded_maxsize)//判斷文件大小是否超過允許的最大值
  {
  if(!is_dir($this->upload_target_dir))//如果文件上傳目錄不存在
  {
   mkdir($this->upload_target_dir);//創建文件上傳目錄
   chmod($this->upload_target_dir,0777);//改權限
  }
  $this->upload_final_name = date("YmdHis").rand(0,100).'.'.$upload_filetype;//生成隨機文件名
  $this->upload_target_path = $this->upload_target_dir."/".$this->upload_final_name;//文件上傳目標目錄
  if(!move_uploaded_file($this->upload_tmp_name,$this->upload_target_path))//文件移動失敗
  {
   echo "<font color=red>文件上傳失敗!</font>";
  }
  else
  {
   echo "<font color=green>文件上傳成功!</font>";
  }
  }
  else
  {
  echo("<font color=red>文件太大,上傳失敗!</font>");
  }
 }
 else
 {
  echo("<font color=red>僅支持一下文件類型,請重新選擇:<br>".implode(',',$this->allow_uploadedfile_type)."</font>");
 }
 }
  /**
   *獲取文件擴展名
   *@param String $filename 要獲取文件名的文件
   */
  public function getFileExt($filename){
   $info = pathinfo($filename);
   return @$info["extension"];
  }
}
?>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章