echo after session - php

I have the code below:
<?php
session_start();
echo "\n\n";
echo "inputAction.php started";
//echo "<br/><br/>";
$name = $_POST["theUser"];
$passw = $_POST["thePassword"];
if (!strcmp($name, "myPassw") && !(strcmp($passw, "1234")) )
{
//echo "correct";
$_SESSION['sessionUser']=$name;
$_SESSION['sessionPassword']=$passw;
header("location:a.php");
}
else
{
//echo "wrong";
header("Location: index.php");
}
?>
My first attempt here is to echo "inputAction.php started"; after session_start();
However, I found out that I got an error:
inputAction.php started
Warning: Cannot modify header information - headers already sent by (output started at /Library/WebServer/Documents/01032011/inputAction.php:4) in /Library/WebServer/Documents/01032011/inputAction.php on line 16
But I notice that this will be fine if I comment out the echo after session_start();
<?php
session_start();
//echo "\n\n";
//echo "inputAction.php started";
//echo "<br/><br/>";
$name = $_POST["theUser"];
$passw = $_POST["thePassword"];
if (!strcmp($name, "myPassw") && !(strcmp($passw, "1234")) )
{
//echo "correct";
$_SESSION['sessionUser']=$name;
$_SESSION['sessionPassword']=$passw;
header("location:a.php");
}
else
{
//echo "wrong";
header("Location: index.php");
}
?>
What happened? Can somebody explain why echo makes the error?
Does that mean that it's a rule not to use echo after session_start?
Any other ways to print logs (alternative to echo) that I can use after session_start?

No, the rule is rather not to output anything before header. And if you take a closer look onto the error message, it says: “Cannot modify header information […] on line 16” because “output started at […]:4”.
The line where the output started does not need to be the first one with echo as PHP does also have an internal buffer that is not flushed with every echo call.
If you want to output something before header you need to buffer it using the output control. So just call ob_start before anything else and every output is buffered so that the HTTP header can be modified even if some output already happened:
<?php
ob_start();
session_start();
// …

That warning is produced with calling the header() function. The header() function sets HTTP header for the response you are sending back. And HTTP header must be the first thing in the response. No other output can be displayed before them.
There are many solutions to this problem. One is to turn on output buffering, which will magically take care of this. The better solution is to structure your code so that you don't output anything before any calls to the header() (or session_start() function). If you would use some MVC framework (cakephp, symphony, zend, ...) you wouldn't even have to worry about it.
This exact problem has been dealt here numerous times (it's one of the most popular questions about PHP). Look at this search results.
Also invest some time in reading PHP's error messages. The error message you provided clearly states that the error was "thrown" in the header() line, and which line started the output.

You've already sent information to the browser with the \n\n, so the browser constructed a page with default headers, as it will do if you send it any text at all (even a single character).
The browser's thinking, "OK, this is just plaintext, so I'll make it into HTML the best I know how and output it." As it does this, headers are made, and the document body is created, so any more headers you want to send it are ignored until this process is restarted (with a refresh).
For this not to happen, don't send any information to the browser until you're ready for it to start constructing the page.
Object buffering is an intermediate-difficulty topic that will take a while to get right if you haven't done it before.

Because you are using the header() function in your else statement, anytime your code goes in there, it tries to redirect your page. However, like Gumbo said, header() will throw an error if there is anything output to the browser before it is called.

If you want it to echo that and then redirect, so that the user can see it, you could do it with some good, old-fashioned HTML, and you would have control over how long it took to move to the next page.
session_start();
echo '<head><meta http-equiv="refresh" content="5;url=http://www.whatever.com/a.php"></head>';
echo "\n\n";
echo 'inputAction.php started';
etc.etc.etc.
But of course, you would still have to test the input to determine what url=, which means you'd either test twice or just put the echo in the ifs anyway. Of course, it doesn't matter where the initial echos are if using ob_start() because it will only be output when the script is finished running.
Also, you really shouldn't store passwords in the Session.

Related

PHP: header not working

Ive read pretty much alot of post about this but seems like its not helping me.
I have been working an a testing local server and everything has been working swimmingly, but when I uploaded it to the web the php is suddenlly not working properly. I am connected to the db and all. the main issues I have is with the header (as far as I know).
I have been shaving bits of code and simplifying it to narrow down the problem and came to the conclusion that it was the header:
<?php
require 'admin/Connections/Connections.php';
session_destroy();
if(isset($_POST['Login'])){
$UN = $_POST['Username'];
$PW = $_POST['password1'];
$result = mysql_query("select * from admin where Username='$UN'");
$row = mysql_fetch_array($result);
echo $row['Password'];
echo $_POST['password1'];
if($PW == $row['Password']){
header('Location: admin/home.php');
}else{
$_SESSION["LoginFail"] = "Yes";
}
}
?>
the echo spits out both $post and $row as the same value so I know it should execute the header, but it just refreshes the page with the added echos.
I tried replacing the url with something like http://www.google.com/ but that takes me to a blank page with the echos. what am I missing? if it is something obvious you have permission to trash me as long as you give me an answer...
Echoing output before you use header() will stop the header from working. From the PHP documentation for header():
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.
At minimum, the header() call should precede the echo calls you have in your code. If that doesn't work, check to see if any output is happening in the require()ed file at the top of your code.
You are outputting HTML with echo. Therefore, header will not redirect.
Solutions:
1) Add ob_start() at the page start. This will store all your output to buffer and thus your page will not have any HTML output, redirection will occur.
2) Comment the code of echos.
3) Use javascript redirect:
echo "<script>window.location.href='admin/home.php';</script>";
This will work irrespective of what is output on the page.
You cant use PHP's header function after an echo, just put it before your echo, then it should work.
You cannot use header() function if you make any output to the client. Sometimes it's referred as "headers already sent" notice.
Also, consider moving alway from mysql_* functions as they're deprecated and won't be supported anymore. Try mysqli.
First, remove your echo statements or comment them.
when you are taking the user to some other page why the hell are you echoing anything here? To show to whom?
and write ob_start(); at the top of your PHP file i.e:
<?php
ob_start();
--------the rest of your code---

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 redirect on submit not working

Many thanks in advance for even attempting to present a solution.
I'm having trouble with a simple html contact form.
The form's method is set to post and it's action is sent to a php file.
At the end of the PHP file the form is sent to, there is a basic location:redirection.
ex) header("Location: ../index.htm");
I configured my php.ini file (Apache) to display the php error(s).
This is what I'm shown:
"Cannot modify header information - headers already sent by (output started at /home2/jwarddes/public_html/newTest/php/contact.php:2) in /home2/jwarddes/public_html/newTest/php/contact.php on line 20"
Line 20 of my code is my header("location:... redirect. This appears to be fine, yet something keeps throwing an error.
Needless to say, I'm stumped.
Could someone please try their hand at a solution or kindly nudge me in the right direction?
Thanks!
I have had this problem many times before, I've seen solutions here and there which haven't worked. In my case I have put it down to the fact that I (php include) my pages into an index, which already has a header attribute.
The way I have worked around this is to use the meta method, echo '<meta http-equiv="refresh" content="0;url=<URL>" />';
To make your page look a little better, you can add a one or two second delay and do something like...
if ($ = $) { echo '(H1)Redirecting you to...(/H1)'; echo '<meta http-equiv="refresh" content="1;url=<URL>" />'; }
that is a common problem.
make sure you do not have any output (even a simple space at the top of the page) as that will send the headers prior to your redirect.
Possible Solutions are the following.
ob_start();
in the top of your page and
ob_end_flush();
at the bottom might solve your issue.
Also, I have this special function below which do a very smart redirect, try it out and let me know :)
/**
* redirect()
*
* Attempts to redirect the user to another page.
* It tries to PHP header redirect, then JavaScript redirect, then try http redirect.
* The following redirection method is only attempted if the previous redirection method attempt has failed
*
* #param mixed $url To be redirected to
* #return nothing
*/
function redirect($url)
{
if (!headers_sent())
{ //If headers not sent yet... then do php redirect
header('Location: ' . $url);
exit;
} else
{ //If headers are sent... do java redirect... if java disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="' . $url . '";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
echo '</noscript>';
exit;
}
} //==== End -- Redirect
There should not be any output (echo) send to browser before this line:
header("Location: ../index.htm");
Post your code, so that I can find out the exact issue
From the manual:
PHP header()
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 can't have anything printed out to the browser before using the redirect.
Anyway if you really want to do that you can do such trick:
echo "<script>location.href='...';</script>"
But that's not recommended as whatever you print out before you redirect cannot be seen by the user so why bother letting it out?
its most probably because of a space at the starting or ending tag of
check that I had the very similar problems when working on...

PHP code will not execute unless there is an echo at a certain spot. Why is this?

$result=mysql_query($sql_info) or die("Error 1: ".mysql_error());
$no= mysql_fetch_array($result);
$groups_no = $no['number'];
mysql_num_rows($result) or die("Error 2: ".mysql_error());
// echo "what's going on?"; if I uncomment this line then the echo below executes
if(($this->user_group=="I am Talent") &&($groups_no==0)) {
header("Location: ".MAIN_URL.$this->groups_page);
echo "what's going on?"; //THIS DOESN'T EXECUTE BY ITSELF...WHY NOT??
}
if(mysql_result(mysql_query(sprintf("SELECT last_update FROM `users_profile` WHERE users_id=%d LIMIT 1",$this->id)),0)==0) {
header("Location: ".MAIN_URL.$this->groups_page);
}
echo "what's going on?"; //won't execute unless the line above
Does anyone know why the above code wouldn't work unless there's an echo statement? I have confirmed through manual database checks that the first if statement should execute.
This should cause a redirection of the page to the link stored in the variable MAIN_URL.$this->groups_page (and this lack of redirection was the original issue). However, the header("Location: ...") part doesn't execute unless there is an echo either in the if statement or above the if statement. Why on earth would this be? I put an echo statement AFTER the header("Location: ".MAIN_URL.$this->groups_page); line in the first if-statement and it didn't execute. It would only execute if I had an echo statement before the header(...) line.
That echo really has no impact on the other echo. What I suspect is going on is the second echo normally doesn't execute because the location redirects are sent to the browser first and thus the last echo is never displayed.
When you enable the first echo however, and then one of the location headers is sent to the browser, PHP should be issuing an error stating that output has already started (by the first echo). In that case the second echo may be showing through, b/c the headers cannot be sent at that point.
#ldiqual ditto; I was in the middle of posting this when your answer came through ;)
Because you can't output anything before setting HTTP headers. You should normally get a PHP error like Headers already sent by....
HTTP headers (in your case: Location: ...) are sent to the browser before the body.
According to PHP: header:
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.

Page Redirection problem in 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.<>

Categories