Search code examples
phpisset

$_POST and $_FILES are sent empty but isset() doesn't recognize


index.php passes firstName and an image to save.php via post. Save.php is checking $_POST and $_FILES to be not empty via isset method. when nothing is sent by POST it should give an error and dies but inside of if block never runs and if we print the array there is nothing in it. which means that nothing passed via $_POST or $_FILES.

when firstName and image are passed it works fine, but when nothing passed isset doesn't recognize it.why?

'error' field of $_FILES array has error code 4, which means 'No file was uploaded', in this case also if block should be execute but doesn't.

this is index.php

<form action="save.php" method="post" enctype="multipart/form-data">
  name: <input type="text" name="firstName"><br>
  pic: <input type="file" name="pic"><br>
  <input type="submit" value="register">
</form>

and here is the save.php:

<?php
if (!isset($_POST['firstName']) || !isset($_FILES['pic'])) 
{
  die('input error');
}

echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';

output:

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

)

Solution

  • When you submit a form you making a post request and you actually sending an empty string or file in your case. And $_POST['firstName'] exist as an empty string;

    Look at code blow:

    $variable = "";
    
    var_dump(isset($variable));
    // This returns true because $variable is set and has a value (an empty string).
    
    var_dump(empty($variable));
    // This returns true because $variable is considered empty. An empty string is considered empty.
    
    var_dump($variable == null);
    // This returns true because when comparing an empty string to null using the == operator, they are considered equal.
    
    var_dump(is_null($variable));
    // This returns false because an empty string is not considered null.
    
    var_dump($variable === null);
    // This returns false because the === operator checks for both value and type equality. $variable is a string, while null is a null value, so they are not identical.
    
    

    As you can see when you check with empty($variable) function it return true because it just check your $variable is null or not

    You might wonder why is_null($variable) returns false, It is because is_null($variable) also checks if the $variable type is equal to null or not; in this case the $variable type is string but the value is null

    So you can use do this:

    <?php
    if ( empty($_POST['firstName']) || $_FILES['pic']['error'] != 0) 
    {
      die('input error');
    }
    

    $_FILES['pic']['error'] will be equal to 0 if there is no errors

    You can find other error codes of $_FILES on php Documentation