Paul
Paul

Reputation: 197

PHP header redirection not working as expected

I have the following issue. I collect some user input and then write it to a text file using PHP. After this is done I want to redirect to another web page - here www.google.com. I am having difficulty.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
$IP = $_SERVER["REMOTE_ADDR"].',';
$logdetails=  $IP.date("F j, Y, g:i a O T");
$stringTimeout = $_POST['_delay'];
$stringData1 = $_POST['userChoices'];
$s = ',';
$postData = $s.$stringTimeout.$s.$stringData1"\n";
fwrite($fh,$logdetails.$postData);
fclose($fh);

header("Location: http://www.google.com");

Upvotes: 2

Views: 744

Answers (7)

Anand
Anand

Reputation: 1680

i had also faced this issue many time. i solved it by putting a die(); on the next line of header("Location: http://www.google.com");

someting like this

header("Location: http://www.google.com"); die();

Upvotes: 0

Ryan
Ryan

Reputation: 1888

I pasted an alternative over the original solution sorry.

Original solution that worked for paul

fwrite($fh,$logdetails.$postData,'a');

This forces fwrite to amend the file, using the 'w' option will overwrite the file

The alternative I also use for multiple variables is:

$write_me = $logdetails.$postData;
fwrite($fh,$write_me);

Upvotes: 1

Francis Gilbert
Francis Gilbert

Reputation: 3442

Try adding:

ob_end_flush();
exit();

after your header() method.

Upvotes: 0

patapizza
patapizza

Reputation: 2398

Isn't there any error?

It may not be related but it seems to me that you forgot one dot before the last escaped "\n" character:

$postData = $s.$stringTimeout.$s.$stringData1."\n";

Upvotes: 1

mcKain
mcKain

Reputation: 437

what if you try your redirect part first in another PHP. divide and conquer! :)

hey and If that does not work, check your html headers, I remember that I had issues with the html headers trying to use:

header("Location: http://www.google.com");

Upvotes: 0

afarazit
afarazit

Reputation: 4984

remove the space between fclose($fh); and header("Location: http://www.google.com"); like in

fclose($fh);
header("Location: http://www.google.com");

Upvotes: 1

Eric Herlitz
Eric Herlitz

Reputation: 26267

The header method really suck when it comes to this and the lack of a redirect method is really annoying.

I assume you get the "Headers already set" or "Headers already sent to the browser". In such case use a javascript instead of the header method.

//header("Location: http://www.google.com");    
echo "<script type='text/javascript'>location.href='http://www.google.se'</script>;";

Upvotes: 2

Related Questions