一個簡單的PHP檔案上傳樣本程式

來源:互聯網
上載者:User
 代碼如下 複製代碼

<?php

// 定義提示函數

function alert($msg){

return '<script type="text/javascript">alert("'.$msg.'");window.history.back(-1);</script>';

}


// 定義允許的檔案類型

$allowType = array('image/jpeg','image/gif','image/jpg');


// 定義路徑,可以是絕對路徑,或者相對路徑都可以

$filePath = './uploadFileDir/';

 

// 接收表單資訊 其中裡邊寫的 file 值是 靜態頁form表單裡的name值

$file = $_FILES['file'];

 

// 第一步,判斷上傳的檔案是否有錯誤

if( $file['error'] !== 0 ){

exit(alert('檔案上傳錯誤'));

}

 

// 第二步,判斷檔案大小,這裡的102400是位元組,換算為kb就是100kb

if( $file['size'] > 102400 ){

exit(alert('檔案過大'));

}

 

// 第三步,判斷檔案類型

if( !in_array(mime_content_type($file['tmp_name']),$allowType) ){

exit(alert('檔案類型錯誤'));

}

 

// 第四步,判斷路徑是否存在,如果不存在則建立

if( !file_exists($filePath) && !mkdir($filePath,0777,true) ){

exit(alert('建立目錄錯誤'));

}

 

// 第五步,定義上傳後的名字及路徑

$filename = time().'_'.$file['name'];

 

// 第六步,複製檔案

if( !copy($file['tmp_name'],$filePath.$filename) ){

exit(alert('上傳檔案出錯,請稍候重試'));

}

 

// 第七步,刪除臨時檔案

unlink($file['tmp_name']);

 

// 提示上傳成功

echo alert('恭喜,上傳檔案['.$filename.']成功!');
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.