I've tried to fix this for ages, but when I try to upload a file I get an "undefined index
" notice. Any help would be great! I get the error on line 38 if that helps, also I think it might be something to do with my form too.
HTML form:
<form action="UploadFileCodeImage.php" method="post"enctype="multipart/form-data">
Upload image (JPG, JPEG, PNG, or GIF):<br/>
<input type="file" name="file" id="file"><br/>
<input type="submit" value="submit" name="file">
</form>
PHP:
<?php
$destination = "C:\xampp\htdocs\Uploaded files\CS\Image";
$target_file = $destination . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$filetype = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = filesize($_FILES["file"]["Temp"]);
if($check !== false) {
echo "Voila! - " . $check["file"];
$uploadOk = 1;
} else {
echo "Error!";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 50000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($filetype != "jpg" && $filetype != "png" && $filetype != "jpeg"
&& $filetype != "gif") {
echo "Sorry, only JPG, JPEG, PNG, 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["file"]["Temp"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Error!";
}
}
?>
Let me outline the errors in your code.
You have two form elements bearing the same name, "file"; that's a conflict.
<input type="file" name="file" id="file">
^^^^^^^^^^^
and
<input type="submit" value="submit" name="file">
^^^^^^^^^^^
Then your conditional statement if(isset($_POST["submit"]))
is based on a submit button being named "submit"; it doesn't exist, so nothing in there will be executed.
Therefore, rename your submit button to that, "submit".
Then you have ["Temp"]
which is invalid, all of those should read as ["tmp_name"]
as per the manual:
which is present in
$check = filesize($_FILES["file"]["Temp"]);
and
if (move_uploaded_file($_FILES["file"]["Temp"], $target_file)) {
Then there's this line:
$destination = "C:\xampp\htdocs\Uploaded files\CS\Image";
there should be two trailing slashes (edit)
$destination = "C:\xampp\htdocs\Uploaded files\CS\Image\\";
since $destination . basename($_FILES["file"]["name"]
will translate as folderImage.jpg
where it should be folder/Image.jpg
, otherwise it will result in an error.