My Form is simple and I thought the uploading php was simple, but when i test it the results are unusual. I can upload any file and any size and it will Work. I thought i had written it to restrict certain files and sizes...Where am I going wrong?
Form:
<form enctype="multipart/form-data" action="upload_file.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
upload_file.php:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok = 1;
$uploaded = $_POST['uploaded'];
//This is our size condition
if ($uploaded_size > 3000){
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type == "text/php"){
echo "No PHP files are allowed for upload.<br>";
$ok = 0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok == 0){
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "Sorry, there was a problem uploading your file.";
}
}
Your code is outright wrong. Nowhere do you define $uploaded_size
, $uploaded_type
, etc... so the code boils down to:
if ($uploaded_size > 3000 {
is equivalent to
if (0 > 3000) { // undefined variables are typecast to 0
which evaluates to false, so $ok
stays 1
and no error is triggered.
I STRONGLY suggest you read the PHP manpages on handling file uploads: http://php.net/manual/en/features.file-upload.php
you need to use it like
if ($_FILES["file"]["size"] > 3000) ...
or define $uploaded_size = $_FILES["file"]["size"] before the check. Also similarly you would need to use $_FILES["file"]["type"]
$uploaded_size = $_FILES["file"]["size"];
$uploaded_type = $_FILES["file"]["type"];
...
Try this:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok = 1;
$uploaded = $_POST['uploaded'];
//This is our size condition
if ($uploaded_size > 3000){
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type == "text/php"){
echo "No PHP files are allowed for upload.<br>";
$ok = 0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok == 0){
Echo "Sorry your file was not uploaded";
die();
}
//If everything is ok we try to upload it
else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "Sorry, there was a problem uploading your file.";
die();
}
}
Adding the die()
function tells the code to stop. Also, where is your $uploaded_type and $uploaded_size var ?