Page Redirection problem in php - php

I want to redirect from login page to my main page using php.
I use the following line of code: header('location:index.php');
inspite of redirection i received the error like:
Warning: Cannot modify header information -
headers already sent by (output started at C:\wamp\www\student\login.php:18)
in C:\wamp\www\student\login.php on line 19

This error occures if you print something before header() function.
For example:
<?php
echo 'test';
header('location:index.php');
exit;
?>
or even:
<html>
<head> .....
<?php
echo 'test';
header('location:index.php');
exit;
?>
You have to move this piece of PHP code before any operation that gives you an output.
You can also do the following trick but it is the second way you should try:
<?php
echo 'test';
ob_start();
flush();
header('location:index.php');
exit;
?>

you need to turn on the output buffer by inserting
ob_start();
at first line of php code

If you have already "echo'd" or "print'd" anything onto the page, either inside your script or outside of any set of PHP tags, then you cannot send any headers anymore. This is what your error message is stating.
Also, you should (try) to use full paths in location tags, it's better for SEO to use full URLs for every link on your website, let alone the redirects.

make sure that the header function is called before any response is outputted, e.g. header() function must be called before any echo functions or print_r, try removing the spaces before the <?php opening tag.

Its very difficult to decide what constitutes output to a page. I tried to eliminate my problem by removing all "echo's", "prints" etc but couldnt make the redirection work. I think there was a problem with a returned sql query. Adding the buffer and flushing it cured the problem.

You need to find out whether the header was sent already sent by checking line by line with header_sent() it will return true or false. If it's already sent you can't use header(). Try meta http-equiv="refresh" content="0;URL='your url'" /.Don't forget to add open and closing tags.<>

Related

Header function not working for the log out and log in

Well I have have already read the cannot modify header
But still I'm getting the error
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\xampp\web\librarian_menu.php:582)
This is my code , I don't know what i am doing wrong
<body>
<?php
#session_start();
require 'connect.php';
if(isset($_SESSION['lib']))
{
echo '<strong style="position:relative;top:25px; left:940px;">'.$_SESSION['lib'].'</strong>';
}
else
{
echo "<script>alert('You need to login first')</script>";
header('Location: quote.php');
}
if(isset($_POST['log_out']))
{
unset($_SESSION['lib']);
header('Location: quote.php');
}
?>
.
.
.
If what you posted above really is your code, then it is pretty obvious where the problem comes from. Just look at the first line of code right before your opening php tag:
<body>
<?php
#session_start();
require 'connect.php';
See the <body> tag? You output it before anything else. A similar issue exists within the else branch of the first conditional: first you echo some string, then you call the header() function. You simply must not output / echo anything prior to calling that header() function.
Note that such code might work, when the http server caches the preliminary output. But you have no guarantee for that. So you cannot rely on it. Apparently in your case that output is not cached, but sent before you cann the header() function.
The reason for this behaviour of php, for this issue is a simple one: http headers are preceding an http reply. Per definition there cannot be any content contained in a reply before the headers. So once php start to send any content it must close the headers and sent them first. If you try to add any additional headers afterwards php has no choice but to raise an error: sending simply is impossible within that reply.
You have to restructure your code to sent the headers prior to anything else. If that really is not possible, then you might want to take a look at "output buffering". It allows you to hold back any output and release it to the client only later, after having done whatever is required, for example defining additional http headers.
Any maybe a side note, just to make things crystal clear: with the message "Warning: Cannot modify header information..." php refers to the http headers, not to any html header tag you might use.
Before header function (such as session_start, header) you cannot output anything to the browser - remove echos and html tags like <body> from the code before session_start() or header().
Read the first few lines of this : http://php.net/manual/en/function.header.php

PHP: Header wont redirect [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
When i put my website online, all of the headers will not work. But when i built it, just on a local database etc. it worked "Works" fine.
I get this ERROR on the website currently:
Warning: Cannot modify header information - headers already sent by (output started at /customers/5/8/4/infuze.dk/httpd.www/index.php:22) in /customers/5/8/4/infuze.dk/httpd.www/includes/functions.php on line 16
I used my google foo a little and as far as i can understand is that i cant output any data before i use headers. But i dont thing that is the case here.
Here is the code i used in on the site.
if(empty($_GET['page'])){
header('location: index.php?page=homepage');
}
or at least one example
I usually get the error "Cannot modify header information - headers already sent by" when the page you're trying to redirect from contains information. Check to see if the script uses echo, include, require, etc., or contains HTML markup before the line at which you try to redirect.
<p>Hello!</p>
<?php
header('location: index.php?page=homepage');
?>
Will NOT work, because it sends the browser information before trying to redirect.
<?php
echo "Hi!";
header('location: index.php?page=homepage');
?>
Also won't work, because it also sends the browser information before trying to redirect.
<?php
header('location: index.php?page=homepage');
include('setup.txt');
?>
<h1>Amazing page!</h1>
WILL work, because it tries to send the browser information AFTER the redirect, but not before.
Headers won't redirect in the following conditions:
Any blank space is remaining in the file after ?> tag.
To avoid this, please avoid ending ?> tag (file end).
Please check whether, any echo or print statement is written accidentally.
Also, please check whether any HTML tag is remaining there.
If you follow, all this, your script will work.
Finally, in the starting of the file, put
ob_start()
This function will store all your page's output in a buffer and thus your redirection will work.
Try this;
<?php
ob_start();
// code
ob_end_flush();
?>
>> Call ob_start() at start of the script.
>> call ob_end_flush() at the end of script.
Thanks!

redirection in a required page in php

I have two scripts get.php and auth.php where i 've required auth.php in get.php, so here's the deal the redirection statement in auth.php i.e, header() is not working for some reason, any quick thoughts on this problem if this can be achieved or not??
As per my understanding, your problem is that:
header("location:[XYX.PHP]") is not working.
It generally does not work due to some output is print already on the page.
Please use
ob_start();
at very the beginning of the page.
This starts output buffering.
And the redirection works.
header("Location: $URL") may not work if you already sent headers by some echo, print_r or similar function.
Look at your web server error logs, does it mention something like "headers already sent" ? If yes that means you're probably outputting something before your header() function call
get.php
<?php include_once("auth.php"); ?>
auth.php
Redirect using the code below which is based on the example found at http://php.net/manual/en/function.header.php.
<?php header("Location: http://www.stackoverflow.com/"); ?>
If it still doesn't work, make sure (like it says on http://php.net/manual/en/function.header.php) that you are not outputting any html or even blank spaces or before calling the header() function. (Perhaps your get.php page is outputting empty space or HTML tags before including auth.php.)
you can use javascript function for this task
echo "window.open(url1, "name1", params);";

PHP/HTML/Javascript: Automatically leave page?

I've written a some PHP that interacts with a SQL database and is just around as an intermediate between two pages.
I want a user to automatically be forced to leave that page and move to another (or even a back to previous page function)
What is the easiest way to do this? I'm happy to use PHP, HTML, or JavaScript to do it.
From php you can use the header() function to change the location:
header("Location: newpage.html");
Just be aware that if you're using header, you can't emit any html or whitespace before you make this call unless you're buffering output. Doing so will cause warnings to the effect that headers have already been sent (there is a way to work around this).
To "move" to a page in PHP you can use the header function.
Ex: header('Location: http://www.example.com/');
In PHP I use the following code at the end of a script to move the user to the next page
<?php
// MYSQL SECTION
// PHP SECTION
header('Location: /next.php');
?>
Just make sure you haven't passed any actual HTML in the page before the header code or the script will break with an error that headers have already been sent.
If you script just interacts with SQL database and does not output anything just simply send a redirect header.
<?php
// sql interaction code goes here.
header('Location: /uri/to/secondpage.php');
exit;
?>
from PHP you can call JavaScript by this way
echo "<script>document.location.href = \"yourpage.php\"</script>";
This code wont bother if there any white space or html content before the line.
you can use the php header function
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
with following example it would be more clear to you.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
?>
but there is some limitation with the header function in 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.
in php
<?php
//the user must leave now
echo"<meta http-equiv='refresh' content='".$time_in_seconds."; URL=abc.com'>";//will move after the time specified,,0 can be specified to move immediately
exit();
?>
in js
window.location="abc.com";//will move immediately,you can time using setTimeout function

How can I redirect in PHP without header errors?

How can I redirect in PHP with this setup below without getting header output errors, I understand that nothing can be printed to the browser before a header is set, I am looking for a solution, not an explanation of why it happens please.
<?PHP
// include header
include ('header.inc.php');
// In my body section file if this is a page that requires a user be logged in then
// I run a function validlogin($url-of-page-we-are-on); inside of that file
//the function is below, it outputs a redirect to login page if not logged in
// include body of page we want
include ('SOME-FILE-HERE.php');
// include footer
include ('footer.inc.php');
// here is the function that is in the body pages, it is only called on a page that we require a logged in user so there are hundreds of pages that do have this and a bunch that don't, it's on a page to page basis
function validlogin($url) {
if ($_SESSION['auto_id'] == '') {
$msg = 'Please login';
$_SESSION['sess_login_msg'] = $msg;
$_SESSION['backurl'] = $url;
$temp = '';
header("Location: /");
exit();
}
}
?>
I would like to user php's header function and not a meta or javascript redirect
Also maintainning a list of pages that require login or not is not an option here if possible
Use ob_start() in the first line even befor the include. so you can set headers anytime.
Can't you just do this:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
include ('SOME-FILE-HERE.php');
include ('footer.inc.php');
?>
Or, put the include files in every one of the "SOME-FILE-HERE"-type files, if that's possible, so you end up with:
<?php
validlogin($url); // call the function here
include ('header.inc.php');
?>
<h1>Page heading</h1>
...page content etc...
<?php
include ('footer.inc.php');
?>
use { echo '<META HTTP-EQUIV="Refresh" Content="0; URL=process.php">';}
As long as you have no script output before the header() function you should be fine. Check there are no echo's or whitespace. Also putting ob_start() at the beginning can help. sometimes there is invisible whitespace - changing the format of your document to ANSI or Unicode may help!
As a note (although I think you already know) header does not terminate the script so the exit() (which you have) is a definite requirement.
Does the footer.inc.php and SOME-FILE-HERE.php write to the response stream immediately? Because if so, this won't work as you will have already written something before you sent the headers.
You need to buffer the ouput so that the HTTP header is not send on the first output. You can either buffer any ouput implicitly by enabling ouput_buffering or explicitly by calling ob_start. But the latter has to be called before the first output, so ideally in the first line of the script that’s initially called.
As already mentioned by the others use ob_start() or the output_buffer-setting to buffer the output. Apart from that it's from my point of view not a good practice to output content in the middle of functional code but this is a another topic.
You can find more information at Google or in this Article about Output Buffering in PHP.

Categories