<?php if (in_array($_FILES["file"]["type"], array("image/gif", "image/jpeg","image/jpg"))) { //对上传图片格式进行限定 if ($_FILES["file"]["error"] > 0) //由文件上传导致的错误提示代码 { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; //错误输出 } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //正确输出 echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) //对上传至文件夹upload的文件进行判断 { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], // 存储在服务器的文件的临时副本的名称 "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>
限制圖片上傳的格式—>判斷上傳是否出錯(1.出錯輸出內容,2.正確輸出內容)—>判斷圖片是否有效
#總體思路就是上面寫的,另外這段程式碼還可以進行最佳化,優化後程式碼:
<?php if (count($_FILES)) { $retFiles = uploadFile("file"); if ($retFiles['status'] == 1) { echo $retFiles['message']; } else if ($retFiles['status'] == 0) { echo "Upload: " . $retFiles["name"] . "<br />"; echo "Type: " . $retFiles["type"] . "<br />"; echo "Size: " . ($retFiles["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $retFiles["temp"] . "<br />"; echo "Stored in: " . "upload/" . $retFiles["name"]; } } function uploadFile($fileName) { $files = $_FILES[$fileName]; if (!in_array($files["type"], array("image/gif","image/jpeg","image/pjpeg","image/jpeg", "image/png"))) { return array("status" => 1, "message" => "Uploaded image format is not correct"); } if ($files["error"] > 0) { return array("status" => 1, "message" => "upload error"); } if (file_exists("upload/" . $files["name"])) { return array("status" => 1, "message" => $files["name"]." already exiss"); } move_uploaded_file($files["tmp_name"], "upload/".$files["name"]); return array("status" => 0, "name" => $files["name"], "type" => $files["type"], "size" => $files['size']/1024, "temp" => $files["tmp_name"]); } ?>
第二種方法使用函數的方法,寫法更簡單,美觀,但是沒有第一種容易理解。
下一節