PHP executes code after echo before finishing echo code - php

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

Related

PHP - Exit preventing a pop up

Can anyone tell me the right way to do this. I want a pop up first, then the script to stop, but when I run this, the exit just overrides the pop up?
if (HandOverNotesModifiedTime > $datetime_from)
{
echo "<script type='text/javascript'>alert('WARNING: Notes have not been updated!');<script>";
exit(header('Location:/handoverTESTING.html');
}
I tried without the exit, just to make sure the pop up works, and it does.
You can use like this :
if (HandOverNotesModifiedTime > $datetime_from)
{
echo "<script type='text/javascript'>alert('WARNING: Notes have not been updated!');</script>";
echo "<script>window.location.assign('/handoverTESTING.html');</script>";
}
Page redirection reason :
Popups are created on the client side, and the header redirection takes place on the server side.
PHP is executed at the server side. It renders HTML,Styles and sends it to the browser then browser execute the javascript codes

How to delay 2 seconds in PHP to include?

I want this PHP script to wait 2 sec before including an sp.php (server panel).
The sleep(2); doesn´t work for me (It doesn´t do anything at all.)
My code:
<?php
$cookie_name = "sc";
?>
<?php
if(!isset($_COOKIE[$cookie_name])) {
include 'noserver.php';
} else {
echo "Server found";
sleep(2);
include 'sp.php';
}
?>
Any ideas? It`s for the server hosting web.
You can use Javascript with setTimeout and window.location.href to redirect to the file.
Example:
<?php
if (!isset($_COOKIE[$cookie_name])) {
include 'noserver.php';
} else {
echo 'Server found';
echo '<script>setTimeout(function(){window.location.href =
"http://yourwebsite.com/sp.php"}, 2 * 1000);</script>';
}
?>
You probably think it is doing nothing at all because you don't see the output until the include has been completed. Try putting a flush command and flushing any buffering after writing "Server found":
print "Server found\n";
// in the very worst case you might be forced to send "<!-- GARBAGE -->"
// with enough "garbage" to force any intermediate buffers to flush.
if (ob_get_level()) {
ob_flush();
}
flush();
...
However, as it has been suggested, this is likely a XY problem. You want something else to happen, and a server side delay of 2 seconds is probably not the best way to achieve this.
For example, if you want a quick "Server found" message to immediately appear, and then a slower page to load (even if it is the same page), you could do this with a session flag or using jQuery and a DOM load.
In the first case you load the same page twice, the first time showing the message, setting the flag and reloading using Location or a Meta reload (echo "<meta http-equiv="refresh" content="2" />)). The second time, with the flag set, you un-set the flag and run the include(). Problem solved with no server sleep() overhead.

header is executed directly

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
}
?>

php if statement not working in internet explorer

ie does not render my php if statement well, any ideas? I say this because it works well in firefox.
<input type="image" src="Images/submit.png" value="REGISTER" name="command" />
if($_REQUEST['command'] == 'REGISTER'){
print "test";
}
else{
}
It is not printing "test"
Internet Explorer is not interpreting your PHP statement at all.
PHP is a server-side programming language, i.e. executed at the server, not the client.
Please rephrase your question. By your previous posts it seems you realize that.
You're missing the <?php ... ?> tags surrounding your PHP code.
PHP is executed server side; IE has no bearing on your if statement. My guess is that $_REQUEST['command'] is not being set.
What does this print:
if(empty($_REQUEST['command')) print 'command is empty';
Another idea would be to append the "command" data to your URL:
http://localhost/your-php-script.php?command=foo
EDIT
Just noticed that you're using type="image", I don't know if IE supports that: http://www.codingforums.com/archive/index.php/t-79035.html, try using a regular submit button.
However: You should check first, if $_REQUEST['command']; is set
if(isset($_REQUEST['command'])) {
if($_REQUEST['command'] == 'REGISTER'){
print "test";
}
else{
}
}

Will php code exit after echo for ajax?

I am running a typical php-engined ajax webpage. I use echo to return a html string from the php code. My question is, if I have some other code after the echo, will those code get executed? Or echo behaves similar to exit, which immediately return and stop running the php code? Thanks.
No, echo in no way exits, you normally have more than one echo in a script. exit does take a string argument that it will output before exiting, however, so you can do:
exit("your string here");
and it will output the string and exit
No, echo would not. To exit after echoing things, you'd say
echo "Dear me, good bye!"; exit();
echo will simply return text to ajax javascript part; however the code after or before echo/echos will execute
No. PHP scripts are rendered in their entirety unless you explicitly exit them. ANY output on a script will be passed back to the ajax function if it was called through ajax.
echo 'This gets outputted<br />';
echo 'As does this';
If you must use a single file and you want your script to exit after performing ajax request with out having to add extra vars to your ajax url or evaluate vars to exit, i would suggest creating a function that performs your ajax, have the function return true on success, then do:
if(ajaxFunction($paramOne, $paramTwo)){exit();}

Categories