Need Help with PHP Uploading Image and PDF File Types
How do I set the form restrictions in php to only allow jpgs and pdfs for upload? Also, I seem to have an upload error when I set the file size to 800000. Here is the upload form:
<form action="upload_files.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<label for="pdf_doc">Your PDF:</label>
<input type="file" name="pdf_doc" id="pdf_doc" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
Here is the upload_files.php
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Return Code: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["img_preview"]["name"] . "<br />";
echo "Type: " . $开发者_如何转开发_FILES["img_preview"]["type"] . "<br />";
echo "Size: " . ($_FILES["img_preview"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["img_preview"]["tmp_name"] . "<br />";
//check the file into its room
if (file_exists("upload/" . $_FILES["img_preview"]["name"]))
{
echo $_FILES["img_preview"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_FILES["img_preview"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["img_preview"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
This is the upload code for the img_preview file. I would create another one for the pdf_doc file, but this one is not working right at the moment.
So, how do I increase the filesize limit to 8MB? And, for the pdf upload I would like to restrict the file type to pdf, jpg, or gif. So, I tried this as the parameters:
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
|| ($_FILES["img_preview"]["type"] == "application/pdf"))
&& ($_FILES["img_preview"]["size"] < 80000))
but again errors. What's the fix? Is there a more fluid way to do this?
File type problem
Since the MIME type reported by the browser (which is what you get in $_FILES
) can be spoofed, you can't rely on it. This leaves you with two reasonable options:
- Filter by file extension
- Filter using
finfo_file
Unfortunately finfo_file
is not included by default on PHP < 5.3, so this leaves you with the extension check (which has worked just fine for me in the past), or using the discontinued PECL package finfo.
Max upload size problem
There are many PHP settings that influence this, and you need to tweak all of them to have big uploads work. Fortunately, for some time now the PHP docs have a page where everything related to file upload that can cause problems is discussed.
精彩评论