check if a querystring exists, if not create one - PHP

21,315

Solution 1

Maybe there are plenty of ways. You can assign value to $_GET key if one does not exist. Or if you really need to query string, you can renavigate the user to the same page with present querystring.

if (!isset($_GET['id'])) {
    header("Location: Page.php?id=1");
    exit;
}

It should be before any output in the page. So if user visits Page.php or Page.php? or Page.php?someDifferentParamThanId=10 it will return false on isset($_GET['id']) thus it will redirect to Page.php?id=1

Solution 2

This should work:

if(isset($_GET['id'])){
    //It exists
}else{
    //It does not, so redirect
    header("Location: Page.php?id=1");
}
Share:
21,315
user2972392
Author by

user2972392

Updated on July 09, 2022

Comments

  • user2972392
    user2972392 almost 2 years

    I have several pages which use querystrings to highlight an option in a menu, all the url's on the page have the currant querystring phrased in them so the same menu option will be highlighted on the next page if the user clicks the link.

    However the problem arrises when someone visits the page without the querystring included in the url, the menu option isn't highlighted.

    What i would like to do is check the URL to see if a querystring is present, if one isnt, create one.

    The url's are phrased as such www.mysite.co.uk/Folder1/Folder2/Page.php?id=3

    and i would like the default querystring to be ?id=1 if one isn't already present in the url.

    Any ideas on how you do this?

    And what would happen if a user visits using the URL www.mysite.co.uk/Folder1/Folder2/Page.php?

    Would the URL end up as www.mysite.co.uk/Folder1/Folder2/Page.php??id=1

    or would it be www.mysite.co.uk/Folder1/Folder2/Page.php?id=1

    Thanks,

  • Dizzley
    Dizzley almost 9 years
    $_GET is a subset of $_REQUEST and I recommend you use $_GET.