PHP Original

From CSE330 Wiki
Jump to navigationJump to search

PHP5

PHP is a server-side language. If your apache is configured to support PHP, then before serving a PHP file, it process it and creates the corresponding HTML code. The advantage is that, you can create dynamic page that can be changed easily. PHP support for Apache is provided by mod_php5 (or mod_php4 if you want to use PHP4). In debian, you can provide php5 support by installing libapache2-mod-php5. This will install apache2 module. There is also php5 commandline interpreter (useful for php5 debugging), which can be installed through php5 meta package. PHP files may have extensions (while .php is the most common). In Apache configuration, you can specify which extenstion are going to be threated as php code by adding the new extentsio to the list of extensions for php.

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

The above code requires mod_php5 to be installed. In debian, the above declaration is stored under /etc/apache2/mods-available/php5.conf.


Declaring PHP

If a file with .php extention (or PHP supported extentions) are requested from Apache, apache parses and interpretes the file. Any code declared between PHP tags are than executed and corresponding HTML file is sent back to the browser. PHP code can be declared with any of the following ways:

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

For example, try this in a php file

info.php


<? 
 phpinfo();
 ?>

And access it through web (http://yourserver/directory_to_file/info.php)

You will see something similar to the picture below:

Php info.png


If you look at the HTML code, you will see a very long text:


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
 <html><head>
<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;}
 </style>
 <title>phpinfo()</title></head>
 <body><div class="center">
 <table border="0" cellpadding="3" width="600">
 ....


What you may noticed is that, we didn't have any html declaration in PHP file. phpinfo is a PHP function that gives all the information. So the segment we wrote is replaced by the output of phpinfo.

Variables and Arrays

The variables require $ at the beginning of their names (regardless of the purpose, be it setting, be it accessing). You don't need to specify type of the variable, as it will be decided based on your setting.

<?
#this is an integer
$i=5;
#this is a string
$msg="my string";
?>

Notice that we have to put ; just like most other high level languages. You can print variables with print function.

print $msg;

you can put a variable inside a string, and the value of that variable will be included in the string. (Note that you can also use echo function, which is slightly faster and can take multiple arguments.)

<?
 $i=5;
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. For example, there is no html tag. PHP files are normally a mix of HTML code and PHP code.

The correct way is to write a well defined HTML code

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

The code that the browser will receive is then be

<html>
<body>
  The value of i is 5
 </body>
</html>

As html and php code are mixed together, you can receive the same effect with the following code

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

</body>
</html>

For the rest of this document, I assume you have the HTML components there, so I will just look at PHP components. Note that, if your print system actually prints the values your browser going to receive. So, if you print some html tags, your browser is going to execute it, e.g.,

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

would cause the browser to receive

 This is a <b> test </b>

which will then be rendered with a bold test.

Arrays

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

$student[0]="Alice";
$student[1]="Bruce";
$student[2]="Charlie";
$student[3]="Dan";
or alternatively
$student=array("Alice","Bruce","Charlie","Dan");

Then you can access the contents with an array index

print $student[5]


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

In php, you can also have associative arrays, that is the arrays whose members can be accessible with strings. An example for such arrays could be

<?
$test["test1"]=1;
$test["test2"]=2;

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

You can access array keys through ''array_keys'' function.

Conditional Statements

if statements provide the conditional statements. The general format is

if ( CONDITION ) {
    some statements
} else {
}
You can use standard comparison operators such as ==,<,> etc.
if ( $string == "this is my string") {
  echo "strings are equal";
}

or

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

Loops

You can use for or while loops. The formats are very similar to C.

for(initialization;condition;loop_increment){
}
 
while (condition){
}
For example, following code will print the sum of number 1 from 10.
  $sum=0;
  $i=1;
  while($i<=10) {
    $sum=$sum+$i;
    $i++;
  }
 
 echo "sum is $sum";
 

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

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

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

break and continue are special commands that will interrupt the loop execution, or jump to the end of loop.

Functions

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

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 could be specified at the argument list

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

Passing Variables

The variables are passed either within URL or when php file receives data submitted by a form. Built in functions $_GET['variablename'] and $_POST[variablename] return the value of variablename depending on the access method. As we will see in the next section, the variables can also be passed through session variables. Finally, you can use cookies to store and retrieve the variables.

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

For example, the following PHP code would be used to print previous hello message according to the name received at URL:

greeting.php:



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

If you access this php file with 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. As you have noticed, it didn't used the default value there since $name is now a string (eventhough it is just "") hence there is an argument sent to helloMsg.


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

<FORM action="info.php" method="post">
    <P>
    <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">
    </P>
 </FORM>

This posts the form data to info.php. Notice that, inputs firstname, lastname, birthyear and gender.

Then we can access those variables through $_POST function in info.php

info.php

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

Session Variables

PHP5 provides a global array, $_SESSION to provide variables that are available globally through a session. The variables will stay there until either you remove them, or you close your browser (or session expired).

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

setsessionvars.php

<?
session_start();

$_SESSION['SESSION']=1;
$_SESSION['UNAME']="burchan";
?>

will set two variables, SESSION and UNAME to be accessible by other pages. In another page, you can access them with

<?

session_start();
if (!isset($_SESSION["SESSION"])) {
  echo "error session is not registered";
  }
  else echo "Username=",$_SESSION['UNAME'];
?>

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

unset($_SESSION['SESSION']);

Uploading files with PHP

First, you should a form that contains the input type file transfer.php


<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" />
</form>


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.

uploader.php:

$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!";
}

Eclipse and PHP

PHP Eclipse is installed locally at

/home/cec/faculty/cs/bayazit/eclipse-extensions

You can add this plugin directory to your eclipse workspace by adding an extension location

Help -> Software Updates ->  Manage Configuration -> Add an Extension Location