php $_GET and undefined index

PhpUndefined

Php Problem Overview


A new problem has arisen for me as I tried to run my script on a different PHP Server.

ON my old server the following code appears to work fine - even when no s parameter is declared.

<?php
 if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
 if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif ($_GET['s'] == null)
echo "<body>"
?>

But now, on a my local server on my local machine (XAMPP - Apache) I get the following error when no value for s is defined.

Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 43
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 45
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 47
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 49

What I want to happen for the script to call certain javascript functions if a value is declared for s, but if nothing is declared i would like the page to load normally.

Can you help me?

Php Solutions


Solution 1 - Php

Error reporting will have not included notices on the previous server which is why you haven't seen the errors.

You should be checking whether the index s actually exists in the $_GET array before attempting to use it.

Something like this would be suffice:

if (isset($_GET['s'])) {
    if ($_GET['s'] == 'jwshxnsyllabus')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
    else if ($_GET['s'] == 'aquinas')
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
    else if ($_GET['s'] == 'POP2')
        echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
    echo "<body>";
}

It may be beneficial (if you plan on adding more cases) to use a switch statement to make your code more readable.

switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
    case 'jwshxnsyllabus':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
        break;
    case 'aquinas':
        echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
        break;
    case 'POP2':
        echo "<body onload=\"loadSyllabi('POP2')\">";
        break;
    default:
        echo "<body>";
        break;
}

EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s= meant to output no <body> tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>.

Solution 2 - Php

Get into the habit of checking if a variable is available with isset, e.g.

if (isset($_GET['s']))
{
     //do stuff that requires 's'
}
else
{
     //do stuff that doesn't need 's'
}

You could disable notice reporting, but dealing them is good hygiene, and can allow you to spot problems you might otherwise miss.

Solution 3 - Php

I always use a utility function/class for reading from the $_GET and $_POST arrays to avoid having to always check the index exists... Something like this will do the trick.

class Input {
function get($name) {
	return isset($_GET[$name]) ? $_GET[$name] : null;
}

function post($name) {
	return isset($_POST[$name]) ? $_POST[$name] : null;
}

function get_post($name) {
	return $this->get($name) ? $this->get($name) : $this->post($name);
}
}
$input = new Input;
$page = $input->get_post('page');

Solution 4 - Php

I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

php.net: http://php.net/manual/pt_BR/function.error-reporting.php

Solution 5 - Php

I recommend you check your arrays before you blindly access them :

if(isset($_GET['s'])){
    if ($_GET['s'] == 'jwshxnsyllabus')
        /* your code here*/
}

Another (quick) fix is to disable the error reporting by writing this on the top of the script :

error_reporting(0);  

In your case, it is very probable that your other server had the error reporting configuration in php.ini set to 0 as default.
By calling the error_reporting with 0 as parameter, you are turning off all notices/warnings and errors. For more details check http://php.net/manual/en/function.error-reporting.php"> the php manual.

Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.

Solution 6 - Php

First check the $_GET['s'] is set or not. Change your conditions like this

<?php
if (isset($_GET['s']) && $_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
elseif (isset($_GET['s']) && $_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif (isset($_GET['s']) && $_GET['s'] == null)
echo "<body>"
?>

And also handle properly your ifelse conditions

Solution 7 - Php

You should check wheter the index exists before use it (compare it)

if (isset($_GET['s']) AND $_GET['s'] == 'foobar') {
    echo "foo";
}

Use E_ALL | E_STRICT while developing!

Solution 8 - Php

Actually none of the proposed answers, although a good practice, would remove the warning.

For the sake of correctness, I'd do the following:

function getParameter($param, $defaultValue) {
	if (array_key_exists($param, $_GET)) {
		$value=$_GET[$param];
		return isSet($value)?$value:$defaultValue;
	}
	return $defaultValue;
}

This way, I check the _GET array for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.

To use the function you just do:

$myvar = getParameter("getparamer", "defaultValue")

so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.

Solution 9 - Php

Avoid if, else and elseifs!

$loadMethod = "";
if(isset($_GET['s'])){
	switch($_GET['s']){
		case 'jwshxnsyllabus':
			$loadMethod = "loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')";
		break;
		case 'aquinas':
			$loadMethod = "loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')";
		break;
		case 'POP2':
			$loadMethod = "loadSyllabi('POP2')";
	}
}

echo '<body onload="'.$loadMethod.'">';

clean, readable code is maintainable code

Solution 10 - Php

Simple function, works with GET or POST. Plus you can assign a default value.

function GetPost($var,$default='') {
	return isset($_GET[$var]) ? $_GET[$var] : (isset($_POST[$var]) ? $_POST[$var] : $default);
}

Solution 11 - Php

Another option would be to suppress the PHP undefined index notice with the @ symbol in front of the GET variable like so:

$s = @$_GET['s'];

This will disable the notice. It is better to check if the variable has been set and act accordingly.

But this also works.

Solution 12 - Php

The real answer to this is to put a @ At symbol before the variable which will suppress the error

@$_GET["field"]
@$_POST["field"]

It will work some slower, but will keep the code clean.

When something saves time for the programmer, and costs time for the website users (or requires more hardware), it depends on how much people will use it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - PhpRudi VisserView Answer on Stackoverflow
Solution 2 - PhpPaul DixonView Answer on Stackoverflow
Solution 3 - PhpevilunixView Answer on Stackoverflow
Solution 4 - PhprodrigoioView Answer on Stackoverflow
Solution 5 - Phpgion_13View Answer on Stackoverflow
Solution 6 - PhpAwais QarniView Answer on Stackoverflow
Solution 7 - PhperenonView Answer on Stackoverflow
Solution 8 - PhpruppsView Answer on Stackoverflow
Solution 9 - PhpSparKView Answer on Stackoverflow
Solution 10 - PhpbolhaskutyaView Answer on Stackoverflow
Solution 11 - PhpFlorisView Answer on Stackoverflow
Solution 12 - PhpSam WashingtonView Answer on Stackoverflow