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

user2972392 picture user2972392 · Feb 2, 2014 · Viewed 19.6k times · Source

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,

Answer

Royal Bg picture Royal Bg · Feb 2, 2014

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