CSE 134A: HTTP Redirects with PHP

To redirect the browser to a different URL, I recommend using PHP's header() function like so:

<?php header("Location: http://www.cs.ucsd.edu/~elkan/134A/") ?>

This is exactly the code in http://www.cs.ucsd.edu/~ddahlstr/cse134a/index.php. If you load this URL in a browser, you'll see it redirects to the course Web page under Professor Elkan's account.

The header() function causes the Web server to return a line in the HTTP headers as opposed to where output usually goes: in the body of the response. Specifying a Location header is actually a special case causing the server to issue a redirection status code (302 Found) instead of the usual successful status code (200 OK). The 302 Found code instructs the browser to load the URL specified by the Location header. You can see these headers by using telnet to request this page from the server:

$ telnet www.cs.ucsd.edu 80
Trying 132.239.51.20...
Connected to www.cs.ucsd.edu.
Escape character is '^]'.
GET /~ddahlstr/cse134a/ HTTP/1.0

HTTP/1.1 302 Found
Date: Sat, 19 Oct 2002 19:25:51 GMT
Server: Apache/1.3.22 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.5 OpenSSL/0.9.6b
DAV/1.0.2 PHP/4.2.2 mod_perl/1.26
X-Powered-By: PHP/4.2.2
Location: http://www.cs.ucsd.edu/~elkan/134A/
Connection: close
Content-Type: text/html

Connection closed by foreign host.

Compare this to an ordinary response returning a page. Notice the status code is 200 OK instead of 302 Found, and there is no Location header:

$ telnet www.cs.ucsd.edu 80
Trying 132.239.51.20...
Connected to www.cs.ucsd.edu.
Escape character is '^]'.
GET /~elkan/134A/ HTTP/1.0

HTTP/1.1 200 OK
Date: Sat, 19 Oct 2002 19:28:02 GMT
Server: Apache/1.3.22 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.5 OpenSSL/0.9.6b DAV/1.0.2 PHP/4.2.2 mod_perl/1.26
Connection: close
Content-Type: text/html

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
[rest of page omitted]

Note: If you're having problems with redirects, make sure you've read the header() function documentation. In particular, keep in mind if any page content is written before calling the function, you'll get an error.