Home > database >  PHP Form Upload Error When Input File Field Is Empty
PHP Form Upload Error When Input File Field Is Empty

Time:11-30

Here is the code for a form that will recreate the issue:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ) { 
    print_r($_FILES['fileToUpload']);

    if (!file_exists($_FILES['fileToUpload']['tmp_name']) || !is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) 
        $primaryImage = file_get_contents($_FILES['fileToUpload']['tmp_name']);
}
?>
<form method="post" enctype="multipart/form-data"> 
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image">
</form>    

enter image description here

When clicking "Upload Image" with no file uploaded, PHP 8 will create this error (I've included the print_r($_FILES['fileToUpload']) output for reference).

Array ( [name] => [full_path] => [type] => [tmp_name] => [error] => 4 [size] => 0 )

Fatal error: Uncaught ValueError: Path cannot be empty in C:\xampp\htdocs\cole\cms\phpExample.php:6 Stack trace: #0 C:\xampp\htdocs\cole\cms\phpExample.php(6): file_get_contents('') #1 {main} thrown in C:\xampp\htdocs\cole\cms\phpExample.php on line 6

I have tried to wrap the issue in a try...catch... block, various checks like the if statement in the above to check for the emptiness of the path. Note, if you upload a file in the form and then click submit, no error will occur.

How can I prevent an error from being thrown while checking the presence of the $_FILE['my_file'] information in PHP 8?

CodePudding user response:

You can check with:

if($_FILES['fileToUpload']['size'] > 0){
// code here
}

which will ensure that you have submitted a file, and its size is not 0

  •  Tags:  
  • php
  • Related