Redirect Using JavaScript and PHP - javascript

I am using below code for redirect users.
<?php
$redirect_to = "https://google.com";
$redirect = "https://yahoo.com";
echo "<script>location.href = '".$redirect_to."';</script>";
header("Location: $redirect");
exit();
?>
I prefer to use javascript redirect, but in somecase when user have not javascript enabled in his browser, I am using PHP redirect as backup redirect but sometime I am getting header already sent error on php redirect code and sometime I am not getting that error.
if I use exit() after redirect by javascript, I will not able to
redirect user if he have javascript disabled in his browser.
my question is there any way to stop php code if javascript redirect was success? I am not getting idea what I have to do for handle my situation.
Let me know if any expert can help me to solve puzzle.
Thanks!

Well, you are a web developer using PHP and Javascript.
One thing to remember, PHP code always runs first on the server. It's a server-side language, so no matter how you arrange your lines of code, your php code will finish running. Then, the client source code (HTML, CSS, JavaScript) is sent to the browser and executed on it (Client-side).
And next, the job of redirecting is always on the client side, the server doesn't actually redirect people to another site. What actually happens is that your php source code generates a redirect command that sends the browser for a redirect.
Another thing, in php, any work related to the header() function needs to be executed before any content is generated. That is, it must run at the top, before any method echo, exit, print,... or content block.
When deploying a php application, if you already use header("Location: ....") then it makes no sense to use javascript directives, as the browser will prioritize handling the redirect in the header first! !
The source code should really be:
<?php
$redirect = "https://yahoo.com";
header("Location: $redirect");
?>
Another way if you still prefer using javascript redirects and are compatible with javascript disabled, that is to use the tag meta[http-equiv="refresh"]. Refer to the following example:
<?php
$redirect_to = "https://google.com";
?>
<meta http-equiv="refresh" content="5;URL='<?php echo $redirect_to; ?>'" />
<script>location.href = "<?php echo $redirect_to; ?>";</script>
The number 5 appears in the content of the meta specifying the countdown (seconds) the browser will redirect when the page has finished loading. When the page cannot execute javascript, after 5 seconds the page will redirect.

Related

how to redirect to another page using php after hosting my website

hello guys please help
How to redirect a page using php?
i am using this one
header('location:quizsection.php?success=success');
It is working on localhost
but after hosting my website it is not working
it is working on perfectly when i using with local server it is not working after i am hosting this on godaddy
and
path is also pefect
Try to use:
header('location: /quizsection.php?success=success');
When I redirect, I go overboard to ensure redirection takes place. I do this:
$url = "quizsection.php?success=success";
header('Location: '.$url);
die("<html>
<meta http-equiv='refresh' content='0; $url'>
<body onload=\"location.replace('$url');\">
<a href='$url'>$url</a>
</body></html>");
Notice that I have a space after "Location:", which you do not have. If the header is ignored, I send HTML. It includes a meta tag to redirect. If that is ignored, the page uses Javascript to redirect. If that is ignored, the user sees the URL and nothing else. The user can click on it to get to the URL.
I actually have this in a function called redirect, so I just use:
redirect("quizsection.php?success=success");
If this doesn't work, it isn't a redirection problem. You need to check your directories and files. Something is not where you think it is or is not named what you think it is. I've personally spent days working on problems that were caused by a misnamed directory or file.
When you print something in PHP, it changes that into HTML and that's what the file shows. So when you think about it you have to do the following:
print("<script type=text/javascript>location.href = \"quizsection.php?success=success\";</script>");
Tell me if this works! If you want to delay the redirect do this:
print("<script type=text/javascript>function redirect() {location.href = \"quizsection.php?success=success\"} setTimeout(redirect, amountOfMilliseconds)</script>");
FYI, there are 1000 milliseconds in a second. Let me know if this works!

How to Handle Redirects for my Login Page PHP

I have recently moved from localhost to my live website. I have a simple PHP login page. After the users details are checked with my mysql table and if the username exist and they provide a valid password for that username they are redirected to the home page. I was using the header function built in to PHP but this seems to be no longer working now that I am on my live website.
After further research it seems that I cannot use header tags after the page loads. So I am not echo'ing out script tags to window.location redirect to my homepage. The problem with this is that when the new location is being redirected to it appears to look like an additional web pages is loading in before my actual webpage that I'm wanting to go to loads in (This is probably due to the fact that I have extra error handling code that is running after the fact). Does anyone else experience this when using this method? Is there a better way to handle this?
This is what I'm using currently just in case there is any confusion
echo '<script>window.location.href = "home.php";</script>';
I was using the header function built in to PHP but this seems to be
no longer working now that I am on my live website.
Headers must be the very first thing that your script outputs or they won't work. PHP has a convenience feature called output buffering which temporarily holds back the output until the script is done. This allows you to put calls to header() anywhere in your code, and then PHP will automatically take care of moving headers to the front of the output for you. Thus, if you have output buffering enabled, you can put headers anywhere and it will still work. If you do not have output buffering enabled, you must put headers at the very start.
I will wager that you are generating output before the headers, and your local PHP install has output buffering enabled, while your remote host does not. You can fix this in one of two ways:
Update your code to ensure that nothing is output before calls to header().
Enable output buffering on your host by setting output_buffering = 1 in your php.ini.
I recently learnt you can do this with a meta tag:
<meta http-equiv="refresh" content="2;url=http://example.com/" />

How to run a javascript animation after click of a php submit

I am trying to start a javscript annimation and then submit a form. I have this but it's not working... I understand php is server side and javascript is client side; however, this works with alerts as long as I get rid of the header so I am confused why it wont work with my annimation.
if (isset($_POST['play'])) {
if ($mSecs >= .1) {
echo "<script>
spinWheel_1.startAnimation();
</script>";
}
sleep(5);
header("Location: winwheel.php");
}
You instruct the browser to immediately navigate away by sending the header. This is the reason why you see your animation without the header in the script.
Also, note that you cannot send the header after sending any output as a response.
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.

How to run PHP editable in an iframe with JS?

I created an HTML/JSS editor using this tool, which, when editing displays the result in an <iframe> (preview).
editor.getSession().addEventListener('change', function () {
iframe.contentWindow.document.body.innerHTML = editor.getSession().getValue(); // ex: '<div>Hi!</div>'
});
This is easy, the problem is with the PHP editor... obviously if I insert a PHP code in the innerHTML this can not be executed on the client side.
If value is:
<?php
$name= 'John Doe';
echo $name;
?>
This shows:
<!--?php $name= 'John Doe'; echo $name; ?-->
What is the best way to save this temporary code and run instantly on the iframe (preview)?
What do you mean by
run instantly on the iframe (preview)
If you wanted the user edited php code to run and show output completely in the client side browser,
then there is no pragmatic way to do this.
Because, to run php codes,
you need a php runtime at the first place.
Now, whether the clients have php installed in their system(PC) or not,
you have no access to that via the browser.
Now if you are desperate to run the code( on your server then ) and send output to the clients browser,
then
WARNING:: It's highly dangerous,
taking string's from unknown(and hence untrusted) sources and running them as php code on the server, you can get your server hacked(and whacked) easily at a short time :p
because,you don't know what code they are writing(unless you explicitly moderate it before running :p )
(Now If you don't know what you are doing)
you can use the eval construct as described here:
http://php.net/manual/en/function.eval.php
eval("?> $str <?php ");

Redirecting someone

I want to redirect someone to index.php, how do i do this? But not the "meta" method, because it needs to be in header, and i can not have it there.
window.location.href = 'http://your-new-url.com';
or
window.location.pathname = 'index.php';
if you need to use a relative pathname.
Do not use JavaScript for this. If the user has JavaScript disabled (or most likely is browsing with a browser without support for JavaScript), the redirection will not work.
From your PHP code, you can send an HTTP header to direct your user to the page of your choice. Use the header() function to do this.
header('Location: index.php');
exit; // Important, stops execution of PHP page
If PHP complains that it cannot send the header because data has already been sent to the browser, simply go to the top of your script and enable output buffering by using ob_start():
ob_start();
With output buffering enabled, you can send headers anywhere in your code since data is only sent at the end of your script.
PHP Documentation: header()
PHP Documentation: ob_start()
Use window.location
<script type="text/javascript">
window.location.href = "http://www.yoursite.com/index.php"
</script>

Categories

Resources