Page 1 of 1

PHP Redirects?

Posted: Thu Oct 25, 2012 11:34 am
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(); 
} 
?>

Re: PHP Redirects?

Posted: Thu Oct 25, 2012 12:13 pm
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.