How to validate file upload field?
I can't seem to validate file upload fields, here's my code:
<?php
if (isset($_POST['submit'])) {
if ($_POST['uploadFile']) {
echo "File uploaded";
} else {
echo "No file attempted to be uploaded";
}
}
?>
<form action="" method="post" 开发者_运维技巧enctype="multipart/form-data">
<input type="file" name="uploadFile" />
<input type="submit" name="submit" />
</form>
What is the mistake I'm making?
EDIT
Came up with my own solution, may not be the best but it works:
if (isset($_POST['submit'])) {
$fileUpload = $_FILES['uploadFile'] ['name'];
if (strlen($fileUpload) > 0) {
echo "File uploaded.";
} else {
echo "No File attempted to be uploaded.";
}
}
the superglobal your are looking for is $_FILES.
var_dump($_FILES); //to see what's happening with the uploaded files
To make sure a POST request is made you can use the following lines:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//A post request!
}
As far as validation, take a look at is_uploaded_file()
and read up on Handling File Uploads.
In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_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 "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
In file uploads with PHP, i think $_FILES[$file]['error'] is your best friend! it breaks it down in 8 possible scenarios, 0 meaning file upload went ok, so something like hereinafter should do the trick
if($_FILES[$file]['error']==0)
// proceed
else
switch($_FILES[$file]['error'])
// debugging
精彩评论