Difference between revisions of "PHP Original"

From CSE330 Wiki
Jump to navigationJump to search
Line 403: Line 403:
== Eclipse and PHP ==
== Eclipse ==
For those of you who like programming with IDEs, Eclipse has support for PHP.  See:
For those of you who like programming with IDEs, Eclipse has support for PHP.  See:

Revision as of 20:56, 3 September 2009


PHP is a server-side language. When a web request for PHP file comes in, the web server processes the PHP file to produce HTML output. That is, the main function of most PHP scripts is to dynamically create HTML content. PHP5 support for Apache is provided by mod_php5. In Ubuntu, you can provide PHP5 support by installing php5. This will install the apache2 module and the php5 command line interpreter (useful for debugging). PHP files may have different extensions, but .php is the most common. In the Apache configuration, you can specify which extensions are going to be treated as PHP scripts by adding the extensions to the list in the /etc/apache2/mods-available/php5.conf file:

 AddType application/x-httpd-php .php .phtml .php3

Declaring PHP

If a PHP file is requested by a web user, Apache parses and interprets the file. Any code declared between PHP tags is then executed and the total HTML output is sent back to the user. PHP code can be declared in a script file in any of the following ways, with the first being the most common:

  PHP Code In Here
  PHP Code In Here
<script language="php">
  PHP Code In Here

For example, edit a new PHP file named info.php, and put these lines in the file:


Put the file in the web directory for your user account (remember that this is ~username/.html/ if you completed the first Module). Then access the web page by going to http://server/~username/info.php. You will see something similar to the picture below:

Php info.png

If you look at the HTML code, you will see quite a lot of HTML output:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<style type="text/css">
 body {background-color: #ffffff; color: #000000;}
 body, td, th, h1, h2 {font-family: sans-serif;}
 pre {margin: 0px; font-family: monospace;}
 a:link {color: #000099; text-decoration: none; background-color: #ffffff;}
 a:hover {text-decoration: underline;}
 table {border-collapse: collapse;}
 .center {text-align: center;}
 .center table { margin-left: auto; margin-right: auto; text-align: left;}
 .center th { text-align: center !important; }
 td, th { border: 1px solid #000000; font-size: 75%; vertical-align: baseline;}
 h1 {font-size: 150%;}
 h2 {font-size: 125%;}
 .p {text-align: left;}
 .e {background-color: #ccccff; font-weight: bold; color: #000000;}
 .h {background-color: #9999cc; font-weight: bold; color: #000000;}
 .v {background-color: #cccccc; color: #000000;}
 .vr {background-color: #cccccc; text-align: right; color: #000000;}
 img {float: right; border: 0px;}
 hr {width: 600px; background-color: #cccccc; border: 0px; height: 1px; color: #000000;}
 <body><div class="center">
 <table border="0" cellpadding="3" width="600">

Of course, none of that HTML was in the info.php file. Instead, the phpinfo() line is a built-in PHP function that produces all of that HTML.

Variables and Arrays

Variables require $ at the beginning of their names (regardless of the purpose, be it setting, be it accessing). You don't need to specify the type of the variable; PHP will use the variable as the correct type based on how it is used in the code.

  #this is an integer
  #this is a string
  $msg="my string";

As in many other languages, statements end with a ;. To actually produce HTML output, you simply print the HTML from the PHP code. The simplest way is to use the print function:

print $msg;

If you use a variable inside of a string, the value of the variable will be put in the string (you might also look at the echo function):

  print "The value of i is $i";

This will generate the string

The value of i is 5

If you create a file with just the above code, you will notice that your browser will only receive the above line. That is, there is no html tag or anything else. Thus, PHP files are normally a mix of HTML code and PHP code. Most PHP scripts, then, look more like this:

  print "The value of i is $i";

The code that the browser will receive is then:

  The value of i is 5

You can have any number of PHP segments and HTML segments in a PHP file. For example:

<? $i=5; ?>
The value of i is <?  print "$i"; ?>

Of course, whatever you print out will be interpreted as HTML by the client's browser, so you can (and will) use HTML tags in the output you produce. For example:

 <? print "This is a <b> test </b> ?> 

This results in the following at the user's browser:

 This is a <b> test </b>

Which would then render test in bold.


Declaring arrays is very easy in PHP. Either you can enter all elements one by one, or you can enter them together:


or alternatively


Then you can access the contents with an index into the array, as normal:

print $student[2];

You can find the size of an array with count function, e.g., count($student)

In PHP, you can also have associative arrays, which are arrays whose members can be accessible with string indices. Here is an example:


echo "test1=",$test[test1],"<br>";
echo "test2=",$test[test2],"<br>";

You can access array keys through array_keys function.

Conditional Statements

if/elseif/else statements provide the conditional statements. The general format is

  some statements
  more statements
   yet more statements

You can use standard comparison operators such as ==,<,> etc.

if ( $string == "this is my string") {
  echo "strings are equal";


 if ($average_temperature>100) {
   echo "No, no, there is no such thing as global warming!!!!";


PHP has for and while loops, similar to Java and C:

while (condition){

For example, the following code will print the sum of numbers from 1 to 10.

  while($i<=10) {
 echo "sum is $sum";

The advantage of loops becomes more obvious when you have to create a long table:

<table border="1">
for($i=0;$i<100;$i++) {
echo "<tr><td>$i </td><td>",$i*$i,"</td></tr>\n";

This creates a table with two columns, each row contains a number and its square.

break and continue are special commands that will interrupt normal control flow through a loop. break jumps out of the loop entirely, while continue jumps to the end of the current loop iteration and flow resumes with the next loop iteration.


PHP functions are identified with the keyword function followed by a function name and argument list for the function.

function name($arg1 [= constant], $arg2 [= constant], ...) {

For example

  function add($x,$y) {
    return ($x+$y);
  echo "Sum of 2+5=",add(2,5); 

If an argument has a default value, it can be specified with the argument on the list:

   function helloMsg($name="there") {
      print "hello $name how are you today?<br>";

The above code will output:

 hello Alice how are you today?<br>
 hello there how are you today?<br>

Passing Variables

Input values can be passed to a script either through the URL request line or through data submitted by a form. Built in arrays $_GET['var'] and $_POST['var'] return the value of var depending on the access method. As we will see in the next section, values can also be passed through session variables. Finally, you can use cookies to store and retrieve values.

If you want to pass values in a URL, the format is http://yourserver/yourphpfile.php?var1=value1&var2=value2.....

For example, the following PHP code would be used to print the previous hello message according to a name given in the URL:


 $person= $_GET['name'];
 function helloMsg($name="there") {
     print "hello $name how are you today?</br>";

If you access the URL like this: greeting.php?name=Alice, it will show hello Alice how are you today?. However, if you access it with greeting.php, it will print hello how are you today?. Note that it does not use the default value there since $name is now a string (in this case, an empty string) and so there is argument being being passed to helloMsg.

Receiving the data from a form is very similar. Consider the following form:

<FORM action="info.php" method="post">
    <LABEL for="firstname">First name: </LABEL>
    <INPUT type="text" name="firstname"><BR>
    <LABEL for="lastname">Last name: </LABEL>
    <INPUT type="text" name="lastname"><BR>
    <LABEL for="birthyear">Birth Year: </LABEL>
    <INPUT type="text" name="birthyear"><BR>
    <INPUT type="radio" name="gender" value="Male"> Male<BR>
    <INPUT type="radio" name="gender" value="Female"> Female<BR>
    <INPUT type="submit" value="Send">
    <INPUT type="reset">

This posts the form data to info.php, with inputs firstname, lastname, birthyear, and gender. The values passed through the form for each input can be accssed in info.php with the $_POST array.


 echo  "Personal Data:", $_POST['firstname'], " ", $_POST['lastname'], "<br>";
 echo  "Birth year:", $_birthyear, " (Age:" , 2007-$birthyear, ")<br>";
 echo "Gender: ", $_POST['gender'];

Session Variables

PHP provides a global array, $_SESSION, for values that are available globally throughout a session. The values will stay there until either you remove them in a PHP script, the user's browser is closed, or their session expires (you can tune the timeout period in the PHP configuration files).

In order to access session values, you should first initiate the session with the session_start() function call. After that, when you access a values with $_SESSION, it will become a session values. For example:




This sets two variables, SESSION and username to be accessible by other pages in this session. In another page, you can access them like so:

if (!isset($_SESSION['SESSION'])) {
  echo "error session is not registered";
else echo "username=",$_SESSION['username'];

You can also remove a session variable from the session with unset command:


Uploading files with PHP

First, you should a form that contains the input type file transfer.php [TAO: this sentence reads wierd...]

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />

When this file is uploaded, you can access the properties of this file throug $_FILES variable. For example, we named the input as uploadedfile. So $_FILES['uploadedfile'] refers to this file. The name of the original file can be found as $_FILES['uploadedfile']['name']. When you upload a file, it is first put to a temporary file. The name of this file can be found as $_FILES['uploadedfile']['tmp_name']. So, in your PHP code, you can move a file from its original location to an upload location by calling a built-in function, move_uploaded_file, which takes an argument for the source and destination locations. Remember that, if you put a relative path, the path will start from the location of your uploader script.


$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";


For those of you who like programming with IDEs, Eclipse has support for PHP. See: http://www.eclipse.org.