1

I have a form for uploading data into my database.The form has a number of input fields ranging form text,number,textarea and file(images).

When the form is submitted, i check if there are any images being uploaded and if so, check if the image being uploaded passes a series of checks( below maximum file size, correct extension etc), with the entire process in a try/catch block set to throw exceptions should any check fail.

My checks are as follows:

$upload=$_FILES['Upload']['tmp_name'];
if(isset($upload))
{
    if(!empty($upload) && is_uploaded_file($upload))
    {
        //Checks file size,extension and uploads the file
    }
    else
    {
        //throw new Exception
    }
}
else
{
    //throw new Exception
}

However, when using the above, isset would return true, even when no files are being uploaded.Upon some googling and looking on stack overflow, specifically isset and !empty not passing through a check for uploaded files , where it is stated that isset will return true due to $_FILES being a superglobal, i looked around for a solution and eventually settles on file_exists() as a replacement for isset() in my code.

My rationale for using file_exists() is that file that are uploaded(submitted) will be stored in a temp directory during the upload process, and if i check for this temp directory, i would thus be able to ascertain if a file is really uploaded.

After replacing isset() with file_exists my code is now working fine, but i am wondering if this is the correct way to proceed, or if there are any other better alternatives.

I look forward to any opinions and/or advice.

Community
  • 1
  • 1
Kenneth .J
  • 1,433
  • 8
  • 27
  • 49

2 Answers2

0

I would use the error-code given by $_FILES:

if($_FILES['Upload']['error'] == UPLOAD_ERR_OK) {
    //seems to have worked
}

There are even other error-codes you could check against, for example if the file was to big etc.

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
0
$upload=$_FILES['Upload']['tmp_name'];
if($upload)
{}

This will give the file temp name or null.

JohnTaa
  • 2,722
  • 2
  • 15
  • 15