php $_GET and undefined index

Course Queries Syllabus Queries 3 years ago

2.82K 2 0 0 0

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago

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 "syllabus', '../syllabi/jwshxnporsyllabus.xml',         '../bibliographies/jwshxnbibliography_')\">";
if ($_GET['s'] == 'aquinas')
echo "syllabus', '../syllabi/AquinasSyllabus.xml')\">"; 
 if ($_GET['s'] == 'POP2')
echo "";
elseif ($_GET['s'] == null)
echo ""
?>

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?

0 views
0 shares

profilepic.png
manpreet 3 years ago

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 "";
    else if ($_GET['s'] == 'aquinas')
        echo ""; 
    else if ($_GET['s'] == 'POP2')
        echo "";
} else {
    echo "";
}

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 "";
        break;
    case 'aquinas':
        echo "";
        break;
    case 'POP2':
        echo "";
        break;
    default:
        echo "";
        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  tag or was this an oversight? Note that the switch will fix this by always defaulting to .


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum