Hi all, very new to PHP (ie. only 2 days old!) so please be gentle!

I have a form with text fields and a file upload, and the php script I have is working wonders in regards to uploading the file and emailing the form data along with a link to the uploaded file.

However, I would like the file upload to be optional but at the moment if no file is selected I get an 'invalid file' error from the script. Any pointers or help?

The upload part of the script is as follows:

// Check filetype and size limits.
if ((($_FILES["uploaded_file"]["type"] == "image/gif")
|| ($_FILES["uploaded_file"]["type"] == "image/jpeg")
|| ($_FILES["uploaded_file"]["type"] == "image/pjpeg"))
&& ($_FILES["uploaded_file"]["size"] < 5000000))
  
  {
  if ($_FILES["uploaded_file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["uploaded_file"]["name"] . "<br />";
    echo "Type: " . $_FILES["uploaded_file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["uploaded_file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["uploaded_file"]["tmp_name"] . "<br />";

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

Thanks,

Matt.

Hi Matt,

You may want to read this first http://php.net/manual/en/features.file-upload.php.

The keywords for your question are if (empty($_FILES) && empty($_POST) && isset($_SERVER)

Please read the above link and try to integrate some of the methods they used. If still does not work for you, let us know and I will write the codes for you.

Thanks veedeoo, all sorted. The keywords you gave were extremely useful and pointed me in the direction I needed to go.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.