PHP Redirects?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mcc_shane
Forum Newbie
Posts: 22
Joined: Sat May 12, 2012 1:47 pm

PHP Redirects?

Post by mcc_shane »

Hi Everyone,

I have a question regarding php redirects. If you visit the below URL and if your not logged in - your presented with a statement saying you have to be logged in (which is what I want) but after the person clicks on "Click Here" they are taken to the login page where they can login. My question is, how would I redirect visitors back to the car-search page they originally wanted to visit?

http://whatsmyowncarworth.com/class-wor ... search.php

This is my php session syntax on the car-search.php page.

Code: Select all

<?php 
session_start(); 

if (!isset($_SESSION['myusername'])) { 
echo "Hello, you must have an account to view this page. <a href=\"http://whatsmyowncarworth.com/class-work/sign2/main_login.php\">Click Here</a>!<br>"; 
exit(); 
} 
?>
JimSB
Forum Newbie
Posts: 6
Joined: Thu Oct 25, 2012 5:15 am

Re: PHP Redirects?

Post by JimSB »

I am in the process of playing around with this now.
Look at the documentation for the Header() function with the Location option.
A sequence like this will force an immediate invocation of the desired page
session_write_close();
Header('Location: http://' . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) . 'pageyouwant.php');
die();
There are some tricks to this though:
you need session_write_close() to make sure that any changes to session variables are successfully written before you move on.
you need to kill the current script or it will continue to process. I am using die() here, but exit; may be better. Some documentation says exit and die are aliases of the same thing.
The header() function must be the VERY FIRST output on the new page, including white space. If it is not you will get an error. I do this by having my page form action invoke itself, determine which button was pressed, and redirecting appropriately.
See my earlier post today about differences in the domain name causing different sessions. This drove me nuts earlier, but seems to be working now (still testing).
There are some other tricks for redirection, including META refresh and writing javascript like
<script type="text/javascript">
<!--
window.location = "http://www.google.com/"
//-->
</script>
These might be even better. I am still experimenting, and any input from more experienced PHP developers is welcome.
Post Reply