Check if query exists if not create one - PHP

I have several pages that use querystrings to highlight an option in the menu, and all the page URLs contain the string expressed in tones, so the next menu option will be highlighted on the next page if the user clicks on the link.

However, the problem occurs when someone visits the page without the request included in the URL, the menu option is not highlighted.

What I would like to do is check the URL to see if the request exists if it is not created.

The URL is expressed as such www.mysite.co.uk/Folder1/Folder2/Page.php?id=3

and I would like the default string ?id=1 if it is not already specified in the url.

Any ideas on how you do this?

And what happens if a user visits via the URL www.mysite.co.uk/Folder1/Folder2/Page.php?

Will the URL be as www.mysite.co.uk/Folder1/Folder2/Page.php??id=1

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

Thanks,

+7
url php query-string pageload
source share
4 answers

There may be many ways. You can assign a value to the key $ _GET if it does not exist. Or, if you really need to request a string, you can redirect the user to the same page with the current request.

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

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

+9
source share

This should work:

 if(isset($_GET['id'])){ //It exists }else{ //It does not, so redirect header("Location: Page.php?id=1"); } 
+1
source share

Do something like:

 if(!isset($_GET['id'])){ header('LOCATION:www.mysite.co.uk/Folder1/Folder2/Page.php?id=1'); die(); } 
-one
source share

In php, the query string is loaded into the $ _REQUEST variable. In your case, $ _REQUEST ['id'] will be 1, 3, or whatever you get in the query string.

To solve the problem, when id is not passed through GET, I think it will be enough to add this line at the beginning of each php page:

 <?php if ( $_REQUEST['id']=='' ) {$_REQUEST['id']=1;} ?> 

No need to change the url on the fly.

-one
source share

All Articles