Jump to content

Recommended Posts

Hey,

 

I'm new to PHP and wanted to know what is the point of setting a  $_POST variables to an empty string before submitting a form. Like for example lets say I am creating a form that lets my add new users. In a tutorial I read, I would first have to initialize the variables. Example below

 

 


if (isset($_POST['submit'])) {

} else { // Form has not been submitted.
	$username = "";
	$password = "";
}

 

I don't get why we have to set  username and password to an empty string if the form hasn't been submitted. Can anyone please help me?  Thanks

If you use the variables without setting them, you will get a WARNING, but your script will run anyways. Rather than fill your log with WARNING messages, it's better practice to just set them to empties.

 

I usually set them to empty before the initial if statement.

$username = "";
$password = "";
if (isset($_POST['submit'])) {
  // Form has been submitted.
}

Now I don't have to worry about the 'else' segment.

 

This habit for me actually came from my C++ programming days, where the scope of a variable was much more restricted - anything initialized within curly brackets was unavailable outside those brackets.

Well, in the case you have provided, declaring those variables is redundant as if $_POST['submit'] is not reached, those variable will not be given any values, and therefore, will not be used in the remainder of the script (or can simply be checked using isset().

 

<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];

... stuff ...
}
echo (isset($username) ? $username : ''); // checks to see if $username has been set;

Think of initializing a variable as declaration.  If you don't initialize, your val will be null, but it's considered good practice to initialize before referencing that space in memory.

 

For example, if I say:

 

echo $username;

 

I'm echoing null (which equates to an empty string in PHP, because it uses dynamic typing).  But $username is not null because $username references an address in memory with a value of null, but because $username doesn't reference anything.

 

It's bad practice because the application doesn't know if you're intentionally referencing null or if you have a typo in your variable name.

 

If you enable strict error reporting, you'll be able to find typos that silently break your application in this way... but if you never initialize anything, you'll just get a lot of notices that don't help you at all.

 

Hope this helps.

This is probably a throw-back to C coding.  If you suddenly begin using an uninitialised variable in C, it could contain anything (whatever happened to be stored at that memory location when the program began running).

 

In C:

void main(void) {
  int i;
  i += 1;
  printf("%d", i);
}

could output anything, so the correct method would be:

void main(void) {
  int i=0;
  i += 1;
  printf("%d", i);
}

which would always output 1.

 

Of course, PHP auto-sets all new variables to NULL when they are first used, so it's not so much of a concern.  It is still considered good coding practise to initialise all variables though...

Think of initializing a variable as declaration.  If you don't initialize, your val will be null, but it's considered good practice to initialize before referencing that space in memory.

 

For example, if I say:

 

echo $username;

 

I'm echoing null (which equates to an empty string in PHP, because it uses dynamic typing).  But $username is not null because $username references an address in memory with a value of null, but because $username doesn't reference anything.

 

 

It's bad practice because the application doesn't know if you're intentionally referencing null or if you have a typo in your variable name.

 

If you enable strict error reporting, you'll be able to find typos that silently break your application in this way... but if you never initialize anything, you'll just get a lot of notices that don't help you at all.

 

Hope this helps.

 

 

Hey  smoseley,

 

Thank you for you explanation that makes sense. I just had a question about the following you said "But $username is not null because $username references an address in memory with a value of null, but because $username doesn't reference anything."

 

I didn't quite understand that... Can you please explain?

Well, in the case you have provided, declaring those variables is redundant as if $_POST['submit'] is not reached, those variable will not be given any values, and therefore, will not be used in the remainder of the script (or can simply be checked using isset().

 

<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];

... stuff ...
}
echo (isset($username) ? $username : ''); // checks to see if $username has been set;

 

Will it be a good idea to set those values to NULL instead of an empty string?

The main reasons behind initializing variables are basically

 

1) To prevent notice errors from appearing.

2) To ensure your variable have a known state.

 

For #1, removing the notice errors by setting the variables makes it so that PHP will have to spend less time reporting errors, not fill your logs up with these errors, and make the errors actually useful.  A lot of people handle these notices the wrong way, in that they just disable the message by turning down error reporting.  Contrary to popular believe this does NOT stop PHP from reporting the error, it merely stops it from echoing the message regarding the error.  All the error reporting mechanisms are still triggered and PHP wastes time doing things it doesn't need to be doing.    You should also keep your error reporting high so that you do see these notices during development.  It will help you greatly when it comes to identify if you made a typo in a variable name such as maybe doing $is_admin when you meant $isAdmin.

 

For #2, this ties into the register_globals setting.  If that setting is enabled then your users can set any variables they want by just adding them to the URL.  If you did not initialize your variables and did something such as:

if ($_POST['username'] == 'blah' && $_POST['password']=='bleh'){
  $isAdmin=true;
}

if ($isAdmin){
  //show super-secret world-destrying options.
}

 

Then all someone would have to do to gain admin access to your script is append ?isAdmin=1 to the URL.  There's no need for them to actually know the username and password because they can just set the variable directly.  If your povide an initialization then this no longer works as your initialization will over-write any value the user specifies:

 

$isAdmin = false;
if ($_POST['username'] == 'blah' && $_POST['password']=='bleh'){
  $isAdmin=true;
}

if ($isAdmin){
  //show super-secret world-destrying options.
}

 

The main reasons behind initializing variables are basically

 

1) To prevent notice errors from appearing.

2) To ensure your variable have a known state.

 

For #1, removing the notice errors by setting the variables makes it so that PHP will have to spend less time reporting errors, not fill your logs up with these errors, and make the errors actually useful.  A lot of people handle these notices the wrong way, in that they just disable the message by turning down error reporting.  Contrary to popular believe this does NOT stop PHP from reporting the error, it merely stops it from echoing the message regarding the error.  All the error reporting mechanisms are still triggered and PHP wastes time doing things it doesn't need to be doing.    You should also keep your error reporting high so that you do see these notices during development.  It will help you greatly when it comes to identify if you made a typo in a variable name such as maybe doing $is_admin when you meant $isAdmin.

 

For #2, this ties into the register_globals setting.  If that setting is enabled then your users can set any variables they want by just adding them to the URL.  If you did not initialize your variables and did something such as:

if ($_POST['username'] == 'blah' && $_POST['password']=='bleh'){
  $isAdmin=true;
}

if ($isAdmin){
  //show super-secret world-destrying options.
}

 

Then all someone would have to do to gain admin access to your script is append ?isAdmin=1 to the URL.  There's no need for them to actually know the username and password because they can just set the variable directly.  If your povide an initialization then this no longer works as your initialization will over-write any value the user specifies:

 

$isAdmin = false;
if ($_POST['username'] == 'blah' && $_POST['password']=='bleh'){
  $isAdmin=true;
}

if ($isAdmin){
  //show super-secret world-destrying options.
}

 

 

Wow. That is a really great analogy!  :D . I overlooked the fact that you can also set the variable to false.  So technically there are 3 ways to set the variables

 

$isAdmin = false;

$isAdmin = "";

$isAdmin = NULL

 

Which method is considered good practice and why?

$isAdmin = false;

$isAdmin = "";

$isAdmin = NULL

 

Which method is considered good practice and why?

What are you using it for?

 

Boolean, set it to FALSE.

Numbers, I set to 0, or if 0 might be used, NULL.

Strings, set it to "".

Arrays, set it to an empty array or to NULL.

etc...

 

I think you get the idea.

$isAdmin = false;

$isAdmin = "";

$isAdmin = NULL

 

Which method is considered good practice and why?

What are you using it for?

 

Boolean, set it to FALSE.

Numbers, I set to 0, or if 0 might be used, NULL.

Strings, set it to "".

Arrays, set it to an empty array or to NULL.

etc...

 

I think you get the idea.

 

Okay I see now... and last questions I have. What is the difference between initializing variables before an initial if statesmen or after an if statement , like the first example on my first post. 

 

Thanks for your help

Okay I see now... and last questions I have. What is the difference between initializing variables before an initial if statesmen or after an if statement , like the first example on my first post. 

Initializing before the initial 'if' statement works well if you might have a lot of nested 'if' statements. You might miss an 'else' statement somewhere, and initializing before will still have the value set.

 

On the other hand, you may want it to not be initialized so that you know that you missed something (isset comes back false, so you know you missed something.)

 

It also may occur that you don't bother initializing the variable in the 'else' component or before the if statement because you know you'll never use that variable, which could happen if you exit() because of a failure.

 

It's just personal preference.

Okay I see now... and last questions I have. What is the difference between initializing variables before an initial if statesmen or after an if statement , like the first example on my first post. 

Initializing before the initial 'if' statement works well if you might have a lot of nested 'if' statements. You might miss an 'else' statement somewhere, and initializing before will still have the value set.

 

On the other hand, you may want it to not be initialized so that you know that you missed something (isset comes back false, so you know you missed something.)

 

Yes that is true.. I agree with you! Thanks for your help!

 

It also may occur that you don't bother initializing the variable in the 'else' component or before the if statement because you know you'll never use that variable, which could happen if you exit() because of a failure.

 

It's just personal preference.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.