Question

I have a main page that users go to that shows output from a MySQL query depending on the variable passed to it. So;

http://website/mypage.php?page=0

However, I would like to set up redirection so that if someone just goes to

http://website/mypage.php

that it will go to http://website/mypage.php?page=0. I thought of using the following code, which verifies the current page as well as verifies that a user's session is established;

elseif ($_SERVER['PHP_SELF'] == '/mypage.php' && isset($_SESSION['valid_user']))
{
header('Refresh: 0; URL=/mypage.php?page=0');
}

But, this looks to be too general. Is there a way to check for exactly '/mypage.php' or maybe '/mypage.php?page=' ? I thought of using strlen to check for only the 11 characters in /mypage.php, but I'm not sure that this is the most efficient way of doing it.

Was it helpful?

Solution 2

In your mypage.php you can check something like this

if(!isset($_GET['page'])) {
    header('location: /mypage.php?page=0');
    exit;
}

But, I think, instead of redirecting to same page with a get variable, why don't just show the page you want to show by default, when there is no page variable is set.

OTHER TIPS

You can check to see if the variable page has a value and if its empty you can do the redirect

if($_GET['page'] == ''){
  header('Location: /mypage.php?page=0');
  exit;
}

or

if(!isset($_GET['page'])){
  header('Location: /mypage.php?page=0');
  exit;
}

You should use this way:

header('Location: /mypage.php?page=0');
exit;

Otherwise check the $_SERVER variables for more strict match. http://php.net/manual/en/reserved.variables.server.php

I think probably you need $_SERVER['REQUEST_URI']

Is this what you're looking for?

if(!isset($_GET['page']) || empty($_GET['page'])) {
    Header('Location: http://website/mypage.php?page=0')
    exit();
}

or

if(!isset($_GET['page']))
    $_GET['page'] = 0;

I'm not sure about the second solution, you shouldn't attribute value to $_GET[] variables.

if( !isset($_REQUEST['page']) ) {
    header('Location: /mypage.php?page=0');
    exit(0);
} else {
    if( $_REQUEST['page']=="" ) {
        header('Location: /mypage.php?page=0');
        exit(0);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top