Tanmay Kumar
Tanmay Kumar

Reputation: 3

How to redirect to another page after a function is triggered [PHP]

(I'm new here so forgive me if this question is dumb)

Hello i'm looking for a solution to redirect to another page after a certain function is called. For example

if (condition is true) {
redirect ()}

function redirect() {
redirect
}

I can't use the header function here because

header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

Is there any way to do this?

Upvotes: 0

Views: 2437

Answers (3)

Tom
Tom

Reputation: 734

If you want to make absolutely sure that the user gets redirected, I think letting PHP handle the redirect is the best approach. This means that you either have to make sure that no HTML/spaces are outputted first (preferred), or use output buffering control with the ob_start() function at the beginning of your script.

Documentation: http://php.net/manual/en/function.ob-start.php

Then you can use a PHP redirect just fine.

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

Upvotes: 0

mishad050
mishad050

Reputation: 448

This also works:

if () {
   echo "<meta http-equiv='refresh' content='0;pagehere.php' />";
   exit();
}

Upvotes: 2

Vincent Duprez
Vincent Duprez

Reputation: 3892

You can write javascript with php that will be interpreted as soon as it is read by the browser..:

<?
if(...)
{
echo '<script type="text/javascript">window.location.href = "http://stackoverflow.com";</script>';
}
?>

Upvotes: 0

Related Questions