<?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"; } ?>
Restrict the format of image uploading—>Judge whether there is an error in uploading (1. Output the content in error, 2. Output the content correctly)—>Judge whether the picture is valid
The general idea is as written above, in addition This code can also be optimized. The optimized code:
<?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"]); } ?>
The second method uses functions, which is simpler and more beautiful to write, but not as easy to understand as the first method.
Next Section