Php Location("some other page") - php

I'm new to PHP and this is something that I don't know how to do, even though I have been searching it.
I know that redirecting can be made with Location("some page"). I also read that this works just if there is nothing displayed to user.
What I want to do is:
Display a message to user. echo "message.redirecting...."
Wait for 2 seconds sleep(2);
Then redirect Location("some page");
Any ideas?
Andrew
This is part of an assignment and javascript is not allowed. Only PHP.

You can use a meta refresh, which is just a html meta tag placed inside the <head> of your page. Like this:
<meta http-equiv="refresh" content="2;url=http://newurl.com/">
This will redirect the page to the http://newurl.com after 2 seconds.

Do not do it this way.
It's VERY bad usability.
And there is not much sense in saying "redirecting".
That's legacy of ancient ages of raw HTML sites. No good site using such redirects these days.
Redirect with no messages.

Unfortunately you can't do that. header() calls, such as header('Location: '); rely on http headers, which have to be sent before any output is sent to the client.

I reccomend using a Javascript Redirect if you want a message displayed to the users.
<html>
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "../javascriptredirect.php"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h2>Prepare to be redirected!</h2>
<p>This page is a time delay redirect, please update your bookmarks to our new
location!</p>
</body>
</html>
or you can do a php redirect like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
?>

Related

How to make a div disappear after PHP execution with ob_flush()

I have a PHP file that I want to show a loading text or an image to the visitor, while it is fully loaded.
As far as I know, I should use ob_flush(); to do so.
I tried the following code:
<?php
ob_start();
echo '<div> Loading </div>';
ob_end_flush();
ob_flush();
flush();
ob_start();
ob_clean();
//my php code
//my php code
?>
With this code everything is ok, the loading text appears first of all and then the PHP exception starts. But my problem is that after the PHP execution completes, the loading text is still on the page and it doesn't disappear.
Please help me solve this problem :)
No, this is not what ob_flush() is for. It is not possible at all with a server side language like PHP. You have to use javascript instead.
Here is the roughly simplified and not 100% accurate description what happens when you request a PHP webpage:
Browser sends a request to the server "Hey server, give me page Home"
Server runs the PHP script for page Home
Usually, the PHP script will generate some output. The server will collect this output.
When the script has completed, the server says "OK Browser, here is your Home page", sends the output (the response) to the browser and then closes the connection.
The connection is now closed and the server has already forgotten that the browser has even asked for a page 1 second ago.
The browser will happily display the newly receieved webpage. There is no way to make something happen in the browser now for your PHP script.
That's called the Request Response Pattern and it's still somewhat fundamental to the web.
So how can you get your loading overlay now? When you can accept that the loading overlay doesn't work on the initial page request, but everytime a user klicks a link on your site, you can use following simple approach.
<!DOCTYPE html>
<html>
<head>
<title>Loading overlay test</title>
</head>
<body>
Click me!
<script>
document.addEventListener(
'click',
function() {
if(event.target.matches('a')) {
document.body.innerHTML = "Loading next page ...";
}
},
false
);
</script>
</body>
</html>
If your page loads fast you will probably not see the effect. I kept the example as simple as possible with some plain text instead of a real loading overlay, you can use this as a starting point.
When you absolutely need an overlay for the first page request, things get more complicated. Here is a non-production ready and ajax-less example:
<?php
// Detect 1st page hit
if(empty($_GET['fetch_real_page'])) {
// Loading page - keep as simple(fast) as possible,
// prevent any slow database queries etc.
?>
<!DOCTYPE html>
<html>
<head>
<title>The loading page</title>
</head>
<body>
Loading first page...
<script>
// This will instantly request the "real" page
window.location.replace(window.location.href + '?fetch_real_page=1');
</script>
</body>
</html>
<?php
exit;
// (Does not need to be called explicitely
// when nothing comes after the if-else construct)
} else {
sleep(2);
// Simulates a slow page load,
// do all the heavy database stuff that slows down your page here.
// Then, output the "real" page:
?>
<!DOCTYPE html>
<html>
<head>
<title>The real page</title>
</head>
<body>
Click me!
<script>
// Set up the loading overlay for secondary requests
document.addEventListener(
'click',
function() {
if(event.target.matches('a')) {
document.body.innerHTML = "Loading next page ...";
}
},
false
);
</script>
</body>
</html>
<?php
}
?>
Things to consider:
You need to extend every internal link with fetch_real_page=1
Sooner or later you need to deal with additional $_GET parameters, so you must extend this code, or switch to cookies or the session to check whether the request is a secondary one or not.
The end of the road will be a javascript/ajax-driven single page app but I think this is beyond the scope of your question.
Beware of this unreadable mix of PHP tags and HTML, code like that is frowned upon for good reasons. This is for demonstration only.

Return Redirect with body in Laravel

I'm trying to do a redirect with body in Laravel. I've tried this:
return Redirect::to($log_in_url)->with('body','<html><head><title>Redirecting to your page</title></head><body>If you are not redirected within 5 seconds, please cl ick here.</body></html>');
I look in the network tab, I don't really see anything.
The question is that how would one make a delayed redirection by showing an HTML waiting page before the actual redirection happens?
You're making a handful of false assumptions:
The with method puts the thing into the session so that you can access it after the redirection. A common usecase is to set messages and then redirect the user.
Don't expect magic by just setting the thing body.
There's no such a standardized redirection called "redirect with body" as you stated. If you need such a thing, you have to implement it.
I assume you're having one of those vBulletin-like redirect styles in mind. To implement it in Laravel context, you gonna need a mediatory view to do a clientside redirect for you after a set amount of delay. Let's name it redirect.blade.php:
<!doctype html>
<html lang="en">
<head>
<title>Redirecting...</title>
<script>
window.setTimeout(function () {
window.location = "{{ $url }}";
}, 5000);
</script>
</head>
<body>
If you are not redirected within 5 seconds,
please click here.
</body>
</html>
With this in place, your controller will pass a $url to this mediatory view and let it be rendered to do the clientside redirection:
# Controller method
return view('redirect', ['url' => $log_in_url])
This style of redirection won't be working if JavaScript is disabled and that's why they put a link into the page content and warn the user about it.
Some take a hybrid approach:
<noscript>
<meta http-equiv="refresh" content="5;url={{ $url }}" />
</noscript>
The reason that they don't go with the refresh header/meta tag in the first place is that it's not specified in the HTTP standard. Read more.
I strongly suggest that you look into alternatives. This is so 1990 and not user-friendly at all.
As a visitor, if I deal with a website that makes me wait for 5 godddamn seconds, I'd just leave. That's why people used to make browser extensions to workaround the vBulletin's login screen waiting time!
Embrace simplicity and just do a regular HTTP redirect. It's best for all humanity.
It's not a task for Laravel. You can just return page with meta, or using javascript.
// Controller
return view('redirect');
// View redirect.blade (Regular html page with additional meta tag)
<meta http-equiv="refresh" content="5;url=http://www.google.com/" />

html div, tags dont work after Header()?

I need help. Are html tags and divs and something in html loading after Header send ?
I try this bud after header the div yes dont show...
Header("Location: index.php");
Echo "<div class=\"yes\">Some text will release</div>";
Is there any way to reload page and code will working with html after ?
The yes div is message If the code will work for example:
<div class=\"yes\">Succesfull</div>
Thank for help
Thanks for all help I got Idea:
On the firt page:
Header("Location: index.php&successfull=1");
On the second page:
If (IsSet($_GET['successfull'])) {
If ($_GET['successfull'] == "1") { Echo "<div class=\"yes\">Successfull</div>"; }
}
You're saying to go to a different page, so no, you can't echo more HTML. You can however send that message to the next page via the $_SESSION.
What you are doing is redirecting to another page. The code you are echoing is being output to the browser, but you don't see it because the redirect occurs
the echo you have after the header wont show since you first redirect to another page.
Location says "The page you are asking for isn't here, go to this other place to get it instead".
In general, there is no way for an HTTP header to tell the browser to reload the page. You can only send an HTTP response header in reply to an HTTP request… and if you get an HTTP request, then the page is being reloaded already.
The exception is when it is responding to a request with an If-Modified-Since header.
You may wish to have a read of the mnot caching tutorial which explains how to tell browsers when they should get a fresh copy of a page instead of loading it from the cache.
you cant preview html code because the page will reload to index.php
so use
<?
header("location:index.php");
?>
<div class="yes">Some text will release</div>
Or keep
<div class="yes">Some text will release</div>
For the next page
if you wanna see the html output you can use this
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=index.php">
<div class="yes">Some text will release</div>
and change Content="5 to the number of second that will wait
You have to use meta-refresh instead:
<html>
<head>
<meta http-equiv="refresh" content="3; URL=index.php" />
</head>
<body>
<div class=\"yes\">Succesfull</div>
</body>
</html>
This will display the message for 3 seconds.

HTTP Referrer on Redirection

I have a small script that redirects users to main site if they come from a banner on my/other remote sites.
<?
.
..
...
....
header("location:$golink");
?>
But google analytics will not show the referrer site (where the script is working) instead it shows the url where the banner is clicked. Obviously I can not keep a track of all sites where banner appears and dont want to. I want the refferer to be the site where the script is working. How do I have to use the $_SERVER['HTTP_REFERER']; in order to do this ?
GA has a method that will let you to override the default referring URL (document.referrer) with a specified value.
So if you want to keep the redirect server-side, you can append the referring URL as a query string param in your header() call, and then look for it on the target page and specify it as the referring URL.
I don't know how you are building your $golink variable, but basically you would add something along the lines of:
$golink .= "?ref=" . $_SERVER['HTTP_REFERER'];
Use a & instead of ? if there are already URL params, and the code above assumes using ref as the URL param, so use whatever var you want.
Then on your target pages, before your _trackPageview call, you would add
_gaq.push(['_setReferrerOverride', ref]);
ref would be a javascript variable with the value of the ref=xxx query string param. For some weird reason Javascript does not have a native way to grab URL param values, nor does GA provide an (exposed) solution. If you already have a solution on your pages for grabbing URL params (like something from a framework or a function you've already made) then use that. Otherwise it's pretty easy to find a javascript function that will do it for you.
There are a couple benefits to doing it this way:
You don't have to worry about the visitor seeing an interstitial page.
You don't have to worry about GA not getting a chance to fully load before redirect
You can see the referrers tied directly to your landing pages, because with the interstitial page, you will always see that interstitial page as the referrer, and will have to look at referring url reports for the interstitial page.
Yes, G.A is blind to this kind of server-side stuff. And their PHP Api is not helpful either.
However, you could have a short redirection page, holding the GA tag inside like this :
<html>
<head>
<title>A web page that points a browser to a different page after 2 seconds</title>
<meta http-equiv="refresh" content="2; URL=<?php echo $golink; ?>">
<meta name="keywords" content="automatic redirection">
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
</head>
<body>
If your browser doesn't automatically go there within a few seconds,
you may want to go to
the destination
manually.
</body>
</html>
Notice the $golink variable in the meta tag.
If you use this, do not forget to replace UA-XXXXX-X by your real account number.
Credits : optimized GA tag goes to Mathias Bynens
[EDIT : javascript only version]
<html>
<head>
<title>Redirecting you...</title>
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
<script>
<!--
if (window.addEventListener)
window.addEventListener('load', function() { window.location="<?php echo $golink; ?>"; }, false);
else
window.attachEvent('onload', function() { window.location="<?php echo $golink; ?>"; });
// -->
</script>
</head>
<body>
</body>
</html>

Creating visible redirect?

Please Pardon if the question sounds silly, but nevertheless its a question which I want to know. :)
How can I redirects which display that you are being redirected (like older Gmail and LinkedIn). Whenever I tried to do that, I got errors saying that Headers were already sent.
Then somebody here told me that I should not output any markup before redirection (like facebook login). So how do I go about it and display something nice during redirection??
you want to use meta redirects. they enable you to show a page, and after a few seconds this page will send you to the new page. all you have to do is add a tag to the portion of your 'something nice' redirection page.
here's a quick tutorial on meta redirects:
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
you want to do something like this:
<html>
<head>
<meta http-equiv="refresh" content="2;url=whereto">
were 2 is the number of seconds to display your page and whereto is where you want to send your user
You need to output your page, which will include the following META keyword:
<html>
<head>
<!-- redirection to example.com in 5 seconds -->
<meta http-equiv="refresh" content="5;url=http://example.com/" />
...
</head>
<body>
...
Read the following article for more help: http://en.wikipedia.org/wiki/Meta_refresh
Those redirections are not done via "normal" redirection HTTP headers. Instead they display a page and use either a META Refresh or some Javascript to navigate to the new page.
Personally I find both methods not very nice, both for users and for search engines. Using HTTP headers that also signify why there is a redirect (Permanently moved, temporary, &c.) are way better imho.
If you are getting the headers already sent then that means you were trying to redirect with a PHP header() redirect and you had output on the screen before calling the header() function, 1 solution to that is to use PHP's Output Buffering which will then allow you to call the header() redirect anywhere on the page and not get that error.
To show a message you could use the meta method mentioned in some other answers maybe even throw in a javascript redirect with it, just to be safe however the way I would do it would be something like this below
<?PHP
ob_start();
//show a message
echo 'You will be redirected in 10 seconds';
//amount of time to show the message above before redirecting
sleep(200);
//redirect
header('http://domain.com');
?>
I did not test this but you should get the idea, actually now that I think about it, sleep() might not work correctly as expected with output buffering

Categories