brad
brad

Reputation: 31

Error while retrieving files from server

<?php

if(isset($_POST['pic'])){

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 300000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {


    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);

      }
      echo "<h1>Done! Looks Great!</h1>";
    }
  }

else
  {
  echo "Invalid file";
  }
}
?>

<form action="editprofile.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<p>Image format should be png or jpg.</p>
<center><p class="submit"><input type="submit" name="pic" value="Upload Picture" /></p></center>
</form>
</div>


<p style="text-align:center; font-size:18px;">Current Picture</p>

<?php

$filename = $_FILES['file']['tmp_name'];

?>

<img src="/path/to/the/upload/folder/<?php echo $filename; ?>"/>
<img src="../../upload/foto.PNG" class="picture"/>

I am getting an error like undefined index - file.

Error is in the last few lines.

I basically have a folder which has an image. I want it to display the only image in the folder.

Upvotes: 0

Views: 156

Answers (1)

Karel Petranek
Karel Petranek

Reputation: 15164

If you open the page for the first time, no form has been sent yet and $_FILES is therefore empty. You try to access $_FILES even in case of first load. This is the faulty line:

$filename = $_FILES['file']['tmp_name'];

You should check that $_POST["pic"] is set before accessing the $_FILES variable (just as you have done on the top of the code).

Upvotes: 1

Related Questions