header is executed directly - php

I am using a if condition and in that there is some script and then header.
But the script wont work and directly header works.
if(strpos(mysql_error(),'Email')!=false)
{
print '<script type="text/javascript">';
print 'alert("The email address is already registered")';
print '</script>';
header('Location: register.php');
}

Replace header with typical JS. That does the trick.
if(strpos(mysql_error(),'Email')!==false)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('The email address is already registered')
window.location.href='register.php';
</SCRIPT>");
}

There are a few different things wrong in your code.
First, the header calls should be the first thing you output. You don't do that. You have unbuffered prints before it. From the (very good) PHP 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.
Second, even if you would have used buffered output, the Javascript would never execute as the body is not evaluated when there is a Location header.
Third, using mysql_error to find out if a certain record exists isn't the way to go. Better would be something along the lines of (pseudocode):
SELECT email FROM table WHERE email="someEmail"
if (rows found) {
alert "email already exists"
}
Finally, use mysqli or PDO.
Good luck learning webdevelopment!

Use:
window.location = "example.html";
See #Bart Friederichs's answer first, even if header works perfectly, the JavaScript alert wont work Because the page will be redirected once its completed and the browser will not execute the JavaScript for you.
<?php
print '<script type="text/javascript">';
print 'alert("The email address is already registered");';
print 'window.location = "register";';
print '</script>';
?>
You could also output it without PHP! for example:
if(strpos(mysql_error(),'Email')!==false)
{
?>
<script type="text/javascript">
alert("The email address is already registered");
window.location = "register.php";
</script>
<?php
}
?>

Related

Format die(); Message in PHP

Is there a way to style the output of php's die(); message?
I want to add some HTML and CSS around the error message so that I could use it in a productive environment.
If you're using the actual die() function, it will always print out exactly what text you pass it (which could be HTML, but might be awkward to use).
You could, however, simply make your own function that prints out an error message nicely and then calls exit - that way you don't have to repeat the HTML that you might otherwise pass to die() every time.
function die_nicely($msg) {
echo <<<END
<div id="critical_error">$msg</div>
END;
exit;
}
<?php
if('1'=='1')
echo '<font color=red>';
die('Its true');
echo 'its false';
?>
<?php
if('1'=='1')
{
echo '<font color=red>Itss true too.</font>';
exit();
}
echo 'its false';
?>
Both above are working, just to clear your doubts. :)
You can add html to the string you are feeding to die, but even easier is just echoing out the html that you want before you call die.
Yes, you can do like this,
die("<div>Error: ".mysql_error()."</div>");
Why not to change die() to its wrapper?

Redirect Function Php

I have a function, 'redirect_to()' written on php script that is called after a successful update to a page on my custom CMS. It works fine on the localhost, but when I try it on my actual live domain I get the following error message:
Warning: Cannot modify header information - headers already sent by (output started at /hermes/bosweb/web119/b1192/ipg.typaldosnetcom/edit_listing.php:7) in /hermes/bosweb/web119/b1192/ipg.typaldosnetcom/includes/functions.php on line 20
Here is the code for the redirect_to() function:
function redirect_to ($location = NULL) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
I've made sure to call the function before I output any HTML, so I'm not sure what the problem really is.
My question: Why am I receiving this error?
It's not lying. You've output something before getting to this point. Check the locations mentioned in the error messages.
Show us the first 25 lines of each of the files mentioned.
you already sent your output to the page before you set the header. first you need to set the headers and then can the output come.
It can even be a whitespace.
It means something was already outputted on the suggested line. Try going there and see what it does.
Try pasting the surrounding code on that position for a better clarification if you can't find the problem yourself.
One common cause is to have a line after a php file you're including...
Simple solution: remove the closing php tag "?>" from all files as it's not needed..
You can test if you have a character before the opening php-script tag by removing any closing php-script tag. This way you are sure there isn't any character left (it's not needed).
Use output buffering:
<?php
ob_start();
// Test buffered output.
echo 'hello world';
function redirect_to ($location = NULL) {
if ($location != NULL) {
header('Location: ' . $location);
exit;
}
}
// rest of php file here
ob_end_flush();
?>
Docs: ob_start() and ob_end_flush()

PHP executes code after echo before finishing echo code

I have the following code:
echo "<script type='text/javascript'>
if(window.location.href.toLowerCase().indexOf('test') != -1) {
}
else
window.open('http://google.com', '_parent', '');
</script>";
echo "test";
The code executes successfully BUT if it will open http://google.com using window.open it still shows echo "test" before successfully redirecting to google.com.
Can I somehow prevent executing code after the else statement in the javascript (window.open('http://google.com', '_parent', '');)?
Thanks
EDIT: Does that seem that I just ask to ask? I thought that something might exist that I could use in javascript to stop browser from printing echo "test" if I reached else statement in javascript code.
You should understand this order.
PHP executes script and generate HTML/JS/etc
Then browser get it, parse and execute.
So you should use any of php condition to avoid printing "test" in some cases

header php not working

well am trying to use the header to send information, but my html is already outputting information, I tried to fix the problem by using the ob_start() function to no avail
ob_start();
require('RegisterPage.php');
if(isset($_POST['register']))
{
if(register($errormsg,$regnumber))
{
$to = $_POST['email'];
$subject = "Registration";
$txt = "You need to return to the Classic Records homepage and enter the number given in order to finish your registration ".$regnumber."";
$headers = "From: registration#greenwichtutoring.com";
mail($to,$subject,$txt,$headers);
header('Location:emailNotification.html');
}
else $error=$errormsg;
}
ob_end_flush();
Check if any scripts included before the ob_start() function are outputting HTML. Sometimes an included file can contain a space after the PHP closing tag. That space will be outputed as is. To fix this, leave the PHP closing tag from your file.
E.g.
<?php
class someClass {
...
}
?><whitespace>
Can give you some good headaches. This is fine and fixes the above problem:
<?php
class someClass {
...
}
You need to call ob_start before any output has happened. So, for example, as the first statement in your main PHP script file (make sure that there is nothing before your <?php like some whitespace of a BOM).
Here you're trying to redirect to a different page and show a message. It can't happpen.
Instead, try using a link, or echo-ing:
<meta http-equiv="Refresh" content="(delay in seconds);URL=(destination)">
in your <HEAD>.
In your case, you want this to be instant, so:
<meta http-equiv="Refresh" content="0;URL=emailNotification.html">
The better alternative, is simply to not require the page until after the if.
If i remember correctly the header(); is executed at the end of the execution of the php script , so try moving it in the beginning of the if
Cheers
You have to buffer the html output, not the php logic. E.g:
ob_start();
<html>...
/* PHP */
...
ob_end_flush();
header('Location: http://www.foo.com/emailNotification.html');
1 space after Location:
and
full url
With Your Dynamic HTTP_HOST
header('Location: http://'.$_SERVER["HTTP_HOST"].'/emailNotification.html');
Chris.

While loop combined with header() in PHP

I've written a script to geocode some points which has a structure basically like this:
//get an unupdated record
$arr_record;
while(count($arr_record) > 0)
{
//strings are derived from $arr_record
geocode($string1);
geocode($string2);
geocode($string3);
array_pop($arr_record);
}
function geocode($string) {
//if successful
update($coords)
}
function update($coords) {
//update the database
header('Location:http://localhost/thisfile.php')
}
The trouble is that even when the geocode is successful and the database is updated, and teh header resent, the script still goes back into the while loop without reloading the page and starting again on a new record.
Is this normal behaviour for PHP? How do I avoid it behaving like this?
After header() use die(); to terminate the script and output.
How do I avoid it behaving like this?
Put exit() after header().
another effective way is not to send headers directly in a loop. which is not proper (i couldn't find in php.net manual but i remember it was discussed before in phpusenet).
it may act unexpected in different php versions. & different apache ver. installations.
php as cgi will make problems too.
you can assign it to return as string then you can send header later...
function update($coords) {
//update the database
if(statement to understand update is ok){
return 'Location:http://localhost/thisfile.php';
} else {
return false;
}
}
if($updateresult=update($cords)!=false){ header($updateresult); }
but if i were you... i would try to work ob_start() ob_get_contents() ob_end()
because those are the excellent way to control what will be sent to browser. normal mimetypes or headers... whatever. it's better way while working with headers & html output at the same time.
ob_start(); /* output will be captured now */
echo time(); /* echo test */
?>
print something more...
<?php /* tag test */
/* do some stuff here that makes output. */
$content=ob_get_contents();
ob_end_clean();
/* now everything as output with echo, print or phptags.
are now stored into $content variable
then you can echo it to browser later
*/
echo "This text will be printed before the previous code";
echo $content;

Categories