Is there a PHP equivalent for ASP response.redirect()

markgoodall
markgoodall used Ask the Experts™
on
Is there an equivalent to the ASP command Response.Redirect ?

In ASP you can put the following code

<% Response.Redirect("http://www.newsite.com") %>

anywhere in the page, and it will take the visitor to that new site.

Is there a way to do that in PHP?

The important part is being able to add it ANYWHERE in the page, not being forced to do it up in the HTML HEADER section.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you can use header() function:

header('Location: http://www.newsite.com');

if you don't have output caching turned on in php, then you have to  call this function before any output to the browser
leakim971Multitechnician
Top Expert 2014
Commented:
Or :


<html><head>
<meta http-equiv="refresh" content="0;URL=http://www.newsite.com">
</head><body></body></html>

Open in new window

Top Expert 2005

Commented:
Yep, that's it.
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Commented:
You won't be able to use php's redirect without keeping it in the header, but if the reason that you need it in php is so that you can choose the location by a php variable, you can opt for javascript written by php. Which can be placed anywhere in your code.

Here's an example:

<?php
$redirect_to = "http://www.google.com";

echo '<script type="text/javascript">
<!--
window.location = "'.$redirect_to.'"
//-->
</script>';

?>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
You can use output buffering to capture the browser output stream (this has performance advantages, too) and this will permit you to send headers at any time you want, so long as you have not sent any browser output.  And with the buffer, you will not send any browser output.  See the man page here:
http://us3.php.net/manual/en/function.ob-start.php
<?php // DEMONSTRATE HOW OUTPUT BUFFERS ALLOW REDIRECTION LATER IN THE CODE LOGIC
error_reporting(E_ALL);
ob_start();
// CREATE BROWSER OUTPUT - THIS GOES INTO THE OUTPUT BUFFER
echo "Hello World";

// REDIRECT
header("Location: /");
exit;

// OUTPUT BUFFER IS FLUSHED BY GC AT PAGE END

Open in new window

Author

Commented:
I'm afraid none of this will work.  

The PHP system in question is overly complex, and each page is built dynamically using up to a dozen included files.   I need to place the code to cause the redirect only on one page but that page only exists as a section that is included at the end of a long list of other includes.  

I need it to function like the ASP response.redirect which is not dependant on placement or anything else to work, it just works.

It sounds like it may be impossible to achieve in PHP.

Most Valuable Expert 2011
Top Expert 2016

Commented:
No, it is not impossible to achieve in PHP - every solution on this page is workable.  But you've got to start with a baseline PHP application that has a sensible design.

Please do two things for us.  First, show us what the generated HTTP headers and/or HTML are from a simple ASP response.redirect statement.

Next, please post the PHP source code for the page where you want to cause the redirect.  I am sure we can help.

Best regards, ~Ray

Author

Commented:
Then let me re-state..... it's likely impossible to achieve using one single PHP command in this particular implentation.  I'm afraid I can't see how any of these solutions so far would work in this particular site.

I really wish I could start with a baseline PHP application that has a sensible design, but this is what I've inherited, and it is what is is, overly complex.

It sounds like the PHP solutions here are browser based. Is that possible?  Perhaps I'm not describing it well, but let me try.   It sounds lilke in the solutions here have the server send instruction back to the browser to cause the browser to jump to the new page. Sort of like the   < meta http-equiv="refresh" content="1;url=default.asp" > does.  It sends the page back to the browser, then the browser jumps to the new page.  Is that right or am I compleley confused on how this works.
 
I think the difference is that the ASP redirect solution is a server-based solution.  When the server sees the Response.Redirect it halts what it's doing and fetches the new page and servers that up to the requesting browser.    The browser has no idea the page was redirected.  

The ASP response.redirect causes the server to send back a different page.  It sounds like the PHP solution send information abck to the browser to tell it to jump.    Big difference.

At least that my impression.  

Hmmmm.... there's got to be a way to get this to work reliably in PHP.....  

Author

Commented:
I wish I could describe how this PHP site is designed.  There seems to be only one single PHP page, and based on parameters, it changes it's content by including up to a dozen included files that come from a library of hundreds of other PHP page segments.  
Most Valuable Expert 2011
Top Expert 2016

Commented:
meta http-equiv="refresh"  - that is one of the proposed solutions, yes.  Your description of how it works sounds correct to me.  The browser does not "jump" - it makes an HTTP request for the new page.

If this is true: "The browser has no idea the page was redirected." then redirect is not the correct terminology.  Browsers request pages - servers do not just spontaneously send pages.  That's a law of RESTful interfaces, and HTTP is the dictionary-picture of a RESTful interface.

From your description it sounds like the response.redirect simply causes the ASP machine to produce a different set of HTML, but from reading this article, it appears that response.redirect is actually HTTP 302 + header(Location)
http://pubs.logicalexpressions.com/pub0009/LPMArticle.asp?ID=214

Let's try this again:

Please do two things for us.  First, show us what the generated HTTP headers and/or HTML are from a simple ASP response.redirect statement.

Next, please post the PHP source code for the page where you want to cause the redirect.  I am sure we can help.

Thanks and regards, ~Ray

Author

Commented:
Okay, thank you. Let me try.....

Here source code for: testpage1.asp
----------------------------------------------------------------------------------------------------------------------
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Page #1</title>
</head>
<body>
This is Test Page #1
<% Response.Redirect("testpage2.asp") %>
</body>
</html>
----------------------------------------------------------------------------------------------------------------------


Source code for: testpage2.asp
----------------------------------------------------------------------------------------------------------------------<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Page #2</title>
</head>
<body>
This is Test Page #2
</body>
</html>
------------------------------------------------------------------------------------------------------



And this is what the browser receives when you go to http://www.domain.com/testpage1.asp
------------------------------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Page #2</title>
</head>
<body>
This is Test Page #2
</body>
</html>
------------------------------------------------------------------------------------------------------------
which is identical to what the browser receives when you go to http://www.domain.com/testpage2.asp


Did I show this properly?
Top Expert 2005

Commented:
Do you have tamper headers add-on for Firefox?  Here are the headers for a 301 (not the same as a response redirect, but these are the actual HTTP Headers, not the <HEAD> section of the web pages.




Requested: http://www.rodsdot.com/ee/add-days-to-javascript-date.asp

Actual File Content
<%
Dim newLocation
newLocation = "http://www.rodsdot.com/javascript/add-days-to-javascript-date.asp"
Response.Status = "301 Moved Permanently"
Response.AddHeader "Location", newLocation
Response.End
%>


Request Header Name		Request Header Value
User-Agent			Mozilla/5.0 ..........
Accept				text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language			en-us;en;q=0.5
Accept-Encoding			gzip,deflate
Accept-Charset			ISO-8859-1,utf-8;q=0.7;*;q=0.7
Keep-Alive			300
Connection			keep-alive




Response Header Name		Response Header Value
Status				Moved Permanently - 301
Connection			Close
Date				Sat, 30 Jan 2010 03:22:26 GMT
Server				Microsoft-IIS/6.0
Location			http://www.rodsdot.com/javascript/add-days-to-javascript-date.asp
Content-Length			0
Content-Type			text/html
Set-Cookie			ASPSESSIONSDIHIAHHFEAEW-SDJDKHIHAREWRSJDVBLSDAD; path=/
Cache-Control			private

Open in new window

Top Expert 2005

Commented:
Or you can telnet into the server and request the redirect page.
Top Expert 2005

Commented:
You can't do a Response.Redirect after the page headers are written in ASP or PHP.

This is the output from your Test Page #1 copied exactly as you wrote above.
This is Test Page #1

Response object error 'ASP 0156 : 80004005'

Header Error

/test_page_1.asp, line 10

The HTTP headers are already written to the client browser. Any HTTP header modifications must be made before writing page content.

Open in new window

Top Expert 2005

Commented:
A valid redirect: FWIW

Requested: http://olympus/mytestpage1.asp

Actual Content:
<%
Option Explicit
Session.CodePage=65001
Response.Charset="UTF-8"
Response.Redirect("testpage2.asp")
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
</body>
</html>


Request Header Name		Request Header Value
Host=olympus			User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko....
Accept				text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language			en-us,en;q=0.5
Accept-Encoding			gzip,deflate
Accept-Charset			ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive			300
Connection			keep-alive
Cookie				ASPSESSIONIDSQQTDSBQ=IEJLDJOBIFAKNAOFGAFOGLBN


Response Header Name		Response Header Value
Status				Object moved - 302
Date				Sat, 30 Jan 2010 06:39:22 GMT
Server				Microsoft-IIS/6.0
X-Powered-By=ASP.NET		Location=testpage2.asp
Content-Length			134
Content-Type			text/html;
Charset				UTF-8
Cache-Control			private

Request Header Name		Request Header Value
Host				olympus
User-Agent			Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/.....
Accept				text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language			en-us,en;q=0.5
Accept-Encoding			gzip,deflate
Accept-Charset			ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive			300
Connection			keep-alive
Cookie				ASPSESSIONIDSQQTDSBQ=IEJLDJOBIFAKNAOFGAFOGL

Open in new window

Author

Commented:
Hello rdivilbiss,  you said

"You can't do a Response.Redirect after the page headers are written in ASP or PHP. This is the output from your Test Page #1 copied exactly as you wrote above."

and I see that 'ASP 0156 : 80004005' error.... but I don't understand where you are seeing/getting that error.    I have these test ASP pages on a server and they work exactly as described. They don't produce that ASP 0156 error that you showed me.

I'm confused.   What is that "ASP 0156 error" that you showed me? Why are you seeing that type of error, but I get no such error from my ASP server?

 
Most Valuable Expert 2011
Top Expert 2016

Commented:
What rdivilbiss means in "can't do a Response.Redirect after the page headers are written in ASP or PHP" refers to an immutable law of the HTTP protocol.  In HTTP, you must produce all of the headers completely and send them all before any of the response output (ie, the HTML).  Once the last header has been sent, you can start sending browser output.  Once any bit of browser output has been sent (even white space), you cannot send headers any more.  There is no way around this.  A header that follows any of the browser output causes the errors shown above in the post at 01/30/10 01:35 AM, ID: 26443559.  There is a different error message from PHP, but the issue is exactly the same.

We are trying to help you here, so I'm going to request this one more time before I give up on this question:

"Next, please post the PHP source code for the page where you want to cause the redirect.  I am sure we can help."

Thanks, ~Ray

Author

Commented:
Okay, I think I undersanding what you are saying, however when you say:

"can't do a Response.Redirect after the page headers are written in ASP or PHP"

do you mean:

"shouldn't do a Response.Redirect after the page headers are written in ASP or PHP"

because I do a Response.Redirect at the end of the ASP code and it work's well as far as I can tell.
The browser goes where expected without any errors or anything.  I appears that it's working, but from what I'm understanding from you is that it shouldn't be working?  



Author

Commented:
Here is the contents of the PHP file that I would need to place the redirect:

---------------------------------------------------------------------------------------------------------------------
<div class='outlined_main'>
<div class='clearfix outlined_main_inner'>
      
      <div style='font-size:16px;text-align:center;color:red;margin-top:8px;margin-bottom:30px;'>
            Also, you can visit <a href="http://www.xxxxx.com">www.xxxxxx.com</a> to check for the xxxxxx nearest you.
      </div>
      
   <table cellspacing='0' cellpadding='0' width='100%' style='margin-top: 15px; margin-bottom: 5px;'>
   <tr>
   <td><h2>Your Contact Information</h2></td>
   </tr>
   </table>


   <form onsubmit='return check_form(this);' action='<?php echo $GLOBALS['live_remote_path']; ?>xxx/sign-up' method='post'>
      
      <input class='regular' type="hidden" name="required" id="required" value="txt_city_id,txt_first_name_id,txt_phone,txt_last_name_id,txt_age_id,txt_email_id" />
      
   <div class='greybox' style='margin-bottom: 20px;'>
   <div class='insider_formbox'>

   <strong>EMAIL ADDRESS:</strong>
   <input class='regular' size='29' name='txt_email' id='txt_email_id' value='<?=$xxxxx_email?>' type='text'/>


the file does continue, but I'm not sure you need the rest.

Thanks again for you help!


Most Valuable Expert 2011
Top Expert 2016

Commented:
Why are you trying to avoid this simple request?

"Next, please post the PHP source code for the page where you want to cause the redirect.  I am sure we can help."

We cannot help you without seeing the code, full stop.  

I meant exactly what I wrote.  There are many layers of complexity to understanding the interaction of ASP, PHP and HTTP protocol, and I do not have time or patience to try to teach you this over the EE forum here.  If you want any further help with this question, just post the code.

Thanks, ~Ray
Most Valuable Expert 2011
Top Expert 2016

Commented:
Last time.  Please post the code.  All of the code.  Use the code snippet.  Thank you.

Author

Commented:
I'm sorry,  I'm not trying to avoid it.  Did I post it incorrectly?

That is the first two dozen lines of the PHP file,  I didn't think it was necessary to post the remaining lines, but I can if necessary.





Author

Commented:
For the sake on anonymity for the parties involved, I  did X-out some of the specific anmes and URLs. I hope that's okay.
 
Top Expert 2005

Commented:
>>Please post the code.  All of the code.  Use the code snippet.  Thank you.

Is the delay in solving the question, not the lack of experts.

Michel PlungjanIT Expert
Top Expert 2009

Commented:
Just for completeness sake:
http://msdn.microsoft.com/en-us/library/ms524309.aspx

I can see nothing in the snippet you posted that indicates that you can do a response.redirect or the php equivalent after the code. You cannot redirect after anything non-header has been outputted
Also looking at the code, what would a redirect accomplish. I think you have convinced yourself that you have a hammer and now all your problems look like nails. No dis-respect intended.

So I suggest you explain what the use-case is for this issue.
1 The user arrives at page x
2. The user decides to y
3. ????
4. profit
Michel PlungjanIT Expert
Top Expert 2009

Commented:
Enlighten me, please

Author

Commented:
Hello rdivilbiss, I have already posted the code "snippet" above.  This is the contents of the PHP that I can modify.  Did I post it incorrectly?   I didn't include the end part, only the top part of the PHP file. And I changed a few of the URL references for privacy.  Isn't that okay?  

Author

Commented:
Hello mplungjan,  let me try to re-explain my issue.  I'm trying to explain it to the best of my ability.  I thought my inition question was clear, but perhaps it isn't.

I have a PHP source file that contains a portion of the visable contents of a particular webpage.  This PHP file is not the whole webpage, just a portion of it.   There are a dozen other PHP source files that are included in the final webpage that is sent to the browser.

I need to quickly turn that webpage off. I need to make it so that when a visitor goes to that webpage, they are forwarded to a new page instead.    I don't have access to all the other PHP source files that create that webpage.  The webpage is composed of at least a dozen other files that can't be changed right now.  So this means that I can't change the part of the webpage that has the <HEADER> tag.  If I could access and change the PHP file that contains the HEADER tag, I would, but I can only change the PHP file that is included down further in the body of the webpage.     It's a bad situation, I know, but it is a reality.

I know that in ASP, I can place a <% Respose.Redirect "url" %> command at the bottom of a page, and somehow it successfully causes the browser to go to the right page.  No need for eveyone to argue if it's possible or how it's possible.  All that matters is that it is possible and it works.   It may not be good programming practice, and may be a bandaid solution, but it effectively let's me redirect a page.  I've probably used it 2 or 3  times in the last 15 years of web programming as a temporary fix when necessary.

I have a situation where the ability to do this...... to place some sort of redirect command within the body of a web page..... would be extremely helpful.    If this were an ASP site I'd place the Response.Redirect down in the body of the page, and it would take care of taking the visitor to the new page temporarily until we gain access to the rest of the files.

I was just hoping there was a similar way to do this in PHP, that's all.   I understand everyone saying that it must be done in the HEADER section.  Okay, I get that.  In ASP it can be done outside the HEADER section and it works.  

Not sure what you mean by hammer and nail.  I just wanted to know if bandaid solution that exists in ASP existed in PHP.  

Author

Commented:
Hello mplungjan, you asked:
--------------------------------------------------------------------------------------
So I suggest you explain what the use-case is for this issue.
1 The user arrives at page x
2. The user decides to y
3. ????
4. profit
--------------------------------------------------------------------------------------
and I don't really know wht that means, but let try......

1. User arrives at page x
2. User is taken to page y

I have no idea what 3.???? and 4. Profit mean.

Let me try this way.....

1. User arrives at page x, which was created/assembled by the contents of the files x1,x2,x3,x4,x5 and x6.

2. I can only change the contents of the file x5 and need to redirect them to the page y.

3. I don't have programming access to change the file x1.

4. In ASP, I can put a temporary redirect in the file x5 and it will take the user to page y.

5. It sounds like I would need to have programmng access to file x1 to do it in PHP




Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

Commented:
short answer: you cannot do that in php.
you could flush the buffers etc with:
http://www.php.net/manual/en/function.ob-end-clean.php
but this requires that x1 includes the ob_start() call.

the only "way" I see is that the x5 somehow hides all the output from x1-x4, and shows y via a frame, for example ...
I don't think that is really what you want to do, neither ...
Most Valuable Expert 2011
Top Expert 2016

Commented:
Regarding this:

"I understand everyone saying that it must be done in the HEADER section.  Okay, I get that.  In ASP it can be done outside the HEADER section and it works."

No, it does NOT have to be done in the header section of the HTML.  You can do it in the body!!

Substitute your fully qualified URL into this statement in place of the "example.com" string.  Put that line into the "x5" part of the script collection.  Then run it and see what happens.  If it does not do EXACTLY  what you want, let's revisit the request to POST THE CODE, thank you.
<?php // REDIRECT 

echo "\n\n<meta http-equiv=\"refresh\" content=\"0;URL=http://example.com\">\n\n";

?>

Open in new window

Commented:
"The PHP system in question is overly complex, and each page is built  dynamically using up to a dozen included files.   I need to place the  code to cause the redirect only on one page but that page only exists as  a section that is included at the end of a long list of other includes. "

What may help; write a condition in that section and echo the redirect.

<?php
if ($_GET['pageid_orsomething']=='pagethatyouwanttoredirect'){
  echo('<meta http-equiv="refresh" content="0; 
  URL=http://www.yoursite.com/test" />');
}
?>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial