Redirecting Browsers to Another Page
[Previous] [Main] [Next]

 
Many web servers recognize special headers in the output stream. It is often useful to have an application simply redirect a browser to another page. This can be done by creating a document page that only contains header information for the browser.  
 
The following example uses the "Location:" header field, which many web servers will use to return another document in lieu of the body. If the value specified is a local filename, the server will send it as the result of the request, as though the browser issued a "GET" for that file. If the value is a full URL, the server will return a "401 redirect" to the browser to retrieve the specified document directly.  
 
See Also
htmlMeta  
 
Example One
 
#include <stdio.h>  
#include <stdlib.h>  
#include <dcmicro/htmlpp/htmlpp.h>  
 
int main( void )  
{  
   htmlCgi   server ;  
   htmlPage  page ;  
   String    new_url = "http://www.connectup.com" ;  
 
   //  Set page options to omit the  
   //  <HTML>, <HEAD>, and <BODY> sections  
   page.NoHTML().NoHead().NoBody() ;  
 
   //  Add header line to redirect the browser  
   page.Header() << "Location: " << new_url << "\n" ;  
 
   //  Output the page  
   server << page ;  
   return 0 ;  
}  
 
Program One Output
 
Content-Type: text/html  
Location: http://www.connectup.com  
 
 
Example Two
 
The following example is similar to Program One above, but retrieves the name of the document to be loaded by decoding a variable named "url" from requested URL. This would typically be used in a hyperlink, such as one for a clickable image or banner advertisement:  
 
   htmlHyperLink  h( "/cgi-bin/redirect?url=http://www.connectup.com" ) ;  
   h << "Click here to go to ConnectUp's home page" ;  
 
 
//  redirect.cpp  
#include <stdio.h>  
#include <stdlib.h>  
#include <dcmicro/htmlpp/htmlpp.h>  
 
int main( void )  
{  
   htmlCgi   server( cin ) ;  
   htmlPage  page ;  
   String    new_url ;  
 
   //  Get the new URL  
   new_url = server.Value( "url" ) ;  
 
   //  If the string looks like a website, but  
   //  lacks the "http://" prefix, add it.  
   if ( new_url.Left(4).AsLower() == "www." )  
      new_url = "http://" + new_url ;  
 
   //  Set page options to omit the  
   //  <HTML>, <HEAD>, and <BODY> sections  
   page.NoHTML().NoHead().NoBody() ;  
 
   //  Add header line to redirect the browser  
   page.Header() << "Location: " << new_url << "\n" ;  
 
   //  Output the page  
   server << page ;  
   return 0 ;  
}  
 


©1998 DC Micro Development. All rights reserved.
No portion of this document may be c opied or reproduced without expressed written consent.
html++ is a trademark of DC Micro Development.