CSc103's Frequently Asked Questions on PHP

Some tutorials:


How do I redirect to a different page?

I did this with redirect.php. This works as follows:

Unbeknownst to you, when http sends a page, it first sends some headers, then a blank line, then the actual html. One header that is always sent is:
Content-type: text/html
If you want to send other headers, there are some PHP functions to do this, the simplest is header(). the Location header causes most browsers to go straight there:
The only trick is to put this function call in a php block that starts immediately as the first thing in your file, before even a space!
Redirecting to <a href="">somewhere else</a>, should happen in a few seconds.

Alternatively, you can redirect with a header  or meta-tag, REFRESH, which takes a number of seconds and (new) location. This can be immediate, or result in a timed delay. This is HTML.

<meta http-equiv="REFRESH" content="5; url=">
Answer in 5 seconds!

Cookies: How do I get the client to remember something for me?

Another "header" sets a cookie, the next time the client calls for a page from you, your "cookies" are sent back to you. This is good, because you may be getting requests from many different clients. Cookies can even be persistent, if you set an expiration date in the far future. By default, a cookie is kept until the browser is closed.
So, let's suppose a user has just submitted a form, choosing a language, so the query string says: lang=en  for example. There is a special PHP Cookie function to help you, do this (again, before anything is printed):
$lang = $_COOKIE['lang']; //get the cookie, if any
if ($newlang=$_GET['lang']) //get any (new) choice from a form
{ setcookie ('lang',$newlang, time()+60*60*24*365); // set the 'lang' cookie.
$lang = $newlang; // will expire one year from now
Only the first argument is required. The second, an actual value, would be logical to include. The third is a time in the past (gets the cookie deleted) or future, its units are "Seconds since 1 January 1970, midnight GMT".  Wow! In this example
  1. We take the cookie value, if it exists.
  2. We look for a value in the query string, and set a cookie with that value, overriding any older cookie
  3. Set it to expire one year from now (if I calculated seconds in a year properly)
  4. note: $lang may well be undefined at this point. Provide for a default.
Now any of your pages have access to the cookie, but be aware that some people do not accept cookies or may delete them.
JavaScript can also access the cookies in document.cookie, which is a string of the form: "lang=fr; colour=red; prov=qc" see my cookie.html