I my login form if I dont check remember me check box in php script it gives <b>Notice</b>: Undefined index: autologin in error. in my .php file I have
$check_autologin = $_POST['autologin']; And I am checking is user checked it
if($check_autologin == 1)
{
$password_hash = $encrypted_mypassword;
setcookie ($cookie_name, 'usr='.$username.'&hash='.$password_hash, time() + $cookie_time);
}
and this is my check box field <input type="checkbox" name="autologin" value="1">Remember Me<br />
How could check box can return any default value if it is not checked?
I suspect the problem is when your checkbox is not checked the value doesn't exist in the $_POST array.
Try insulating your value check by using
isset( $_POST['autologin'] )
thusly:
$check_autologin = false;
if( isset( $_POST['autologin'] ) ) {
$check_autologin = $_POST['autologin'];
}
Undefined Index means that you're asking PHP to tell you the value of an array element that doesn't exist.
It is a 'Notice', which means it isn't a fatal error and doesn't stop the program from running, but is a good idea to fix. (it is also possible to set PHP so it doesn't report Notice-level events, but again, better just to fix the problem)
How to fix it?
a) As already suggested, check whether it's been set before you check what the value is.
So rather than just saying if($_POST['x']) say if(isset($_POST['x]) && $_POST['x'])
b) Explicitly supress the warning. PHP allows you to do this with the # symbol.
So you would say if(#$_POST['x'])
c) Ensure that you only ever make reference to variables that you know have been set. This would mean a different approach to your code, but could be a start toward making it more robust in general.
For example, rather than looking directly at the $_POST values you're expecting, you could write a foreach($_POST) loop which allows you to inspect everything in $_POST. This would also allow you to spot when someone posts values you're not expecting to receive.
Related
I checked all 29 previous posts tagged with array_key_exists and I cannot find a specific question answered that deals with my issue. Our server has recently been updated and we've advanced to PHP 5.2.17 (and yes I know that's still behind, but we're fixing issues as we continue to advance, and 5.3 caused way too many issues for handling at once, let alone 5.4).
Our webpages are throwing an error message tied to array_key_exists:
[ERROR][2][array_key_exists() [function.array-key-exists]: The second
argument should be either an array or an object]
else if(array_key_exists("ACCOUNT", $_SESSION) && $_SESSION["ACCOUNT"] == $target){
// do nothing, we are a-ok
}
In the above code (I think) we're checking to see if a session has already been set and exists for the present account. If so we do nothing. Otherwise we set the session in another else statement after this.
$_SESSION["ACCOUNT"] is being set in a cookie. The value "ACCOUNT" is the subdomain which is also used to identify the account in the database. Here are the lines from the cookie which shows the account is set. The account does exist.
SESSION[ACCOUNTID] = 39
SESSION[ACCOUNT] = demo
SESSION[PAIDACCOUNT] = 0
My question is how should that line of php now be coded so as not to throw that error?
Thanks!
You should use isset instead
else if(isset($_SESSION["ACCOUNT"]) && $_SESSION["ACCOUNT"] == $target){
// do nothing, we are a-ok
}
So I am using the following style of code if(array_key_exists('some_value', $_POST)){echo 'hi';}
For PHP 5.2.17 I am getting a warning from this style of code. This is the warning:
WARNING: argument 2 for array_key_exists() is not either an array or an object on line: 123
This seems strange to me because I believe that the $_POST array should always be defined. Is that not the case? I'm not sure what would cause the $_POST array to not be considered an array. I am not resetting $_POST to anything so it should exist as an array at all times. Does anyone have any idea what is wrong. Please let me know if more information is needed and thank you for the help.
Edit: I should note that this only happens on the production server. My local environment does not have this problem.
The Superglobals $_POST and $_GET are only populated if the script is POSTed to or GET from. In your example, the reason that you'd get that error is if there was not post action to the script. Before checking for a certain post value, you should check to make sure there was a post:
if(isset($_POST)) {
//The form was posted
}
In that fashion. From there, you can check for certain values using array_key_exist, or you can further check isset($_POST['myKey']).
Use if(isset($_POST['some_value'])) { echo 'hi'; } instead. Never had a problem with it.
Also check if you are not overriding or unsetting $_POST (or some framework you are using is doing it for you). I avoid to do so with superglobal variables since I think it is a bad practice and might give headaches like this one.
how can I prevent PHP from returning an Undefined variable error every time I try to check a variable if it has contents and that certain variable hasn't been used yet? In my previous setup, I can check $_POST['email'] even if I haven't put anything into it yet. It simply returns a blank or empty result. That's how I want my PHP setup to work but for the life of me, I can't seem to find figure out how to configure it. :(
Example:
<?php
if ($_POST['info'] != '') {
// do some stuff
}
?>
<form method="post">
<input type="text" name="info" />
<input type="submit" />
</form>
When you use the above script in a single PHP page and run it on my current setup, it returns an Undefined variable error. On my previous setup, that script worked like a charm. Can anyone share some light into this problem of mine. If you need further details, just say so and I will try to add more details to this post.
I know about the isset() checking but I don't want to use it on all of my scripts. I want it to not be that restrictive about variables.
You could use the empty function, which returns true if the variable is either unset or empty (i.e. a zero-length string, 0, NULL, FALSE and so on):
if(!empty($_POST['variable'])){
/* ... */
}
This is pretty much the same test as the one you're doing now, except that it will also return false (not run the block), without warnings, when the variable is unset.
Most likely it's not an error, but a Warning. You can set PHP not to display errors/warnings if you want. Just add this to the begining of your code:
ini_set('display_errors', 0);
Altough, I recommend you not to be lazy and have your code not display any errors, warnings, notices whatsoever, better safe than sorry.
And the preferred way to do what you want to do is
<?php
if (isset($_POST['info'])) {
// do some stuff
}
?>
<form method="post">
<input type="text" name="info" />
<input type="submit" />
</form>
I have sometimes done the following to do a comparison and avoid the warning about an unset variable:
if( #$_POST['variable'] == 'value' )
{
...
}
Although PHP would still call custom error handlers, so perhaps I need to reconsider this strategy.
Are you using your own Server? If so you can change the error_reporting via PHP.INI. Above the line
"error_reporting = E_ALL;" (might not be E_ALL) There will be a small documentation explaining which type of errors you can show.
If you're using a shared server from a webhosting company, I believe some may offer quick PHP management under your Webhosting account CP.
I hope I helped ;/
ps- If you do have your own server, you'll have to restart Apache. I'm not sure how it's done in Ubunto (if that's what you're using) but for CentOS it's:
/sbin/service httpd restart
The variable will be always SET as long as you sent the form .
So its better to check of the variable is not empty.
if(!empty($_POST['var']))
If you want to set $_POST vars, having a whole lot of these statements really clutters your code:
if (isset($_POST['info']))
$info = $_POST['info'];
... etc....
How about this?
function setPostVar( &$v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
eval("\$v = isset(\$_POST[\"$match[1]\"])?\$_POST[\"$match[1]\"]:'';");
}
Now, as long as you are happy naming variables similar to your POST vars
ie. $Foo = $_POST['Foo'];
you can just do this:
setPostVar($Foo); // equivalent to if(isset($_POST['Foo']) $Foo = $_POST['Foo'];
setPostVar($Bar); // ditto
setPostVar($Baz); // ditto
I'm trying to build a registration system using PHP and the AJAX components of jquery.
My jQuery takes the values of the username and password fields and makes a POST request to the PHP script, which grabs the values using $_POST and saves them to the database.
Of course, i'm wanting to make sure that there aren't any duplicate usernames, and beyond using the PHP mysql_error() function, i wasn't sure how to do this.
So i want to set my PHP to first check for entries in the database with the username the person enters in the form, if it exists, i'd like to return a custom error message to the user using the php return() feature.
How can i use jQuery to first POST the values to the script, and then return any data/ custom error messages that i am creating with return();
By the way, security is not an issue here.
Simplest way would be to make a page, for example, post.php. post.php will do all the checking and stuff you want and, I know you want to use return, but just echoing the stuff back would be the absolute easiest. So, echo any error or even a value (for example, you can echo back -1 for a false or a 1 for a true).
The jQuery side is pretty simple:
$('form').submit(function(){
$.post('post.php',{username:$('#username').val(),password:$('#password').val()},function(data){
//username and password == $_POST['username'] && $_POST['password']
//data will now equal anything you echo back. So, lets say you did as my example and used -1 for an error
if(data==-1){alert('ERROR');}
});
return false;
});
If there is an error you will get an alert otherwise nothing will happen at all. Now you could do an else{} and have whatever you want for if there is no error.
I'm new to PHP so I apologize if this is a simple problem...
I am moving a PHP site from one server to another. The new server is IIS 7.0, PHP 5.2.1, with short open tag turned "On", and I don't know how the original server was set-up (I was just given the code).
The following is the very first section of code on one of the pages:
<?
ob_start();
session_start();
if($_GET['confirm'] == 13 || $_GET['confirm'] == 14 || $_GET['confirm'] == 15 || $_GET['confirm'] == 16)
{
include("test/query/test_query.php");
}
?>
When this page executes, the following error is always shown:
PHP Notice: Undefined index: confirm in [file location].php on line 6
Also, users access this page by being redirected from the home page (which is a standard HTML page). The full URL when properly navigated to is the following:
http://www.[site].com/test.php#login
... I understand why the error is thrown. What I don't understand is how this code could ever work as it does on the original server. Could I be missing a configuration setting?
*This same issue happens in dozens of locations all over the site. This is just one specific occurrence of the issue.
The new server has error_reporting set to E_ALL. What you're seeing is a notice, not an error. Try:
error_reporting(E_ALL ^ E_NOTICE)
With error reporting set to E_ALL, accessing a member of an array which is not set generates an error. If you don't wish to lower your error reporting level, before checking $_GET['var'], change your code to:
if(isset($_GET['confirm']) && ($_GET['confirm'] == 13 || $_GET['confirm'] == 14 || $_GET['confirm'] == 15 || $_GET['confirm'] == 16)) {
by adding the call to isset() before you actually access $_GET['confirm'], you will verify that you're not accessing an array member which is not set. ($_GET['confirm'] will only be set if the URL ends in ?confirm=... or ?something...&confirm=...)
I suggest to optimize the code for reading:
if (isset($_GET['confirm']) && ($_GET['confirm'] >= 13 && $_GET['confirm'] <= 16))
And I totally agree with Josh's proposal.
Since there is no index $_GET['confirm'], PHP throws a notice that you are looking at an undefined index. The notice is being displayed because the new server has the E_NOTICE flag set in error_reporting somewhere, either in php.ini or in some config file or bootstrap that is run on pageloads.
From the php manual, E_NOTICE: "Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script."
You can either try turning off the notices if you aren't worried about them, or use them to track down places where there may be problems.
For the code you posted, an easy fix would be to change the conditional to
if(isset($_GET['confirm']) && <list of OR conditions>)
That way PHP bails out of evaluating the conditional if there is no 'confirm' index.
isset() is a useful function. It returns "true" if the variable exists and "false" if not. Usually, people use it in conjunction with a superglobal like $_GET or $_POST to determine whether you're being sent from another page on the site - this allows you to create different actions based on where your user is coming from and what data is tagging along. It also prevents errors in trying to use variables you haven't yet defined, like the OP is getting. So instead of needing to write two different .php files and worrying about sending your user to the wrong one, you can do it all in one page.
Jay,
I'd be careful about your usage of some of these calls. <?php is more likely to work than <? . I've heard session_start() should be the very first thing set to the browser or it can cause header issues. And yes, you need to have a variable declared before you use it - if you're not typing in [file].php?confirm=[some number] as your URL, your page will break unless you amend it to allow for breaks.
That's because confirm query string variable does not seem to be set, you can check it like:
ini_set('display_errors', true);
error_reporting(E_ALL);
var_dump($_GET['confirm']);