<?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"]); } ?>
第二种方法使用函数的方法,写法更简单,美观,但是没有第一种容易理解。
下一节