How to redirect a person after loggin - php

I'm using the below function to redirect a person after specific task (eg.: after login, after logout, after searching etc.)
code is below:
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url){
header("location: $url");
exit();
}
// Some other function below
?>
But now I'm dealing this class with many project of different host (MLM project). I have a problem now. With some server it works as i expected, but in some other server, it's not redirecting. If i enable error_reporting(E_ALL); i found a notice that headers are already send. So I'm in confusion that what can I do now instead of header() function. Also i tried the below code
<?php
function redirection($url){
echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
exit();
}
?>
But it is not desirable as everybody wants automatic redirection. My servers are windows and linux both. Please help me anyone

well, this situation is very common, then you can simple turn on output buffering (the output will be stored in an internal buffer).
Use ob_start(); in the very first line of your application
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url)
{
header("location: $url");
exit();
}
// Some other function below
}
?>
<?php
ob_start("redirection");
// Your Common Class Page
include("Common.php");
// some code
ob_end_flush(); // turn off output buffering
?>

One way to deal with this is to test if the header has already been sent before calling header(location). You could use mix both solutions:
<?php
class common {
/* Redirect to another page
* $url= Url to go
*/
function redirection($url){
if (!headers_sent()) {
header("location: $url");
} else {
echo "<div align='center'><a href='$url' target='_top'><img src='../img/proceed.jpg' alt='Proceed>>' align='absmiddle' border='0'></a></div>";
}
exit();
}
// Some other function below
?>
This way if the headers haven't been sent, you redirect automatically. If they have, you ask the client to click.
This is the reason why when you see a redirection notice in most websites, it also includes a sentence stating - if you are not redirected automatically, please click here...
Hope this helps.
Good luck!

If headers have already been sent, it is likely because content has already been written out to the screen (via an echo, print, or similar). Since your class has no control over what came before it was instantiated and the function was called, it seems unlikely that you can do much to avoid your client PHP (what calls your class) from writing anything out before. Either use Javascript or use Apache redirects.

I would try using:
header("Location: ".$url, TRUE, 302);
If you want to use a different method, or called "refresh" method,
header("Refresh:0;url=".$url);
Both would work in every case. The problem with your header is, you need to let them know it's a 302 redirect, as well as set TRUE to replace the existing headers. If header is already set, you need to replace it using TRUE boolean.
302 is also the common HTTP response code for redirection, which needs to be specified when you are trying to redirect using header.
The Refresh method works fine as well, though it has compatibility issues with older browsers.
http://en.wikipedia.org/wiki/HTTP_302
http://php.net/manual/en/function.header.php

the easiest way is to do it through client side. javascript...
window.location= url

Related

How can I "redirect" a get request with PHP? [duplicate]

Is it possible to redirect a user to a different page through the use of PHP?
Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?
This could even protect my pages from unauthorized users.
Summary of existing answers plus my own two cents:
1. Basic answer
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
header('Location: '.$newURL);
2. Important details
die() or exit()
header("Location: https://example.com/myOtherPage.php");
die();
Why you should use die() or exit(): The Daily WTF
Absolute or relative URL
Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.
Status Codes
PHP's "Location"-header still uses the HTTP 302-redirect code, this is a "temporary" redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).
Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.
3. Documentation
HTTP Headers and the header() function in PHP
What the PHP manual says
What Wikipedia says
What the W3C says
4. Alternatives
You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.
5. Helper Functions
This function doesn't incorporate the 303 status code:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('https://example.com/', false);
This is more flexible:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6. Workaround
As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:
<meta http-equiv="refresh" content="0;url=finalpage.html">
Or a JavaScript redirect even.
window.location.replace("https://example.com/");
Use the header() function to send an HTTP Location header:
header('Location: '.$newURL);
Contrary to what some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.
File example.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
Result of three executions:
bart#hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
Resuming — obligatory die()/exit() is some urban legend that has nothing to do with actual PHP. It has nothing to do with client "respecting" the Location: header. Sending a header does not stop PHP execution, regardless of the client used.
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
Don't forget to die() / exit() !
Output JavaScript from PHP using echo, which will do the job.
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.
For more about buffering (advantages)
What is output buffering?
1. Without header
here you will not face any problem
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2. Using header function with exit()
<?php
header('Location: target-page.php');
exit();
?>
but if you use header function then some times you will get "warning
like header already send" to resolve that do not echo or print before sending headers or you can simply use die() or exit() after header function.
3. Using header function with ob_start() and ob_end_flush()
<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>
Most of these answers are forgetting a very important step!
header("Location: myOtherPage.php");
die();
Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not have to respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.
Use:
<?php header('Location: another-php-file.php'); exit(); ?>
Or if you've already opened PHP tags, use this:
header('Location: another-php-file.php'); exit();
You can also redirect to external pages, e.g.:
header('Location: https://www.google.com'); exit();
Make sure you include exit() or include die().
You can use session variables to control access to pages and authorize valid users as well:
<?php
session_start();
if (!isset( $_SESSION["valid_user"]))
{
header("location:../");
exit();
}
// Page goes here
?>
http://php.net/manual/en/reserved.variables.session.php.
Recently, I got cyber attacks and decided, I needed to know the users trying to access the Admin Panel or reserved part of the web Application.
So, I added a log access for the IP address and user sessions in a text file, because I don't want to bother my database.
Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URL and generate the rest, then you can do something like this...
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/'; // <-- Your relative path
header('Location: ' . $url, true, 302); // Use either 301 or 302
header( 'Location: http://www.yoursite.com/new_page.html' );
Use the following code:
header("Location: /index.php");
exit(0);
I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status header to properly redirect).
function Redirect($url, $code = 302)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (headers_sent() !== true)
{
if (strlen(session_id()) > 0) // If using sessions
{
session_regenerate_id(true); // Avoids session fixation attacks
session_write_close(); // Avoids having sessions lock other requests
}
if (strncmp('cgi', PHP_SAPI, 3) === 0)
{
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
I've also handled the issue of supporting the different HTTP redirection codes (301, 302, 303 and 307), as it was addressed in the comments of my previous answer. Here are the descriptions:
301 - Moved Permanently
302 - Found
303 - See Other
307 - Temporary Redirect (HTTP/1.1)
To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:
<?php
header('Location: mypage.php');
?>
In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)
Relative/Absolute Path
When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:
<?php
header('Location: /directory/mypage.php');
?>
If ever the target page is on another server, you include the full URL:
<?php
header('Location: http://www.ccm.net/forum/');
?>
HTTP Headers
According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!
Temporary/Permanent Redirections
By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.
If you would like to notify search engines that a page has been permanently moved to another location, use the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: new_address');
?>
For example, this page has the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: /pc/imprimante.php3');
exit();
?>
When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.
Interpretation of PHP Code
The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: address');
exit();
?>
header("Location: https://www.example.com/redirect.php");
Direct redirect to this link https://www.example.com/redirect.php
$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");
First get $redirect value and than redirect to [value] like: https://www.example.com/redirect.php
Use:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
This is a regular and normal PHP redirect, but you can make a redirecting page with a few seconds wait by the below code:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
Yes, it's possible to use PHP. We will redirect to another page.
Try following code:
<?php
header("Location:./"); // Redirect to index file
header("Location:index.php"); // Redirect to index file
header("Location:example.php");
?>
To redirect in PHP use:
<?php header('Location: URL'); exit; ?>
In the eve of the semantic web, correctness is something to consider. Unfortunately, PHP's "Location"-header still uses the HTTP 302-redirect code, which, strictly, isn't the best one for redirection. The one it should use instead, is the 303 one.
W3C is kind enough to mention that the 303-header is incompatible with "many pre-HTTP/1.1 user agents," which would amount to no browser in current use. So, the 302 is a relic, which shouldn't be used.
...or you could just ignore it, as everyone else...
You can use some JavaScript methods like below
self.location="http://www.example.com/index.php";
window.location.href="http://www.example.com/index.php";
document.location.href = 'http://www.example.com/index.php';
window.location.replace("http://www.example.com/index.php");
Yes, you can use the header() function,
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
And also best practice is to call the exit() function right after the header() function to avoid the below code execution.
According to the documentation, header() must be called before any actual output is sent.
Like others here said, sending the location header with:
header( "Location: http://www.mywebsite.com/otherpage.php" );
but you need to do it before you've sent any other output to the browser.
Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.
Here are my thoughts:
IMHO, the best way to redirect an incoming request would be by using location headers, which goes
<?php
header("Location: /index.php");
?>
Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.
Although this is a quick-and-dirty way to achieve what was originally asked, it would eventually turn out to be an SEO disaster, as this kind of redirect is always interpreted as a 301 / 302 redirect, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page.
Hence it will affect the SEO settings of the website.
The best way to redirect with PHP is the following code...
header("Location: /index.php");
Make sure no code will work after
header("Location: /index.php");
All the code must be executed before the above line.
Suppose,
Case 1:
echo "I am a web developer";
header("Location: /index.php");
It will redirect properly to the location (index.php).
Case 2:
return $something;
header("Location: /index.php");
The above code will not redirect to the location (index.php).
You can try using
header('Location:'.$your_url)
for more info you can refer php official documentation
We can do it in two ways:
When the user comes on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php
By the below PHP code
<?php
header("Location: https://bskud.com/PINCODE/BIHAR.php");
exit;
?>
Save the above code in https://bskud.com/PINCODE/BIHAR/index.php
When any condition is true then redirect to another page:
<?php
$myVar = "bskud";
if ($myVar == "bskud") {
?>
<script> window.location.href="https://bskud.com"; </script>
<?php
}
else {
echo "<b>Check the website name again</b>";
}
?>
1. Using header, a built-in PHP function
a) Simple redirect without parameters
<?php
header('Location: index.php');
?>
b) Redirect with GET parameters
<?php
$id = 2;
header("Location: index.php?id=$id&msg=succesfully redirect");
?>
2. Redirect with JavaScript in PHP
a) Simple redirect without parameters
<?php
echo "<script>location.href='index.php';</script>";
?>
b) Redirect with GET parameters
<?php
$id = 2;
echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
?>
Using header function for routing
<?php
header('Location: B.php');
exit();
?>
Suppose we want to route from A.php file to B.php than we have to take help of <button> or <a>. Lets see an example
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
There are multiple ways of doing this, but if you’d prefer php, I’d recommend the use of the header() function.
Basically
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
If you want to kick it up a notch, it’s best to use it in functions. That way, you are able to add authentications and other checking elemnts in it.
Let’s try with by checking the user’s level.
So, suppose you have stored the user’s authority level in a session called u_auth.
In the function.php
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
You’ll then call the function for every page that you want to authenticate.
Like in page.php or any other page.
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
References;
http://php.net/manual/en/function.header.php
I like the kind of redirection after counting seconds
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");

Redirect in the helper file does not work in Laravel

The redirect() helper function in the helper file does not work in Laravel.
Here is my code helpers.php
if (! function_exists('license_check')) {
function license_check(){
//This does not work, returns a blank page
return redirect()->route('loginlicense');
//This does not work, returns a blank page
return \Redirect::route('loginlicense');
//This work but it prints on the browser before redirecting
echo \Redirect::route('loginlicense');
echo redirect()->route('loginlicense');
//This work but it prints on the browser before redirecting
die(\Redirect::route('loginlicense'));
die(redirect()->route('loginlicense'));
//The below works. But I would like to pass laravel flash sessions with `Laravel's with('status', 'My mesage')`
$url = route('loginlicense');
header("Location: ".$url);
exit();
}
}
license_check();
Why am I getting a blank page instead of being redirected to the url specified while using Redirect:: or redirect().
Same Issue
I had this issue - and did not want every controller action to worry about what this helper could deal with, so I figured that "Needs to be returned to the browser" could be accomplished by an echo and exit;
My Solution
// Redirect to the login?
if (empty($admin) || empty($token)) {
// I have to echo the redirect in order to return the response from here.
echo redirect('/admin/login');
exit;
}
More Explanation
Redirect - set headers only, before output.
When you redirect in PHP, you are only setting headers - that's what the redirect() function will do. This function derives to a Redirect Facade method to(), which returns a laravel RedirectResponse. When "echoing" it should only give back a response with headers and no body.
This means you cannot start outputting before the redirect. Remove any var_dumps, included template/view files, or other echos! Even a blank string or line space in a template file can ruin this.
Remember, you are server-side!
You would not be able to (due to errors - see headers already sent), or want to, redirect in the middle of a template file, because PHP is the language that is processed on the server side - so just once... if you need to be redirecting within a rendered view (probably based on some condition), use javascript!
More about "echo"
Because we are doing an echo redirect(), you may be scared of what the echo means. It is just sending back the full response (with only headers if done right!)
Sometimes I think that it is harder for people to realize that the only way PHP can ever send back a response (headers and the body) is through an echo (or similar outputting functions eg. printf, var_dump, etc), but most frameworks do not make you aware of this, so your only experience with echo is inside of templates.
Ps. Some frameworks utilize output_buffering to store the "echo" results in a buffer for last minute processing before sending everything.
Test it in your network tab of your browser
If you are doing it right, in the network tab of the browser, you will see a status code of 302 and the response section will say "Failed to load a response..." because it was redirecting.
If you are seeing the URL or anything else in the response tab, eg. the url , it is likely because you are sending out content via a var_dump, including a template file, or another echo that is creating a response body. Try using your browser network tab and preserve the log to see what is happening.
Even sending an empty string or line break counts as a response body (hence blank page). Typically you should get warnings about trying to set headers after some of the response body has already been sent in PHP. Basically, you should not be including a template or echoing anything out before a redirect. Your logic should process the redirect first thing!
The exit is there to make sure it does not go on to include your view or echo more things out!
It's because invoking redirect() by calling it inside a function does not work. Just like what Quezler said, it needs to be returned to the browser.
You can handle redirect in the controller. Helper function return a boolean value, or maybe throw exceptions.
helper.php
if (! function_exists('license_check')) {
function license_check($id) {
if($id == 2){
return true;
} else {
return false;
}
}
}
HomeController.php
use Session;
$check_lic = license_check(2);
if($check_lic) {
session()->flash('success', 'Your message!');
return redirect()->route('loginlicense');
} else {
session()->flash('error', 'you have not purchase licence!');
return redirect()->back();
}

Send users to page after form submit [duplicate]

Is it possible to redirect a user to a different page through the use of PHP?
Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?
This could even protect my pages from unauthorized users.
Summary of existing answers plus my own two cents:
1. Basic answer
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
header('Location: '.$newURL);
2. Important details
die() or exit()
header("Location: https://example.com/myOtherPage.php");
die();
Why you should use die() or exit(): The Daily WTF
Absolute or relative URL
Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.
Status Codes
PHP's "Location"-header still uses the HTTP 302-redirect code, this is a "temporary" redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).
Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.
3. Documentation
HTTP Headers and the header() function in PHP
What the PHP manual says
What Wikipedia says
What the W3C says
4. Alternatives
You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.
5. Helper Functions
This function doesn't incorporate the 303 status code:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('https://example.com/', false);
This is more flexible:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6. Workaround
As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:
<meta http-equiv="refresh" content="0;url=finalpage.html">
Or a JavaScript redirect even.
window.location.replace("https://example.com/");
Use the header() function to send an HTTP Location header:
header('Location: '.$newURL);
Contrary to what some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.
File example.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
Result of three executions:
bart#hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
Resuming — obligatory die()/exit() is some urban legend that has nothing to do with actual PHP. It has nothing to do with client "respecting" the Location: header. Sending a header does not stop PHP execution, regardless of the client used.
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
Don't forget to die() / exit() !
Output JavaScript from PHP using echo, which will do the job.
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.
For more about buffering (advantages)
What is output buffering?
1. Without header
here you will not face any problem
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2. Using header function with exit()
<?php
header('Location: target-page.php');
exit();
?>
but if you use header function then some times you will get "warning
like header already send" to resolve that do not echo or print before sending headers or you can simply use die() or exit() after header function.
3. Using header function with ob_start() and ob_end_flush()
<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>
Most of these answers are forgetting a very important step!
header("Location: myOtherPage.php");
die();
Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not have to respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.
Use:
<?php header('Location: another-php-file.php'); exit(); ?>
Or if you've already opened PHP tags, use this:
header('Location: another-php-file.php'); exit();
You can also redirect to external pages, e.g.:
header('Location: https://www.google.com'); exit();
Make sure you include exit() or include die().
You can use session variables to control access to pages and authorize valid users as well:
<?php
session_start();
if (!isset( $_SESSION["valid_user"]))
{
header("location:../");
exit();
}
// Page goes here
?>
http://php.net/manual/en/reserved.variables.session.php.
Recently, I got cyber attacks and decided, I needed to know the users trying to access the Admin Panel or reserved part of the web Application.
So, I added a log access for the IP address and user sessions in a text file, because I don't want to bother my database.
Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URL and generate the rest, then you can do something like this...
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/'; // <-- Your relative path
header('Location: ' . $url, true, 302); // Use either 301 or 302
header( 'Location: http://www.yoursite.com/new_page.html' );
Use the following code:
header("Location: /index.php");
exit(0);
I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status header to properly redirect).
function Redirect($url, $code = 302)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (headers_sent() !== true)
{
if (strlen(session_id()) > 0) // If using sessions
{
session_regenerate_id(true); // Avoids session fixation attacks
session_write_close(); // Avoids having sessions lock other requests
}
if (strncmp('cgi', PHP_SAPI, 3) === 0)
{
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
I've also handled the issue of supporting the different HTTP redirection codes (301, 302, 303 and 307), as it was addressed in the comments of my previous answer. Here are the descriptions:
301 - Moved Permanently
302 - Found
303 - See Other
307 - Temporary Redirect (HTTP/1.1)
To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:
<?php
header('Location: mypage.php');
?>
In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)
Relative/Absolute Path
When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:
<?php
header('Location: /directory/mypage.php');
?>
If ever the target page is on another server, you include the full URL:
<?php
header('Location: http://www.ccm.net/forum/');
?>
HTTP Headers
According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!
Temporary/Permanent Redirections
By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.
If you would like to notify search engines that a page has been permanently moved to another location, use the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: new_address');
?>
For example, this page has the following code:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: /pc/imprimante.php3');
exit();
?>
When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.
Interpretation of PHP Code
The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:
<?
header('Status: 301 Moved Permanently', false, 301);
header('Location: address');
exit();
?>
header("Location: https://www.example.com/redirect.php");
Direct redirect to this link https://www.example.com/redirect.php
$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");
First get $redirect value and than redirect to [value] like: https://www.example.com/redirect.php
Use:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
This is a regular and normal PHP redirect, but you can make a redirecting page with a few seconds wait by the below code:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
Yes, it's possible to use PHP. We will redirect to another page.
Try following code:
<?php
header("Location:./"); // Redirect to index file
header("Location:index.php"); // Redirect to index file
header("Location:example.php");
?>
To redirect in PHP use:
<?php header('Location: URL'); exit; ?>
In the eve of the semantic web, correctness is something to consider. Unfortunately, PHP's "Location"-header still uses the HTTP 302-redirect code, which, strictly, isn't the best one for redirection. The one it should use instead, is the 303 one.
W3C is kind enough to mention that the 303-header is incompatible with "many pre-HTTP/1.1 user agents," which would amount to no browser in current use. So, the 302 is a relic, which shouldn't be used.
...or you could just ignore it, as everyone else...
You can use some JavaScript methods like below
self.location="http://www.example.com/index.php";
window.location.href="http://www.example.com/index.php";
document.location.href = 'http://www.example.com/index.php';
window.location.replace("http://www.example.com/index.php");
Yes, you can use the header() function,
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
And also best practice is to call the exit() function right after the header() function to avoid the below code execution.
According to the documentation, header() must be called before any actual output is sent.
Like others here said, sending the location header with:
header( "Location: http://www.mywebsite.com/otherpage.php" );
but you need to do it before you've sent any other output to the browser.
Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.
Here are my thoughts:
IMHO, the best way to redirect an incoming request would be by using location headers, which goes
<?php
header("Location: /index.php");
?>
Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.
Although this is a quick-and-dirty way to achieve what was originally asked, it would eventually turn out to be an SEO disaster, as this kind of redirect is always interpreted as a 301 / 302 redirect, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page.
Hence it will affect the SEO settings of the website.
The best way to redirect with PHP is the following code...
header("Location: /index.php");
Make sure no code will work after
header("Location: /index.php");
All the code must be executed before the above line.
Suppose,
Case 1:
echo "I am a web developer";
header("Location: /index.php");
It will redirect properly to the location (index.php).
Case 2:
return $something;
header("Location: /index.php");
The above code will not redirect to the location (index.php).
You can try using
header('Location:'.$your_url)
for more info you can refer php official documentation
We can do it in two ways:
When the user comes on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php
By the below PHP code
<?php
header("Location: https://bskud.com/PINCODE/BIHAR.php");
exit;
?>
Save the above code in https://bskud.com/PINCODE/BIHAR/index.php
When any condition is true then redirect to another page:
<?php
$myVar = "bskud";
if ($myVar == "bskud") {
?>
<script> window.location.href="https://bskud.com"; </script>
<?php
}
else {
echo "<b>Check the website name again</b>";
}
?>
1. Using header, a built-in PHP function
a) Simple redirect without parameters
<?php
header('Location: index.php');
?>
b) Redirect with GET parameters
<?php
$id = 2;
header("Location: index.php?id=$id&msg=succesfully redirect");
?>
2. Redirect with JavaScript in PHP
a) Simple redirect without parameters
<?php
echo "<script>location.href='index.php';</script>";
?>
b) Redirect with GET parameters
<?php
$id = 2;
echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
?>
Using header function for routing
<?php
header('Location: B.php');
exit();
?>
Suppose we want to route from A.php file to B.php than we have to take help of <button> or <a>. Lets see an example
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
There are multiple ways of doing this, but if you’d prefer php, I’d recommend the use of the header() function.
Basically
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
If you want to kick it up a notch, it’s best to use it in functions. That way, you are able to add authentications and other checking elemnts in it.
Let’s try with by checking the user’s level.
So, suppose you have stored the user’s authority level in a session called u_auth.
In the function.php
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
You’ll then call the function for every page that you want to authenticate.
Like in page.php or any other page.
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
References;
http://php.net/manual/en/function.header.php
I like the kind of redirection after counting seconds
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");

How to declare more than one header on PHP

I want to send my users to different pages based on user action. So I made multiple functions at the top of the page like so:
<?php
function one() {
header("location: pagea.php");
}
function two() {
header("location: pageb.php");
}
function three() {
header("location: pagec.php");
}
?>
Of course I get an error because I am re declaring headers. At first I though it was going to be okay since I am containing them inside functions and am calling any one function at a time. But still I get the error. Is there any other way of doing this?
I think you misunderstand what the HTTP header Location does.
The Location header instructs the client to navigate to another page. You cannot send more the one Location header per page.
Also, PHP sends headers right before the first output. Once you output, you cannot specify any more headers (unless you are using Output Buffering).
If you specify the same header twice, by default, header() will replace the previous value with the latest one... For example:
<?php
header('Location: a.php');
header('Location: b.php');
header('Location: c.php');
will redirect the user to c.php, never once passing by a.php or b.php. You can override this behavior by passing a false value to the second parameter (called $replace):
<?php
header('X-Powered-By: MyFrameWork', false);
header('X-Powered-By: MyFrameWork Plugin', false);
The Location header can only be specified once. Sending multiple Location header will not redirect the users to the pages... It will probably confuse the crap out of the UA. Also, understand that the code continues to execute after sending a Location header. So follow that call to header() with an exit. Here is a proper redirect function:
function redirect($page) {
header('Location: ' . $page);
exit;
}
Either they aren't all in functions or more than one is being called.
Try something like this:
<?php
$page = // use an if statement or whatever you need to figure out
//which page you need (pagea.php, etc.)
fnx($page)
function fnx($page) {
header("location: " . $page);
}
?>
or
<?php
$page = // use an if statement or whatever you need to figure out
//which page you need (pagea.php, etc.)
header("location: " . $page);
?>
You're getting that error because your script has already produced output (you used echo/print before calling header()). You need to call header() before your script produces any output.
From the PHP Manual
http://php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
You'll get the following error when you attempt to call header() after sending any output...
Warning: Cannot modify header information - headers already sent
Here is how i like to do when i need to send multiple headers :
$headers = array(
'Location' => 'http://www.stackoverflow.com',
'Content-Type' => ' application/pdf',
);
foreach ($headers as $headerType => $headerValue)
{
header($headerType . ': ' . $headerValue);
}
Use headers_sent() to check if you'll be able to send headers or not.
function one() {
return "location: pagea.php";
}
function two() {
return "location: pageb.php";
}
function three() {
return "location: pagec.php";
}
header(one()); // for example
Maybe something like that?
For the sake of people who may be coming here from Google, if you're interested in having multiple of the same type of header:
It is technically possible to have multiple headers that are of the same type passed in PHP. header has a parameter called "replace". From the documentation:
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.
So you should be able to write:
header("location: pagea.php"); #You want to overwrite the initial one, so you'd have this one be default, or true
header("location: pageb.php",false);
header("location: pagec.php",false);
Of course, if your type of header can't be had multiple times, you'll get an error. In this case you get this error (written this way in Chrome):
This page isn’t working
localhost sent an invalid response.
ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION
For other headers, however, this method should work fine. The example they supply is:
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
I have a nice solution:
die(header("Location: someting.php"));
You can do that as often as you want.
(Nothing else worked for me and to me this is a nice alternative).
Especially for everyone who has a problem with using multiple options for "header" (on my site it would always just take one, no matter what I did).
You can try something like that.
<?php
function one() {
$redirect=pagea.".".php;
}
function two() {
$redirect=pageb.".".php;
}
function three() {
$redirect=pagec.".".php;
}
header("location:".$redirect);
?>

PHP page redirect [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 5 years ago.
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".
}
Yes, you would use the header function.
/* Redirect browser */
header("Location: http://www.yourwebsite.com/user.php");
exit();
It is a good practice to call exit() right after it so that code below it does not get executed.
Also, from the documentation:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
This means you should not echo anything right before the header() function, as doing so will more than likely throw an error. Also, you will need to verify that this code gets run before any other output as well.
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).
Simple way is to use:
echo '<script>window.location.href = "the-target-page.php";</script>';
$url='the/url/you/want/to/go';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
this works for me fine.
header( "Location: http://www.domain.com/user.php" );
But you can't first do an echo, and then redirect.
<?php
http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);
?>
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.'">';
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;
?>
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.
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");

Categories