[php] PHP header(Location: ...): Force URL change in address bar

I'm currently working on a mobile site with authentication using PHP sessions with a database. I have a login page with a form that goes to server_login.php on submit. The php file then creates some session data (store in $_SESSION), and redirects the user back to the index page:

header("location:../../index.php");

The new web page (index.php) loads correctly; however, when the header redirects the page, the URL at the address bar is not changed; it stays at *http://localhost/php/server/server_login.php* instead of http://localhost/index.php and thus all my other resources that makes use of relative pathing could not be loaded. It's as if the web page still thinks that it resides at /php/server instead of /.

Strangely, my other use of header("location: ...") at logout.php works and redirects the page successfully with a URL change.

I've made sure that there are no outputs in my *server_login.php* before the header redirect (above it are just mysql calls to check) and I've used ob_start() and ob_end_flush() too.

Are there any methods of forcing the URL on the address bar to change (and thus hopefully fix the relative path problem)? Or am I doing something wrong?

P/S: I am using jQuery Mobile.

EDIT: Here's my code for the redirection that doesn't change the URL:

// some other stuff not shown


$sql = "SELECT * FROM $user_table WHERE email = '$myemail' AND password = '$mypassword'";
$login_result = mysql_query($sql, $connection);

$count = mysql_num_rows($login_result);

if ($count == 1) {

    // Successfully verified login information

    session_start();

    if (!isset($_SESSION['is_logged_in'])) {
        $_SESSION['is_logged_in'] = 1;
    }

    if (!isset($_SESSION['email'])) {
        $_SESSION['email'] = $myemail;
    }
    if (!isset($_SESSION['password'])) {
        $_SESSION['password'] = $mypassword;
    }

    // Register user's name and ID
    if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id'])))  {
        $row = mysql_fetch_assoc($login_result);
        $_SESSION['name'] = $row['name'];
        $_SESSION['user_id'] = $row['user_id'];
    }

    header("Location: http://localhost:8080/meet2eat/index.php");

} else {
    // Not logged in. Redirect back to login page
    header("Location: http://localhost:8080/meet2eat/php/login.php?err=1");

}

This question is related to php redirect header location

The answer is


use

header("Location: index.php"); //this work in my site

read more on header() at php documentation.


you may want to put a break; after your location:

header("HTTP/1.1 301 Moved Permanently");
header('Location:  '.  $YourArrayName["YourURL"]  );
break;

You are suppose to use it like header(Location:../index.php) if it in another folder


In your form element add data-ajax="false". I had the same problem using jquery mobile.


I had the same problem with posting a form. What I did was that turning off the data-ajax.


// Register user's name and ID

if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id'])))  {
    $row = mysql_fetch_assoc($login_result);
    $_SESSION['name'] = $row['name'];
    $_SESSION['user_id'] = $row['user_id'];
}

header("Location: http://localhost:8080/meet2eat/index.php");

change to

// Register user's name and ID

if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id'])))  {
    $row = mysql_fetch_assoc($login_result);
    $_SESSION['name'] = $row['name'];
    $_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}

why all of this location url?

http://localhost:8080/meet2eat/index.php

you can just use

index.php

if the php files are in the same folder and this is better because if you want to host the files or change the port you will have no problem reaching this URL.


As "cfphpflex" suggested you can add break; after setting the header. You can also echo something, such as echo 'test';.


Just change home to your liking

$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/home';

header('Location: ' . $home_url);

Do not use any white space. I had the same issue. Then I removed white space like:

header("location:index.php"); or header('location:index.php');

Then it worked.


I got a solution for you, Why dont you rather use Explode if your url is something like

Url-> website.com/test/blog.php

$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);

Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem

Also yes always add whitespace like @Peter O suggested.


Try changing:

header("Location : blabla")
                ^
                |
           (whitespace)

To

header("Location: blabla")

Well, if the server sends a correct redirection header, the browser redirects and therefore "changes the url". It might be a browser issue, then. I don't know if it has anything to do with it, but you should not send a relative url in the location header ("HTTP/1.1 requires an absolute URI as argument to ยป Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. ", http://php.net/manual/en/function.header.php), and "location" must be capitalized, like:

header('Location: http://myhost.com/mypage.php');

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll

Examples related to location

Nginx serves .php files as downloads, instead of executing them Get User's Current Location / Coordinates Location Services not working in iOS 8 How to set fake GPS location on IOS real device Android Google Maps API V2 Zoom to Current Location What is meaning of negative dbm in signal strength? How does it work - requestLocationUpdates() + LocationRequest/Listener How to get Android GPS location Redirect using AngularJS How to check if Location Services are enabled?