Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Form Upload Error When Input File Field Is Empty

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading