Go back to the previous page in PHP

Although there are many methods to do this, I prefer the following code to go back to the previous page in PHP.

11


session_start();
$url = basename($_SERVER['PHP_SELF']);
$query = $_SERVER['QUERY_STRING'];
if($query){
$url .= "?".$query;
}
$_SESSION['current_page'] = $url;

In the page you want to come back to, add the above code. In the variable $url, even the query string attached to the added. This helps in case you want to go back to page like userprofile.php?userid=1234567 .Store this in a session variable.

In the second page, get the value from the session variable.


session_start();
$previous_page = $_SESSION['current_page'];

To go back to the previous page using a button:


<a href="<?php echo $previous_page;?>"><button>BACK</button></a>

Or

By Using header:


header("location:$previous_page");

Hope this helps!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s