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