简体   繁体   中英

isset PHP5 is facultative or not

Why we use isset here with !empty ?
Is it necessarily to use it because isset check whether the variable is set or not and $_POST is a superglobal variable already set.

 <?php
    include 'Config.php';
    $email  = "";
    $mdp    = "";
    $e = array();
    if(isset($_POST))
    {
     if(!empty($_POST))
     {
      $email  = $_POST['adresse_email'];
      $mdp    = $_POST['motpasse'];
   ...

isset() checks if the variable exists, but not it's content.

You use empty() later to check if it's an empty string.

In this case, since $_POST is an array, and you're not saying which position to pick the value from, empty() will check if the array contains any positions.


As mentioned in the comments by Armen , those two verifications are pointless. You could simply check if the request method of the script is POST

 if ($_SERVER['REQUEST_METHOD'] === 'POST') 

In your example isset() is used to check if the $_POST superglobal variable is set, but it's redundant code. empty() already includes the functionality of isset() but also does more. From the documentation:

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following things are considered to be empty:

 "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value) 

... so it will also check if the $_POST array has elements in it (is not an empty array).

For a simple web form checking, using !empty($_POST) is easier than writing $_SERVER['REQUEST_METHOD'] === 'POST' , but the result is the same, if the request was not made through POST, none of them will match.

Additionaly, in your code, you could use isset() on the $_POST elements also to rule out the warnings issued by PHP if an index is not defined (if an element wasn't submitted in the form):

$email  = isset($_POST['adresse_email']) ? $_POST['adresse_email'] : '';
$mdp    = isset($_POST['motpasse']) ? $_POST['motpasse'] : '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM