Question

PHP redirect, after page has loaded

Asked by: j8vy

Hello, I know that this question has been asked a million times, a million different ways here at experts-exchange, but unfortunately I was unable to find an existing answer to my question in my search through the existing resolutions. I would like to load my 404 error page completely (display the entire page of content), then after a few seconds, redirect to a specified url of my site.

I would like to be able to either redirect them to the previous page, or to a new url of my site, based on a variable or something, and I would like to set the refresh time via a variable.
E.g.
redirect (
time = 3 /* Refresh time in seconds */
new = 0
/* If $new = 0 we go to a new, if new = 1 we go to the previous page
if $new == 0; {
   new_url = http://newpage/;
} else {
   new_url = $referrer;
}
)
/* Now perform the redirect after a set amount of $time
redirect()

... Obviously I don't know the code, but maybe you will get my idea.

All of my hosting accounts support php, and I use it heavily, especially on my MT installations, so this script should work fine for me. Also, I do not want to rely on JavaScript or a meta tag to perform the refresh, because in some instance, both of these methods may fail, sometimes related to the browser, or JavaScript being disabled by the user. Where, if the server is performing the redirect, it "should" always work.

I appreciate an advice that would be provided. I am definately not a PHP guy, so I need your help :).

Regards,
-MattV

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-12-15 at 22:25:35ID21244506
Tags

php

,

redirect

,

after

,

page

Topic

PHP Scripting Language

Participating Experts
5
Points
400
Comments
27

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. PHP Redirection
    I have another domain I purchased and I want it so the when I person types the domain into their browser it will go to a different .html on my site instead of index.html - how can i use php to accomplish this?
  2. referral
    hello, I have this in domain1.com >goto.php <?php header("Location: " . $_GET['link']); die(); ?> when I type this in IE http://domain1.com/out.php?link=http://domain2.com it goes to domain2.com and when I check logs to see who has referred in domain2.co...
  3. Php Redirect
    Hi Experts, I need to create a PHP page that redirects to namedrive.com, the destination URL should be: http://www.ndparking.com/nameofdomain.com this is the script: <? $domain = $_SERVER['HTTP_REFERER'] ; $dest = "http://www.ndparking.com/"; echo "redir...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jkna_gunnPosted on 2004-12-15 at 23:07:33ID: 12837975

you can use usleep() to pause for a specified time

usleep(5000000); // 5 seconds

normally in php you would use Header('Location: $url') to redirect
but it sounds like you want to show the page contents first then redirect.
im not sure how to do that without javascript or meta. sorry.
   

 

by: jkna_gunnPosted on 2004-12-15 at 23:09:22ID: 12837982

just noticed that sleep() is probably more use to you and you just pass in the number of seconds

sleep(5); // 5 seconds

 

by: j8vyPosted on 2004-12-15 at 23:17:03ID: 12837998

Couldn't you just place the php code near the end of the </body> tag, so that the page would load, then the php script would be executed at the end. We could start execution of the script, then wait the specified seconds, then load a new page. Does this make any sense?

 

by: j8vyPosted on 2004-12-15 at 23:18:56ID: 12838005

p.s. If anyone is wondering why I would wnat to do this w/ a 404 error document, maybe it would make more sense if we used a "thank you" page in our example. ...thank them for ordering, visiting, etc. then send them to the home page. This is why the page needs to load or be displayed before the redirect. Thanks.

 

by: jkna_gunnPosted on 2004-12-15 at 23:30:11ID: 12838040

if you are using the Header() function to redirect then no it can't be at the end.
it must come before any output.

Is redirection absolutely necessary? It may be lame but you could just have a link on the thank you page.
Otherwise I would suggest javascript which im not a fan of either

 

by: j8vyPosted on 2004-12-15 at 23:34:46ID: 12838062

Well, I do have a link there now, but I wanted it automated if possible.

What if ......... what if we just placed an include at the bottom of the page, and the page that we are including could have the pause / redirect code in its header? Would this work? Can you include a script like that and make it work? I have never tried it ...

 

by: jkna_gunnPosted on 2004-12-15 at 23:40:03ID: 12838085

No as output has already been sent to the browser.

I really can't think of a way with PHP, hopefully someone else might be able to help you.

Good luck.

 

by: j8vyPosted on 2004-12-15 at 23:43:40ID: 12838103

Well, thanks for trying, I'll wait until tomorrow to see if anyone else can help with this idea. It may not be possible ...

 

by: RoonaanPosted on 2004-12-16 at 00:30:10ID: 12838265

For the record:
We have two different situations:
1. You want to redirect to the previous page.
2. You want to redirect to a specific page.

[1] You want to redirect to the previous page
There are a few problems with this one. Idealy you would be using javascript to do this, as the way to do it in that language is quite easy:
<script type="text/javascript">setTimeout("history.go(-1)",5000);</script>
You mention however that people might not have javascript enabled. Besides this problem, also usability has always been a strong argument for the custom "go back/continue" hyperlink often seen on this type of pages. You DO want to notify your users on what is happening, so therefor you should always have some kind of line telling them what to do if all else fails.
Skipping the javascript, one other solution might be using $_SERVER['HTTP_REFERER'] to retrieve the previous page. However, increasingly, people have been disabling this feature from their webbrowsers because this would be saver in terms of privacy etc.
Thirdly you could try to use session to track your user. But then again, this might be total overkill to your situation. In this situation I would combine the first two methods:

<?php
if(!empty($_SERVER['HTTP_REFERER']))
  header('Refresh: 5,URL="'.$_SERVER['HTTP_REFERER'].'"');
else
  echo '<script type="text/javascript">setTimeout("history.go(-1);",5000);</script>';
?>

[2] Return to a specific page
Obviously, the best way to handle this is with a plain header('Refresh: ..'); like in the example above.

-r-

 

by: jkna_gunnPosted on 2004-12-16 at 00:45:49ID: 12838343

Didn't know about the refresh header is that equivalent to a META refresh?

 

by: _GeG_Posted on 2004-12-16 at 00:46:48ID: 12838346

just for the record:
you can also put a meta redirect in the head section of the html, like
<html>
<head>
<meta http-equiv="REFRESH" content="15;url=http://www.domain.com/index.html">
...
this would redirect after 15 seconds to http://www.domain.com/index.html

 

by: _GeG_Posted on 2004-12-16 at 00:48:56ID: 12838354

@ jkna_gunn
the refresh header is not part of the official standard, but is supported by most newer browsers.

 

by: RoonaanPosted on 2004-12-16 at 00:49:06ID: 12838355

Yes, header("Refresh") is the same as meta refresh

http://www.desilva.biz/php/phprefresh.html

-r-

 

by: conrad_escapePosted on 2004-12-16 at 07:39:05ID: 12841700

You can also solve this trough plain javascript


function redir($where,$time)
{

$ret ='

<body onload="redirect_delayed();">
<script>
    var isGO;
    function redirect_delayed() {
        if (isGO == true) {
            location.href="'.$where.'";
        } else {
            isGO = true;
        }
        setTimeout("redirect_delayed()",'.$time.');
    }
</script>
';

return $ret;
}

 

by: j8vyPosted on 2004-12-16 at 08:31:10ID: 12842381

I am sorry to be "the bearer of bad news here guys ...", and I certainly appreciate your help, but here are the issues that I raised in my initial question.

1.) One, many people may hav JS disabled.

2. ) The meta "refresh" is simply not supported in all browsers.

I am one of the poeple that is on the "standards" bandwagon! As you can notice with my sites, when I first started, I used to use HTML 3.2, then HTML 4.01 transitioanl (full of tables, some CSS, and JavaScript everywhere. Now, my "new" sites are XHTML 1.1 transitional & CSS strictly and they all validate! I make absolute sure of it! With this move in my business, I also wanted to investigate all options that would allow my websites to perform "uniformly" and look the same to each and every person that reads them ... even if it is a screen reader, which is why I embrace XHTML 1.1 so much. It is so easy for screen readers, humans and even SE "bots to read the pages. I have been having awesome results by using these standards in my coding.

Ok, I'll stop now ... :) :) Those are my reasons, maybe you can understand me.

There simply has to be a way to do this. I think. I have never come to experts-exchange, and left w/o an answer! I feel that if you throw enough programmers at an issue, surely someone will come up with a solution. Thanks again for all of the proposed solutions.

Regards,
-Matt V

 

by: j8vyPosted on 2004-12-16 at 08:39:00ID: 12842519

  Hello again!

Questions for "Roonaan" ...

 Will your solution allow the page to load first? since it has that 5 second pause in it?

Another thing that I like about your solution is, if the refresh doesn't work, it will try JavaScript. Correct?

I guess that if I could just have a solution that would try a couple of different methods before it fails (E.g. header refresh or JavaScript, etc.) then that would be better than nothing.

Also with your proposed solution, would you be able to create a variable that would allow me to tell the script if it must go back one page of if it should go forward to a new page? If it must go forward, then we must also tell it the new address, else just use $referrer or if that fails try JavaScript.

This also refers back to my original post about this solution being "protable", allowing me to use the same script on different pages of my site, in different situations.

...thanks

 

by: jkna_gunnPosted on 2004-12-16 at 13:57:54ID: 12845578

if the header refresh is equivalent to meta refresh then its not a standard which i assume it what your after.

i too use xhtml now and in this case i wouls use javascript to redirect the page
but also have a noscript tag that says your browser does not support automatic redirection please click here etc.

 

by: j8vyPosted on 2004-12-16 at 15:23:51ID: 12846187

Yes, you are right, I would like something that is a "standard".

... What if we wrote a php page that was actually a program itself. ???? What the h^%l do u say??? :) Let me explain further! :)

Ok, so we design a program that "includes" two files when it starts.
- File one contains the settings required to execute the script properly
E.g.
  - time = 3 /* Refresh time in seconds */
  - new = 0 /* =1 -> go to new page / =0 go back one page */
  - new_url = http://domain.com/  /* If new=1 this is the new address */

- File two would contain a template for my site.

Next, our program would execute code "similar" to that provided by 'Roonaan':
<?php
if(!empty($_SERVER['HTTP_REFERER']))
  header('Refresh: 5,URL="'.$_SERVER['HTTP_REFERER'].'"');
else
  echo '<script type="text/javascript">setTimeout("history.go(-1);",5000);</script>';
?>

What I am trying to describe is a program that doesn't  use the header call or JS, but is an actual program that will load the new page or the previous page via an actual request to the server for that particular page's URL, not just a simple redirect. This program would display our "thank you" page template or whatever via an include statement, then just print the page (make a dynamic page of sorts) that we included. I believe that this would allow us to move away from JS and header refresh tags, and into a program that is executed exclusively by the server, not by the client. The 'client' or browser in this case simply request our PHP page/program via link, then the server performes the rest of the functions. Our "programs" stdout would be our template.

Am I even on the right page? Let me know what you think. Thanks.

 

by: RoonaanPosted on 2004-12-17 at 00:20:52ID: 12848428

Hi again.

I do not actually understand your "php as a program" way.

What I would suggest is to have a combination of what I wrote originaly, and what you and others have suggested along the way.

Although the noscript part is the correct way to do it, I would leave it as is, and just have an ordinairy <p> instead of the <noscript>. Why? Because you want all the people to know what is going to happen, and not just those who have cancelled out javascript.

We even could call this a four stages missile :-)
1. Php header();
2. Meta tag
3. Settimeout
4. Manually

<?php

page_redirect(20, 'http://google.com/'); //goto google in 20 secs
//page_redirect(20); //goto previous page in 20 secs

function page_redirect($interval = 0, $redirect = false)
{
  // use page_redirect(i) to goto history(-1) in i seconds,
  // page_redirect(i, 'url') to forward
 
  $use_meta_tag     = false;
  $use_settimeout   = false;
  $use_noscriptback = false;
  $use_noscriptgoto = false;
 
  if($redirect === false) //history.go(-1)
  {
    $refer = !empty($_SERVER['HTTP_REFERER'])
           ? $_SERVER['HTTP_REFERER']
           : '';
  }
  else
  {
    $refer = $redirect;
  }
 
  if(!empty($refer))
  {
    header('Refresh: '.$interval.';'.$refer);
   
    $use_meta_tag =
      '<meta'.
      ' http-equiv="Refresh"'.
      ' content="'.$interval.';'.
      'URL='.htmlspecialchars($refer).'"'.
      ' />';

    $use_settimeout =
      '<script type="text/javascript">'.
      'setTimeout("document.location=\''.
      addSlashes(htmlspecialchars($refer)).
      '\';",'.($interval+500).');</script>';
   
    $use_noscriptgoto = $refer;
    $use_noscriptback = false;
  }
  else
  {
    $use_meta_tag = false;
    $use_noscript_back = true;
    $use_noscript_goto = false;
    $use_settimeout =
      '<script type="text/javascript">'.
      'setTimeout("history.go(-1);",'.
      ($interval+500).');</script>';
  }
 
  //Template
  include "template.php";
}
?>

[[TEMPLATE]]
<?php echo '<'.'?xml version="1.0" encoding="iso-8859-1"?'.'>'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" >
  <head>
    <?php if($use_meta_tag) echo $use_meta_tag; ?>
    <title>You are being redirected</title>
  </head>
  <body>
  <?php if($use_settimeout) echo $use_settimeout; ?>
  <?php if($use_noscriptback) {?>
  <p>Dear visitor, you are being automatically
  redirected to the previous page. If this does not happen
  within <?php echo $interval; ?> seconds, please manually
  go to the previous page.</p>
  <?php } ?>
  <?php if($use_noscriptgoto) {?>
  <p>Dear visitor, you are being automatically
  redirected to the url below. If this does not happen
  within <?php echo $interval; ?> seconds, please manually
  go to this page:
  </p>
  <p style="text-align:center">
    <a href="<?php echo htmlspecialchars($use_noscriptgoto);?>">
    <?php echo htmlspecialchars($use_noscriptgoto);?></a>
  </p>
  <?php } ?>
  </body>
</html>

Hope this works out

Regards

-r-

 

by: RoonaanPosted on 2004-12-17 at 00:22:48ID: 12848436

Hmm.. something wrong with the EE clock?

Comment from j8vy
Date: 12/17/2004 12:23AM CET     <---- 12:23 AM is before 09:20 AM ???

Comment from Roonaan
Date: 12/17/2004 09:20AM CET     <---- 12:23 AM is before 09:20 AM ???

But that was somewhat offtopic :-)

-r-

 

by: j8vyPosted on 2004-12-18 at 10:36:37ID: 12858573

Hello! I am sorry that it has taken me so long to get back with you. I finally got around to incorporating your suggestions into my thank you page today, and there only seems to be one small issue. :)

... there always is (just one small problem), isn't there ! :) :)

The page loads properly, but it does not seem to care how many seconds I specify as the interval. It just redirects immediately. I have tested the script both ways, and it works properly. Meaning if the url is left out, then it goes back one page, but if you supply a url, it goes to that url correctly. It just does it immediately.

I really appreciate your help with this Roonaan. It looks like it is going to work out great!

Regards,
-Matt V

 

by: j8vyPosted on 2004-12-18 at 10:46:54ID: 12858608

Oh, damn it!! I always forget the important stuff!! ..........

I wanted to show you some things in case you wanted to look:

My thank you page: http://www.unique-wholesale-source.com/thanks.php

Your script (my implementation): http://www.unique-wholesale-source.com/thanks.php.txt

My current Template: http://www.unique-wholesale-source.com/thanks.tmpl.txt

(see all of those tables ..., this is one of my previous designs before I started using Movable Type and stepped up to XHTML)

P.S. You will have to use a Gecko based browser such as FireFox to look at the template text file. IE loads it as an HTML page ...stupid, SPYWARE infested IE .... :(

 

by: j8vyPosted on 2004-12-22 at 05:44:31ID: 12883638

Hello again! I am just wondering if you have had any chance to review this issue? Thanks again for your help. We just need to make the $interval var work properly, and we will be good to go.

-Matt

 

by: MasterEthanPosted on 2005-01-04 at 22:48:36ID: 12959830

Alright, haven't read EVERY comment, but I think I have a solution.

<?
$refresh_time = "5"; /* Seconds to refresh */
$refresh_new = "0"; /* 0 => New Page, 1 => REFERER.  DEFAULT VALUE "0" */
$refresh_new_url = "http://www.newurl.com/newpage.html";
$refresh_time = $refresh_time * 1000
if(!empty($_SERVER['HTTP_REFERER']) {  /* Check is REFERER is set. */
    $refresh_new = "1";
}
if($refresh_new == "1") { /* REFERER */
?>
<script type="text/javascript">setTimeout("history.go(-1);",$time);</script>
<noscript><a href="<?=$_SERVER['HTTP_REFERER']?>">Click Here to return to previous page.</a></noscript>
<?
} else if($refresh_new == "0") { /* New Page */
?>
<script type="text/javascript">setTimeout("window.location="$refresh_new_url";.",$time);</script>
<noscript><a href="<?=$refresh_new_url?>">Click Here to go to the home page.</a></noscript>
<?
}
?>

That should do it.

 

by: j8vyPosted on 2005-01-05 at 20:06:02ID: 12969157

Hello, I am sorry, but I am extremely busy at this moment. I need to complete a Movable Type install / site design, then I can get back to this code which is for one of my sites.

If you don't hear from me in a couple of days, just post here again so I will get an email. Thanks for your help! I really appreciate it. :)

Regards,
-Matt V

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...