Pergunta

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,

Foi útil?

Solução

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

Outras dicas

This should work:

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

Do something like:

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

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

For solving the problem when no id is given via GET, I think will be enough to add this line at the beginning of each php page:

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

It is not necessary to change the URL on the fly.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top