PHP: Undefined Index - Yet I defined Them ? :S - php

Hey all, my first time asking on stackoverflow!
Anyway. So this morning (and most of last night) I have been working on an a project of mine. Its a simple small scale e-commerce site.
Not to bog down with the details of the website, I'll skip straight to it.
Basically, I have my website hosted on a webserver with my own domain. In order to submit the work to my University tutors, I have to transfer the files to their web-server. This can only be accessed when connected to the university network and runs under the path http://jawa/handins/...../
Now in order for the MySQL and PHP to function I have to extract the tables and information from my personal phpmyadmin panel and dump it into the phpmyadmin panel provided on the Uni network. The database is called something alot different but the tables are the same, so a small minute to make sure my mysql_connect functions are pointing to the correct database and everything is working fine. Or at least that is the plan..
For some reason my PHP variables (Which WORK on MY server) are now undefined - How? I havent changed a single piece of code except where the database is and that is it:
//form data
$firstName = strip_tags($_POST['firstName']);
$lastName = strip_tags($_POST['lastName']);
$Email = strip_tags($_POST['Email']);
$userName = strip_tags($_POST['userName']);
$regPass = strip_tags($_POST['regPass']);
$repeatPass = strip_tags($_POST['repeatPass']);
$date = date("Y-m-d");
$permissions = strip_tags($_POST['permissions']);
Everything matches up with the relevant submit fields. There is nothing different with the code I have running on my personal webserver, and the code hosted on the university network. Yet now these variables you see here are not defined. Forgive me for being stupid if it's obvious, but ive been up for 20hrs straight now and I'm getting really agitated with small problems. However I will not vent my frustration out on anyone, it's not your fault!
Essentially, those variables are used for a registration form. Each sumbit field is given the value which is passed on the $_POST[] function. The form is "POSTING" so no problems there. Im just at a loss!

You probably have a different error_reporting level on your own machine, then it is on the other server. Please add error_reporting(E_ALL); to the top of your page, and these will yell at you.

As #Wesley van Opdorp mentioned, your machine must've a different reporting level, if you set it to E_ALL you will see all errors diplayed such as warnings, notices, and fatal errors.
You have to remember, if you're writing code with the error_reporting turned off or it is set to hide warnings or even notices and everything is working fine, if you turn it on, it may affect your code as it will report every single undefined variable and some other warnings as if it's on strict mode. You may have to add additional checks if that's the case like using isset or is_null before using or referring to undefined variables. Just a thought.

#Wesley is probably right about error reporting.
Try this too though. Check if the input has been entered before trying to use it:
$firstName = isset($_POST['firstName'])?strip_tags($_POST['firstName']):null;
Looks rough I know, but looks it can be as easy as this:
$date = date("Y-m-d");
$inputs = array('firstName', 'lastName', 'Email', 'userName', 'regPass', 'repeatPass', 'permissions');
foreach($inputs as $input)
{
$values[$input] = isset($_POST[$input])?$_POST[$input]:null;
//if it was set/used, store it in the variable, if not store null
}
This saves you writing a line for each of the inputs.
So for example $values['firstName'] would have the value of "John" OR null
So when using any of the $values elements check if it's null or use empty() to see if they put in an actual value.

Related

PHP Filter Input Array

if(isset(filter_input_array(input_post)
Also the reason why im using Filter input array is because $_POST doesn't even work anymore not on netbeans anyway.
My localHost hits me back with a :
Warning: Use of undefined constant input_post - assumed 'input_post' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\Test1\Includes\signup2.inc.php on line 3
I'm pretty new to Coding and especially PHP. Im in 1st year of Uni doing course work, so dont get upset if its a silly question. But I have no idea how to fix this.
This is all I have so far
<?php
if(isset(filter_input_array(input_post)['signup-submit'])) {
require 'dbh.inc.php';
$username = filter_input_array(input_post)['uid'];
$email = filter_input_array(input_post)['mail'];
$password = filter_input_array(input_post)['pwd'];
$passwordRepeat = filter_input_array(input_post)['pwd-repeat'];
Filtering input is fundamentally wrong (really the issue here is about PHP naming conventions).
because $_POST doesn't even work anymore
So your workaround for a problem is no longer working. Stop trying to fix your workaround and fix the problem. PHP is primarily a scripting language for the web - if it is not handling request data something is very wrong.
Try using $_REQUEST as global var.

Simple issue with checkboxes in a SQL form submit

So forgive this dumb question. I'm a music teacher, not a programmer.
I am submitting a form. I have possibly checked checkboxes for "spoken languages".
<input type="checkbox" id="speakEnglish" name="speakEnglish" value="yes" />
<input type="checkbox" id="speakGerman" name="speakGerman" value="yes" />
And then on form submit I have
$speakEnglish = $_POST['speakEnglish'];
$speakGerman = $_POST['speakGerman'];
And formulate my SQL query from that. It was submitting and INSERTing fine on my local host, but since uploading to a server I'm getting this when a checkbox is empty...
AN error occurred in the script '/home/berli/public_html/TEST/signup.php' on line 295:
Undefined index: speakGerman
This confuses me .. though I understand whats going on.
But why was my form submitting with empty checkboxes before, and now it throws an error?
What is the normal way to handle this?
Something like..?
if(isset($_POST[checkboxVar]) { $SQLcheckboxVar = $_POST[checkboxVar]} };
I just don't understand why empty checkboxes didn't hang me up on local host, but now they do. I cant think of anything else I could have done to cause that and I certainly wasn't testing for the checkbox variables before... but I have a SQL table full of INSERTed entries.
Is there some kind of difference on how this would work locally vs on a server?
Your servers error reporting must show notices/warnings (not sure specifically which one that is).
You are correct in saying that if(isset($_POST['checkboxVar'])) is all you would need to hide that error if you can't change your php configuration (php.ini). This is what you need on your online server (usually /etc/php.ini):
;Show all errors, except for notices and coding standards warnings
error_reporting = E_ALL & ~E_NOTICE
Your local configuration is probably using the default php settings, which are suppressing any Notices. The production server has a stricter error reporting which lets you know of tiny (most probably not important) problems.
In this case you are trying to access a variable which is not defined, as the browser is NOT sending any data for checkboxes that have not been selected.
As already pointed out above, a simple if(isset($_POST[checkboxVar])) will do the trick to get rid of the notice on per-variable level.
In case you wish to stay a music teacher and not break your head against the wall every time these things pop up it may be easier to simply put the following as the first line of your program:
error_reporting(E_ALL & ~E_NOTICE);
The simplest way to avoid this Notice is to check if your Checkbox has been checked with something like:
if (!isset($_POST['checkboxVar'])) $_POST['checkboxVar'] = 'no';
or
$checkboxVar = isset($_POST['checkboxVar']) ? $_POST['checkboxVar'] : 'no';
The Problem you ran into is, that the browser will not submit anything in the formdata if your checkbox hasn't been checked.

Is there another way to assign PHP variables that I don't know about?

I'm debugging some client PHP code that has me stumped. As this pseudo-example illustrates, there is code on the receiving end of a form submission that processes the form values, but without ever apparently assigning those values:
(On form submission, where form has fields 'name' and 'position'):
echo "The name is = ". $name;
echo "The position is = ". $position;
This code is part of a large app, and code from other files is called before this. BUT the crucial point is that if I do a search for '$name = ' across the entire codebase it never shows up. How then is it possible that the request variable gets assigned to $name? Is there another way to assign value to a variable in PHP other than $var = value??
My only other clue is that this project uses Smarty, which I don't know anything about.
It may be that the person that created the code was working on a server with register_globals on. What that does, for example, is create regular global variables as the result of a form submission rather than populating the $_POST or $_GET arrays.
If the register_globals directive has been set to true in php.ini, then all POST attributes will also show up as individual variables, in the way you describe. Note that this directive is false by default, and that use of this directive is deprecated.
When you look at the smarty documentation you can see that variables are assigned like this (copied from the linked page):
<?php
$smarty = new Smarty();
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');
$smarty->display('index.tpl');
?>
Technically yes there is.
$x = 'name';
$$x = 'harry';
echo 'Yer a wizard '.$name;
(I would be surprised if this was the reason)
I guess your server has register_globals setting on, which automatically generates variables from posted items:
$_POST['foo'] === $foo
Maybe this is another outbreak of the register_globals disease?
This has been thought to have died out, but surfaces again and again!
Sounds to me like someone included those variables with the intention of doing more with them, but never got around to doing so. Unless an include php page is assigning values to those variables, nothing will go in them.
Try turning your error reporting level up, if these variables are being used but haven't been initialised, a warning will be shown

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.

PHP Based session variable not retaining value. Works on localhost, but not on server

I've been trying to debug this problem for many hours, but to no avail. I've been using PHP for many years, and got back into it after long hiatus, so I'm still a bit rusty.
Anyways, my $_SESSION vars are not retaining their value for some reason that I can't figure out. The site worked on localhost perfectly, but uploading it to the server seemed to break it.
First thing I checked was the PHP.ini server settings. Everything seems fine. In fact, my login system is session based and it works perfectly. So now that I know $_SESSIONS are working properly and retaining their value for my login, I'm presuming the server is setup and the problem is in my script.
Here's a stripped version of the code that's causing a problem. $type, $order and $style are not being retained after they are set via a GET variable. The user clicks a link, which sets a variable via GET, and this variable is retained for the remainder of their session.
Is there some problem with my logic that I'm not seeing?
<?php
require_once('includes/top.php'); //first line includes a call to session_start();
require_once('includes/db.php');
$type = filter_input(INPUT_GET, 't', FILTER_VALIDATE_INT);
$order = filter_input(INPUT_GET, 'o', FILTER_VALIDATE_INT);
$style = filter_input(INPUT_GET, 's', FILTER_VALIDATE_INT);
/*
According to documentation, filter_input returns a NULL when variables
are undefined. So, if t, o, or s are not set via URL, $type, $order and $style
will be NULL.
*/
print_r($_SESSION);
/*
All other sessions, such as the login session, etc. are displayed here. After
the sessions are set below, they are displayed up here to... simply with no value.
This leads me to believe the problem is with the code below, perhaps?
*/
// If $type is not null (meaning it WAS set via the get method above)
// or it's false because the validation failed for some reason,
// then set the session to the $type. I removed the false check for simplicity.
// This code is being successfully executed, and the data is being stored...
if(!is_null($type))
{
$_SESSION['type'] = $type;
}
if(!is_null($order))
{
$_SESSION['order'] = $order;
}
if(!is_null($style))
{
$_SESSION['style'] = $style;
}
$smarty->display($template);
?>
If anyone can point me in the right direction, I'd greatly appreciate it. Thanks.
Unbelievable!
After three hours of debugging, I've figured out the problem
HostGator, my no-longer-beloved host, runs their default ini with register_globals ON
I can't believe this.
So my variables of $type was being overwritten with $_SESSION['type'] and they were being treated as the same. So it was a server issue causing the problem, not my coding. That's great to know, but I want my 5 hours of pulling my hair out back.
I hope this helps someone down the road whose using HostGator and is confused as hell.
You need to call the session_start() function . Before accessing the $_SESSION variable.
Then It will retain all SESSION variables to you..
I think you pointed out you have made a call to session_start() in the top.php right? And another thing I notice is that you are validating Integer fields through the PHP Filter. Be sure that they are integer values or you are bound to end up with null values. Do a test to see if the TYPE,ORDER and STYLE values are set before validating. Do keep in mind that, using the php filter is to validate for a certain type and not to store. I dont think that $type would store your data, it would rather be a boolean check. Try assigning the $_GET[] variables to the SESSION VARIABLES. Hope this helps.

Categories