[php] PHP page redirect

Can PHP make a redirect call after executing a function? I am creating a function on the completion of which I want it to redirect to a file located in the same root folder. Can it be done?

if (...) {
    // I am using echo here.
} else if ($_SESSION['qnum'] > 10) { 
    session_destroy();
    echo "Some error occured.";
    // Redirect to "user.php".
}

This question is related to php redirect header

The answer is


Using a javascript as a failsafe will ensure the user is redirected (even if the headers have already been sent). Here you go:

// $url should be an absolute url
function redirect($url){
    if (headers_sent()){
      die('<script type="text/javascript">window.location=\''.$url.'\';</script??>');
    }else{
      header('Location: ' . $url);
      die();
    }    
}

If you need to properly handle relative paths, I've written a function for that (but that's outside the scope of the question).


if you want to include the redirect in your php file without necessarily having it at the top, you can activate output buffering at the top, then call redirect from anywhere within the page. Example;

 <?php
 ob_start(); //first line
 ... do some work here
 ... do some more
 header("Location: http://www.yourwebsite.com/user.php"); 
 exit();
 ... do some work here
 ... do some more

The header() function does this:

header("Location: user.php");

I serach about this and i find related this answer in

https://stackoverflow.com/questions/13539752/redirect-function/13539808

function redirect_url($path)
{
  header("location:".$path);
  exit;
}

<?php

    http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);

?>

The header() function in PHP does this, but make sure that you call it before any other file contents are sent to the browser or else you will receive an error.

JavaScript is an alternative if you have already sent the file contents.


You can use this code to redirect in php

<?php
/* Redirect browser */
header("Location: http://example.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

header( "Location: http://www.domain.com/user.php" );

But you can't first do an echo, and then redirect.


   $url='the/url/you/want/to/go';
   echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';

this works for me fine.


Yes.

In essence, as long as nothing is output, you can do whatever you want (kill a session, remove user cookies, calculate Pi to 'n' digits, etc.) prior to issuing a location header.


As metioned by nixxx adding ob_start() before adding any php code will prevent the headers already sent error.

It worked for me

The code below also works. But it first loads the page and then redirects when I use it.

echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';

actually, I found this in the code of a php based cms.

redirect('?module=blog', 0);

so it is possible. In this case, you are logged in at the admin level, so no harm no foul (I suppose). the first part is the url, and the second? I can't find any documentation for what the integer is for, but I guess it's either time, or data since it is attached to a form.

I, too, wanted to refresh a page after an event, and placing this in a better spot worked out well.


I would probably set the message as a session variable, redirect the user to another page which displays the message and destroy the session.


Simple way is to use:

  echo '<script>window.location.href = "the-target-page.php";</script>';

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll