This is the code:
if($rowCheck>0) {
session_start();
while($row = mysql_fetch_assoc($check)) {
$_SESSION['developer'] = $row;
}
header("Location: http://".$_SERVER['SERVER_NAME']."/index.php");
}
else
echo 'Invalid Password or Email!';
Everything is working fine except the header, and if i write an echo after the header it will work normally. Also if i printed the location, it will show me the exact and right location.
I'm running on mamp and macos. So it's on a localhost.
Any help ?
As scott said, you need the exit() or die() after the header.
Also, check that there are no empty spaces before or after your opening and closing php tags, like this:
<?php
That will cause header functions to fail, as it is considered input. Any related include files should be checked as well.
Add exit() or die() after the header line. The header function does not stop execution of the rest of the script.
just comment everything and paste at the right beginning header("Location: http://".$_SERVER['SERVER_NAME']."/index.php"); and see if it is working. If not, check for a BOM encoding.
Couple things.
First I would put ini_set("display_errors", 1); at the very top of your page within the PHP code. You may be getting a "headers already sent" error.
Add an exit after the header to keep the script from going any further:
header("Location: http://".$_SERVER['SERVER_NAME']."/index.php");
exit;
Lastly this bit doesn't make sense.
while($row = mysql_fetch_assoc($check)) {
$_SESSION['developer'] = $row;
}
You're setting that session variable once so you don't need the while. You're also setting it equal to a mysql resource (which you may intend to do), but maybe you just need a column
$row = mysql_fetch_assoc($check);
$_SESSION['developer'] = $row['username'];
Related
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---
No idea why this is not working. Here is the code:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
echo $_POST['cancel'];
}
Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.
This is likely a problem generated by the headers being already sent.
Why
This occurs if you have echoed anything before deciding to redirect. If so, then the initial (default) headers have been sent and the new headers cannot replace something that's already in the output buffer getting ready to be sent to the browser.
Sometimes it's not even necessary to have echoed something yourself:
if an error is being outputted to the browser it's also considered content so the headers must be sent before the error information;
if one of your files is encoded in one format (let's say ISO-8859-1) and another is encoded in another (let's say UTF-8 with BOM) the incompatibility between the two encodings may result in a few characters being outputted;
Let's check
To test if this is the case you have to enable error reporting: error_reporting(E_ALL); and set the errors to be displayed ini_set('display_errors', TRUE); after which you will likely see a warning referring to the headers being already sent.
Let's fix
Fixing this kinds of errors:
writing your redirect logic somewhere in the code before anything is outputted;
using output buffers to trap any outgoing info and only release it at some point when you know all redirect attempts have been run;
Using a proper MVC framework they already solve it;
More
MVC solves it both functionally by ensuring that the logic is in the controller and the controller triggers the display/rendering of a view only at the end of the controllers. This means you can decide to do a redirect somewhere within the action but not withing the view.
I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php'); anymore, instead I'm using javascript's document.location.
Change your:
header('Location: page1.php');
To something like this:
echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";
And what is the purpose of echo $_POST['cancel']; by the way?, just delete that line if what you want is just the redirection. I've been using that <script> every time and it doesn't fail me. :-)
Use #obstart or try to use Java Script
put your obstart(); into your top of the page
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
If you use Javascript Use window.location.href
window.location.href example:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
exit();
}
I had also the similar issue in godaddy hosting.
But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.
Please find the example of the fix:
fileName:index.php
<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>
I had similar problem...
solved by adding ob_start(); and ob_end_flush();
...
<?php
ob_start();
require 'engine/vishnuHTML.class.php';
require 'engine/admin/login.class.php';
$html=new vishnuHTML();
(!isset($_SESSION))?session_start():"";
/* blah bla Code
...........
...........
*/
</div>
</div>
<?php
}
ob_end_flush();
?>
Think of ob_start() as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."
ob_end_clean() or ob_flush(), which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.
For me also it was not working. Then i try with javascript inside php like
echo "<script type='text/javascript'> window.location='index.php'; </script>";
This will definitely working.
Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.
UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.
Neer to specify exit code here so php not execute further
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit(0); // require to exit here
}
Try adding
ob_start();
at the top of the code i.e. before the include statement.
Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.
Be very careful with whitespace and other stuff that may affect the "output" already done. I certainly know this but still suffered from the same problem. My whole "Admin.php"-file had some spaces after the closing php-tag ?> down the bottom on the last row :)
Easily discovered by adding...
error_reporting(E_ALL);
...which told me which line of code that generated the output.
Try this, Add #ob_start() function in top of the page,
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
Use the following code:
if(isset($_SERVER['HTTPS']) == 'on')
{
$self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
<script type='text/javascript'>
window.location.href = 'http://<?php echo $self ?>';
</script>"
<?php
exit();
}
?>
put < ?php tag on the top of your file (starting on frist line of document)
not:
--- Blank space or something ---
<?php
but:
<?php
..your code
header('Location: page1.php');
...
$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.
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.
Hey, I am trying to make an if statement that redirects them to a different page if true, simple right?
I am not sure why this is not working but I am using:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
$userid = strtolower($_SESSION['X2X2']);
$getuser = mysql_query("SELECT * FROM XXXXXX WHERE X2X2 = '$userid'");
$info = mysql_fetch_array($getuser);
$id = $info['X3X3'];
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
header('Location: http://beta.XXXXX.co.uk/purchase.php');
mysql_close($con);
}
When I put
<?
echo $_POST['accounttype'];
?>
And I get back
Paid User - £2 p/m
Which is correct?
Any help would be appreciated,
Thanks.
Looks like you want to call exit() before the close brace on your if statement.
The documentation for header has example code like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The end bit of your if statement really ought to be:
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
mysql_close($con); // do this before sending a redirect header
header('Location: http://beta.XXXXX.co.uk/purchase.php');
exit();
Also, header doesn't work if you've already sent any output, per this warning from the 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. 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.
As it seems to depend on £, you have several possibilities depending on which values $_POST['accounttype'] can have.
First I suggest you try:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
(as £ is £ in HTML).
If this doesn't work, what is the part of the string, that makes it unique? Paid User or 2 p/m? If any of these, it is sufficient to check against a substring like:
if (substr($_POST['accounttype'],-5)=='2 p/m'){
or
if (substr($_POST['accounttype'],0,9)=='Paid User'){
or any combination (avoiding £).
You haven't by any chance already output something to the browser have you? If you modify the location header after using the echo or print statements, it will issue a warning which you probably won't see unless you have verbose errors or logging turned on.
I know this can happen with UTF-8 files in some versions of PHP - the byte order mark (BOM) of the UTF-8 file are output before the PHP script starts execution, which prevents the location header from being sent.
Altering the HTTP header with header requires that the HTTP header has not been sent yet. This can be one reason for why it doesn’t work for you as the HTTP header is sent together with the first output of your script (any output including text before <?php).
When you set error_reporting to E_ALL and display_errors to true, PHP will display you all errors immediately. This can help you to determine the cause of you error.
My first inclination would be to check if there are any extra characters on your POST data by trying the following:
if (trim($_POST['accounttype']) == 'Paid User - £2 p/m') {