得到我确信这是一个简单的问题,但似乎找不到一个有效的简单解决方案。我正在创建一个图片上传网站,我只想让JPEG和PNG成为允许的文件类型。这是我的PHP代码的开始,当用户在选择文件后点击“上传”按钮时运行。在此之后,我只有一长串的IF语句,这些语句都运行和运行。
非常感谢任何帮助。
if($ _FILES ['filename'] ['name'] ['size']){
session_start();
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
if($size < 2000000) {...
答案 0 :(得分:4)
我认为这样做
$allowed_types =array('jpg','png')
$userFile = $_FILES['filename']['name'];
$error = null;
// Get the file extension
$extension = pathinfo($userFile, PATHINFO_EXTENSION);
// Search the array for the allowed file type
if (in_array($extension, $allowed_types, false) != true) {
$error = "ERROR: ILLEGAL FILE TYPE";
return $error; // or use exit;
}
答案 1 :(得分:1)
检查上传文件的type属性。示例代码来自: http://www.php.net/manual/en/features.file-upload.php
/***
now verify the mime, i did not find
something more easy than verify the
'image/' ty^pe. if wrong tell it!
***/
if(!eregi('image/', $_FILES['attachement']['type'])) {
echo 'The uploaded file is not an image please upload a valide file!';
} else {
答案 2 :(得分:1)
我试过了..它帮助了我......
这也可以帮到你..
<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, PNG, JPEG and GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>