Skip to main content
gamedev.net
🔒 Locked 🤖 Godot

[web] $_REQUEST['headache']

Started by benryves Jul 15, 2004 at 7:05 AM 4 replies 450+ views
Original Post
benryves
benryves
In developing a calendar in PHP to display a month I need to be able to pass variables, such as ?month=7&year=2004&job=2&location=3 to the PHP script. I currently use:

$currentDate = getdate();
$month = $currentDate['mon'];
$year = $currentDate['year'];

if ($_REQUEST['month']) {
	$month = $_REQUEST['month'];
}

if ($_REQUEST['year']) {
	$year = $_REQUEST['year'];
}
However, if I do not specify a year or month variable, I get 'undefined index' errors. Is there a means of checking if the $_REQUEST variable exists before I try and read it?
[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]
markr
markr
It's not really an error. This is a "feature" of PHP - it chucks out warnings if you attempt to access an undefined part of an array.

Stick an @ in front of an expression accessing an array if there could be any chance of it being undefined.

Your best bet is to try to produce code which gives no warnings or any other messages on the log when it's running correctly. That way you'll more easily spot genuine errors.

A lot of PHP apps I've seen generate large numbers of warnings as a matter of course - this sucks as it drowns out real warnings possibly caused by errors or hack attempts, etc.

Mark
benryves
benryves
OK, thanks. Especially the tip about the @ :)
I wrote a simple function that's quite useful:
function checkRequest($r) {	if (substr_count($_SERVER['REQUEST_URI'],$r)!=0) {		return true;	} else {		return false;	}}

This way, I can create error free scripts like this:
if (checkRequest('month')) { $month = $_REQUEST['month']; }
[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]
Spoonbender
Spoonbender
The "pretty" solution is to use isset()

isset($_REQUEST['month']) will return true if the variable is set. False if it doesn't exist
benryves
benryves
Quote:
Original post by Spoonster
The "pretty" solution is to use isset()

isset($_REQUEST['month']) will return true if the variable is set. False if it doesn't exist

Damn, I knew there was a function for that but couldn't remember the name of it. I was looking up "ifexist" and "doesexist" and so on. Whoops. Thanks!
[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]
markr
markr
The "@" solution may not be pretty, but it's certainly the most concise, and there are a lot of situations where using isset() would be far more complex. Consider

@ $inventory[$itemtype] += $quantity;


If $inventory does not have an entry for $itemtype, it should create it and set it to quantity, otherwise add to the quantity already there.

Doing that with isset() requires an if

Mark

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.