So i want the user to only be able to upload docs or docx’s. So first here’s my html:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="img">
<input type="submit">
</form>
And here’s my php:
$allowedExts = array("doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ($extension!=".doc" || $extension!=".doc"
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
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("Proposals/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"Proposals/" . $_FILES["file"]["name"]);
echo "Stored in: " . "Proposals/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
Everytime I try to upload a file, whether it’s a doc or a png it outputs this:
Upload:
Type:
Size: 0 Kb
Temp file:
already exists.
And nothing ends up getting uploaded to the Proposals folder. So I have 2 questions:
1) what is the problem with my code?
2) it redirects to upload_file.php and displays a message. Is there a way to actually go back the main page and display text that it was successful?
The first question has already been answered so I won’t answer it again.
It is normally better to show the success message on the redirected page but you can solve this two ways:
header("Location: old_page.php");Also this is not the best way to get a file extension:
Try using pathinfo instead: http://php.net/manual/en/function.pathinfo.php
And your
ifstatement:Even though this is a tiny usage of
in_arrayI still would recommend taking that out and using a more practical method of searching arrays: http://php.net/manual/en/function.array-search.phpSo your
ifwould become something like: