echo Javascript window.location.href not working - php

I have a function which echoes javascript to navigate to a different page. While navigation occurs, the
echo 'window.location.href="'.$url.'";';
does not work and simply prints it on the screen.
"window.location.href="./index.php";
I use my function this way: redirect("./index.php");
My php function is as follows
function redirect($url)
{
if (!headers_sent())
{
header('Location: '.$url);
exit;
}
else
{
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;
}
}

Your browser treats the response as plaintext.
Prepend to you response a Content-Type: text/html\n plus wrap your content inside an <html></html> tag.

Try this way.
<?php
$yourURL="http://www.stackoverflow.com";
echo ("<script>location.href='$yourURL'</script>");
?>

Why not just use output buffering and not have to deal with JavaScript or meta redirects at all?
<?php
// Top of your page
ob_start();
// Code goes here
// Redirect
if ($redirect_is_necessary)
{
header('Location: '.$url);
exit;
}
// Rest of page goes here
// Bottom of page
ob_end_flush();
?>

Related

PHP error- Header sleep function not working

I have a PHP code that has header and sleep Functions to display an alert as it redirects the page a bit slower. But the sleep does not seem to be working.
This is the PHP code, Please check:
<?php
if ($query) {
echo '<script language="javascript">';
echo 'alert("Registration SUCCESFUL")';
echo '</script>';
header('sleep(10);');
header('Location: http://localhost/amberTAG%20requester/Login%20Page/Login.html');
} else {
echo '<script language="javascript">';
echo 'alert("Registration UNSUCCESFUL, Sorry!")';
echo '</script>';
header('sleep(10);');
}
?>
Thanks,
Just use sleep without header
sleep(10);
header('Location: http://localhost/amberTAG%20requester/Login%20Page/Login.html');
Or use:
header('refresh:10; URL=http://localhost/amberTAG%20requester/Login%20Page/Login.html');
If you want to use sleep before alert, you should use setTimeout for JavaScript.
Try this:
setTimeout(function(){
alert("Registration UNSUCCESFUL, Sorry!");
}, 10000);
And, if you want to use sleep before URL redirection, try this:
header( "refresh:10;url=yoururl.html" );

PHP Redirect Not Working (Inside if statement)

The following code compares the current page to the site root and redirects if different.
This work fine locally but not on the server.
<?php
ob_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/includes.php');
if (SITE_FULL_URL !== SITE_URL . '/') {
redirect(SITE_URL);
} else {
/* Page Switcher */
switch ($urlarray[0]) {
case '':
require_once($_SERVER['DOCUMENT_ROOT'] . '/mod/home/index.php');
break;
default:
require_once($_SERVER['DOCUMENT_ROOT'] . '/mod/404/index.php');
break;
}
}
ob_end_flush();
As soon as the redirect function is placed inside an if statement it stops working.
The redirect function is as follows:
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 javascript redirect... if javascript 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;
}
}

Write text with echo() after reloading page with header()

I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results&timestamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.

PHP Header Function Not Working Well

I have one file "djakhiltalreja_video.php" and another file "mobile_djakhiltalreja_video.php".i just want to redirect to this link http://akhil.djmusicweb.com/mobile_djakhiltalreja_video.php , current page :- djakhiltalreja_video.php .
but redirected url is http://akhil.djmusicweb.com/mobile_mobile_djakhiltalreja_video.php .
why double occurence of mobile_ ???
<?php
$pagename = "mobile_".basename($_SERVER['PHP_SELF']);
header('Location: http://akhil.djmusicweb.com/'.$pagename);
exit();
?>
Note : Remove mobile prefix from your page-name. I think it's covered in to $_SERVER['PHP_SELF']
Please check below solution for your problem.
Solution :
$pagename = basename($_SERVER['PHP_SELF']);
$url = "http://akhil.djmusicweb.com/".$pagename;
if (!headers_sent()) {
header('Location: '.$url);
exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
exit;
}
This simple code will do the trick for you. It will check if headers are not sent, then it will call the PHP’s header function to redirect. But if the headers are sent, it will use Javascript to redirect to the URL you want.

Header Location dont work on live server but works on localhost

I have this code which relocates a user to index.php if they set the value of a dropdownmenu
on an irrelevant page to set it for please check my code.
if(isset($_GET['d'])&&empty($_GET['d'])===false){
$cur_page=$_SERVER['PHP_SELF'];
$current_page = substr($cur_page,1);
$possible_page = array('terms.php','contact.php','about.php');
if(in_array($current_page,$possible_page)){
header('Location:/index.php?d='.$_GET['d'].'');
exit();
}else{
echo $_GET['d'];
}
It works fine on my localserver but on live server it does not ?
add ob_start(); at very beginning of the php script. If it include another file then do not use ?> in the end. Thanks
I always use this little method and works perfect in all situation.
public static function Redirect($sec, $file)
{
if (!headers_sent())
{
header( "refresh: $sec;url=$file" );
}
elseif (headers_sent())
{
echo '<noscript>';
echo '<meta http-equiv="refresh" content="'.$sec.';url='.$file.'" />';
echo '</noscript>';
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$file.'";';
echo '</script>';
}
}
In last case it will redirect for sure.

Categories