How to redirect in php?

how to redirect in HTML?

As you know,redirect to other page in HTML is sample,and have many ways:

<head>
<!-- Reload page after 10 seconds from page loaded. -->
<meta http-equiv="refresh" content="10">
<!-- after 5 seconds redirect to page hello.html-->
<meta http-equiv="refresh" content="5;url=hello.html">
</head>

how to redirect in php?

But,I was asked many times:how to redirect in php?

Actually,there are a php redirect page function,it is header()

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

How to use php header redirect function Parameters?

Parameter $string:

The header string.

There are two special-case header calls. The first is a header that starts with the string “HTTP/” (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
header("HTTP/1.0 404 Not Found");
?>

For FastCGI you must use the following for a 404 response:

<?php
header("Status: 404 Not Found");
?>

The second special case is the “Location:” header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

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

Parameter $replace:

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

Parameter $http_response_code:

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty.

This php redirect code Note:

1.Before this fuction header(),can not have any output.

2.After this fuction header(),php code will be execute yet,to make sure stop it,you can add exit function.

Also,you can use this function to download files,just like:

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header(‘Content-Disposition: attachment; filename=”downloaded.pdf”‘);// The PDF source is in original.pdf
readfile(‘original.pdf’);
?>
And read more about simple php redirect code or php redirect script,you can find at this http://php.net/manual/en/function.header.php

Related Blogs

Related Blogs

Related Blogs


Related Blogs

    About admin