PHP $_GET and $_POST undefined problem - php

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']);

Related

array_key_exists throwing error: The second argument should be either an array or an object

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
}

I have an undefined variable, but i don't know why

This is the code i have problem with: http://tutsforweb.blogspot.hu/2012/02/php-installation-script.html
Notice: Undefined variable: pre_error in C:\wamp\www\torolni\install.php
on line 110 Call Stack #TimeMemoryFunctionLocation
10.0022297152{main}( )..\install.php:0 20.0022297824step_2( )..\install.php:13
I have the same problem,as the first commenter, but i don't know how to "close Notice message in your php ini file". What is that? Where can i find it? I use WAMP. Could it be a problem in a "real" server? (Not in localhost)
I can't go to the 3rd step because of the error. Help me please.
They are suggesting to not display PHP notices, but I think it is bad advice because instead of fixing possible code problems that method just hides the message. Fixing the probem would be to initiate the variable:
function step_2(){
$pre_error = '';
//...
}
Let me start off by saying turning off notices to hide your PHP errors is not very good practice at all!
Looking at the error, you cannot echo a non-existent variable. $pre_error is not defined in the case where things work correctly. You can declare this at the start of 'Step 2'.
function step_2(){
$pre_error = '';
if....
It would also be a good idea to update the conditionals in the if statements so that you check the array key exists before testing it's value.
E.g. && $_POST['pre_error'] != '' should change to && (isset($_POST['pre_error']) && $_POST['pre_error'] != '')
Click on your WAMP icon in the taskbar > PHP > php.ini. This will bring you to the text file that sets up your basic PHP behaviors. You can customize those behaviors by following this reference: http://www.php.net/manual/en/function.error-reporting.php
Also, please don't make a PHP installation script. All sorts of security issues will rear their ugly head, especially if you're not using secure FTP over SSL.
To find your php.ini file:
Option 1: Navigate to the corresponding folder on your computer and open the php.ini file with notepad. on mine it is specifically C:\wamp\bin\apache\Apache2.2.17\bin (Your exact location and version of php may be slightly different.
Option 2
Click on the wamp icon in your system tray->PHP->php.ini
In notepad hit ctrl+f and search for display_errors = On. set this to display_errors = Off
Restart your wamp server and the notice should no longer be displayed
This is a very poor fix however as others have mentioned. I would also recommend you turn them back on when you are finished with that tutorials as displaying errors is invaluable when developing.

Smarty internal error

Looking through the server PHP error log has revealed that a certain type of PHP Notices comes up as the most frequent, and it has to do with Smarty. I've found a question which seems to describe the same error, but there is actually no answer.
The notice is the following (there are different variables stated as undefined):
PHP Notice: Undefined variable: is_admin in /usr/share/php/Smarty/sysplugins/smarty_internal_data.php on line 291
I wonder how I can possibly debug this one since no data (like template name) is provided.
Below I'm gonna give you some idea of the code (which you can read in full detail here since it's all open-source).
So there is one global smarty object which is created in a file called header.php, and further in the same file some global smarty variables are set, including the one from the notice above:
//init Smarty
require_once('Smarty.class.php');
$smarty = new Smarty();
...
$smarty->assign('is_admin', is_admin() ? 1 : 0);
This header.php is then included in every file that needs to show some HTML by calling $smarty->display(...). So I presume that in any file where the $smarty object is present this object has a variable called is_admin. However, it doesn't seem to be the case.
Additionally, "normal" Smarty warnings about unset variables look differently:
PHP Notice: Undefined index: sent_id in /var/www/smarty_dir/templates_c/a5aab2c66c44442365a39981ba9be18e0a1f11ad.file.history.tpl.cache.php on line 123
Any ideas?
Upd.
I've read some logs and I see that such warnings seemingly arise when a user enters a page and gets 302 HTTP status. This may be due to the following code (which is placed after smarty constructor call but before the variables are assigned:
//cookie check
if (!is_logged() && isset($_COOKIE['auth'])) {
if ($user_id = check_auth_cookie()) {
if (user_login('', '', $user_id, $_COOKIE['auth'])) {
header("Location:".$_SERVER['REQUEST_URI']);
return;
}
}
}
So I guess I should move $smarty initialisation after this block and it is likely to help. Still I'm curious about how it relates to the issue.
I think I got it. The issue is really in the piece of code including
header("Location:".$_SERVER['REQUEST_URI']);
return;
My error is that return does not act like exit in this case, because when you call return from a file which is required or incuded into another one, you just return the control to that another file. I wasn't aware of this feature.
'is_admin', is_admin() you are trying to assign the function is_admin() as a variable {$is_admin} to the Smarty template, which according to me, is impossible.
Assign the return result to a variable i.e.:
$var = is_admin();
$smarty->assign('is_admin', $var);

PHP Function 'return' not returning

This is a bit of an oddity for me. PHP is my forte, and I can normally figure out any issue I encounter.
I have a custom framework that I have been using for years. I have taken it upon myself to rewrite it, and I'm doing everything essentially the same that I was before. The problem lies in the following construct:
function ModPages_GetPage() {
$page = ModPages_GetPageByName($_GET['page_name']);
if($page != false) {
include(TPL_DIR.'pages/pages.view.php');
} else {
ErrorMessage('Invalid Page', 'The selected page could not be found.');
}
}
function ModPages_GetPageByName($page_name = null) {
$db = new Database;
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
$page = $db->GetRow($query);
return $page;
}
This code is being called with 'home' for the value of $_GET['page_name']. The call to ModPages_GetPageByName() is working fine, but the value of $page in ModPages_GetPage() isn't getting set. Matter of fact, any debugging statements thrown in after that call are failing to display anything.
I have display_errors set to on, and error_reporting set to E_ALL. I get a couple notices from my Database class, but that's it.
Running the script at a shell fails to produce any errors. When using strace, I do see the process spits out an 'exit_group(255)'.
This one has me quite baffled. I could sure use some direction on this.
I would think it's your query, shouldn't you just return the page name instead of star? as star (*) would return an array which is probably being passed back as the value? just my guess.
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
if you do a print_r on the $page return I would think it should be an array
$page = $db->GetRow($query);
echo "Page:<pre>".print_r($page,true)."</pre><br />\n";
Then maybe return something like this
return $page['page_name_field'];
ok before we get to a solution can we first make sure that before setting the $page variable, first just echo $_GET['page_name'] to see if there is a value being received.
PK
Does your script stop right after your database call, or just doesn't display any output?
If the first is true, then it looks like a fatal error. With E_ALL, it should be displayed, are you sure both display_errors and error_reporting are as you say at that point, and that the GetRow function doesn't alter them in any way? If so, maybe there's something in the Apache error log (PHP errors are sometimes logged there).
If the latter is true I'm thinking about an exception being thrown in a method that is being called, and caught in a higher level function. To check this you can put the database call (ie: the point where things go wrong) inside a try/catch block and see if you reach the catch block.
I would try following:
replace $_GET with $_REQUEST (maybe your form is using POST?)
do a print_r to check contents of your variables.
use mysql_error to view any errors, or print your mysql query in your browser, copy/paste it in phpmyadmin, is it returning anything? error.. data?
something similar happend to me once, my framework was encoded in ANSI and my calling php file was UTF8+BOM... I changed everything to UTF8+BOM and it worked.
try also different browser, I know it might not be a browser problem, but it might be that your script is cached somewhere.
are you using some caching? like eaccelerator?
Are those functions in a class? If so, you will need $page = $this->ModPages_GetPageByName().
Also I would echo out the argument and the sql statment in ModPages_GetPageByName(). This way you can verify that it isn't a SQL error.
I can't say for sure why your code isn't working, but I can make some suggestions that might help in locating the error.
The first thing I notice is you don't check that $db actually contains a valid database. I don't know the details of your Database object but I'm assuming there's some mechanism in there for checking if it's actually connected to the database. You should use that to determine if the database is connected before running queries on it.
$db = new Database ();
if ($db -> isConnected ())
{
$query = 'SELECT * (etc etc etc)';
// ...
}
else
{
// Put some kind of DB connection error notification or throw an exception here
}
Just on a stylistic note, you don't need to store the results of your DB lookup before returning it, unless you're planning on doing some processing on the result before returning it. You can just return the lookup directly. Of course that's just a stylistic choice, but it saves a line or two :)
return ($db->GetRow($query));
After you run your getpage function, I'd strongly recommend var_dump()ing the result. Even if your function returned NULL, you'll still see this in the var_dump. If in doubt, dump it out :). I'd also recommend installing xdebug to make the var_dump output more readable.
$page = ModPages_GetPageByName($_GET['page_name']);
var_dump ($page);
I would also strongly recommending var_dumping your query before you execute just to make absolutely sure that you're running the query you think you're running. Copy and paste the outputted query into sqlyog or phpmyadmin or whatever you use for interactive access to your database and make sure it returns what you think it should return.
Other things to check, is the page you're trying to return actually set page_enabled='yes'? Does the page_enabled column actually store the value as 'yes', or is it a bool or an integer or something else? Is magic quotes enabled or disabled? If they're in one state when you think they're in the other they can cause confusion. Are errors actually being reported to the browser? Add a line at the top of your script that's guaranteed to fail just to make sure, like an attempted foreach on an integer. If you don't see an error, then maybe error reporting isn't configured properly. I know those are obvious questions but I also know how easy it is to overlook the obvious if you're not getting what you expect out of a query.
Are you sure $page is not set, or is it just that your debug instructions don't print anything? Try logging to a file or a database instead; maybe your code triggered output buffering or something like that.
Also, you are calling ModPages_GetPageByName before declaring it. That is usually okay, but might not be in special circumstances (e.g. when the code is wrapped in an if block). Try swapping the two.
Also, check your environment and disable opcode caching and other possible error sources. APC for example can call the old version of the script long after you changed the PHP file.
While some of you have put extra effort into responding to this, nobody has been able to see the full picture, even given the details I have provided. I have been unable to trace the issue back to its source, but have moved on to a different project.

check box stops my Jquery script

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.

Categories