PHP文件上傳

PHP編程語言中的常見的$_FILES系統(tǒng)函數(shù)用法有:

$_FILES['myFile']['name'] 顯示客戶端文件的原名稱。
$_FILES['myFile']['type'] 文件的 MIME 類型,例如"image/gif"。
$_FILES['myFile']['size'] 已上傳文件的大小,單位為字節(jié)。
$_FILES['myFile']['tmp_name'] 儲(chǔ)存的臨時(shí)文件名,一般是系統(tǒng)默認(rèn)。
$_FILES['myFile']['error'] 該文件上傳相關(guān)的錯(cuò)誤代碼。以下為不同代碼代表的意思:
0; 文件上傳成功。
1; 超過了文件大小php.ini中即系統(tǒng)設(shè)定的大小。
2; 超過了文件大小MAX_FILE_SIZE 選項(xiàng)指定的值。
3; 文件只有部分被上傳。
4; 沒有文件被上傳。
5; 上傳文件大小為0。

前端

<form action="accept-file.php" method="post" enctype="multipart/form-data">
    Your Photo: <input type="file" name="photo" size="25" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>

后端

<?php
$valid_file = true;
//if they DID upload a file...
if($_FILES['photo']['name'])
{
    //if no errors...
    if(!$_FILES['photo']['error'])
    {
        //now is the time to modify the future file name and validate the file
        $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
        if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
        {
            $valid_file = false;
            $message = 'Oops!  Your file\'s size is to large.';
        }
        
        //if the file has passed the test
        if($valid_file)
        {
            $new_file_name = $_FILES["photo"]["name"];
            echo "Upload: " . $_FILES["photo"]["name"] . "<br />";
            echo "Type: " . $_FILES["photo"]["type"] . "<br />";
            echo "Size: " . ($_FILES["photo"]["size"] / 1024) . " Kb<br />";
            echo "Stored in: " . $_FILES["photo"]["tmp_name"] . "<br />";
            
            //move it to where we want it to be
            move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
            $message = 'Congratulations!  Your file was accepted.';
        }
    }
    //if there is an error...
    else
    {
        //set that to be the returned message
        $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
    }
}
echo $message;
?>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容