PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

[FIXED] If condition is meet but is ignored in PHP code

 February 22, 2022     if-statement, isset, php     No comments   

Issue

I have the following code to validate if a username is entered:

 if (!isset($_POST['username']) ) {
    
    header("location: index.php");
    $error_message = "Please enter your Username and Password!";
    exit();
 }

If I don't enter any value in the username field, the condition turns out false and would execute the code inside the if statement and similar situation when I enter a username!

Any idea why this is happening?


Solution

If you have a form with an <input name="username"> then this input will always have some sort of value. If you don't enter anything, the value is still the empty string. And of course that empty string is posted to the server.

On the other hand PHP isset checks

"if a variable is declared and is different than null"

And of course this is true even for the empty string (ie username exists and it's different from null). If you want to catch all situations where your username is either not existing at all or an empty string you can for instance do as follows

if (!isset($_POST['username']) || trim($_POST['username']) === '' )

or you can use

if (strlen($_POST['username']) == 0)


Answered By - derpirscher
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing