Reputation: 2543
I am trying to retrieve the path of an image that I upload in the html page using php, but when i use the method $_FILES['file1']['tmp_name'] it displays an error saying "undifined index: file1". This is the code I am trying: HTML:
<form name="form1" method="GET" action="image.php">
<br/>
<input type="file" name="file1"/>
<input type="submit" value="submit"/>
</form>
PHP:
<?php
$files=$_FILES['file1']['tmp_name'];
$folder="images";
if(is_uploaded_file($_FILES['file1']['tmp_name']))
{
move_uploaded_file($_FILES['file1']['tmp_name'], $folder . '/'.$_FILES['file1']['name']);
$image=$folder . '/'.$_FILES['file1']['name'];
echo "Successfully Uploaded";
echo $image;
}
else
die("Not Uploaded");
?>
Upvotes: 1
Views: 833
Reputation: 74217
Uploading files require a POST method and not a GET.
Consult:
Also make sure the folder you are wanting to upload to, has proper permissions to write to it.
Sidenote edit: Plus, as stated in the other answer, a valid enctype is required.
I'd also use:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){...}
In order to ensure of a POST method, while using full bracing for your else
and adding another else{...}
for the above.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$files=$_FILES['file1']['tmp_name'];
$folder="images";
if(is_uploaded_file($_FILES['file1']['tmp_name']))
{
move_uploaded_file($_FILES['file1']['tmp_name'], $folder . '/'.$_FILES['file1']['name']);
$image=$folder . '/'.$_FILES['file1']['name'];
echo "Successfully Uploaded";
echo $image;
} else {
die("Not Uploaded");
}
} else{
echo "A POST method was not used here.";
}
Also a conditional !empty()
against your file input.
Upvotes: 3
Reputation: 1165
Change:
<form name="form1" method="GET" action="image.php">
to
<form name="form1" method="POST" enctype="multipart/form-data" action="image.php">
Upvotes: 2