Difference between revisions of "PHP Original"

From CSE330 Wiki
Jump to navigationJump to search
(Removed Ubuntu support)
 
(53 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 
= PHP5 =
 
= 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 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. 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/httpd/conf.d/php.conf'' file:
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''.
 
  
 +
  AddType text/html .php .phtml .php3
  
 
==Declaring PHP==
 
==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:
+
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
PHP Code In Here
+
  PHP Code In Here
 
  ?>
 
  ?>
  
 
  <?php
 
  <?php
PHP Code In Here
+
  PHP Code In Here
 
  php?>
 
  php?>
  
 
  <script language="php">
 
  <script language="php">
  PHP Code In Here
+
  PHP Code In Here
 
  </script>
 
  </script>
  
For example, try this in a php file
+
You may see the following shortcut syntax for declaring php, but it may not work unless the shortcut syntax is configured for your server, as such we generally recommend sticking with one of the first ways of declaring php.
 +
<?
 +
  PHP Code In Here
 +
?>
  
info.php
+
For example, edit a new PHP file named ''info.php'', and put these lines in the file:
  
 
+
  <?php
  <?  
+
  phpinfo();
  phpinfo();
+
?>
  ?>
 
 
   
 
   
 +
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:
  
And access it through web (http://yourserver/directory_to_file/info.php)
+
[[Image:Php_info.png]]
  
You will see something similar to the picture below:
 
  
[[Image:Php_info.png]]
+
If you look at the HTML code, you will see quite a lot of HTML output:
  
 
If you look at the HTML code, you will see a very long text:
 
 
<code><pre>
 
<code><pre>
 
 
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
 
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
 
  <html><head>
 
  <html><head>
Line 73: Line 68:
 
</code>
 
</code>
  
 
+
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.
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==
 
== 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.
+
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
+
  <?php
$i=5;
+
  #this is an integer
#this is a string
+
  $i=5;
$msg="my string";
+
  #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.
+
 
 +
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;
 
  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.)
+
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):
  
  <?
+
  <?php
  $i=5;
+
  $i=5;
print "The value of i is $i";
+
  print "The value of i is $i";
 
  ?>
 
  ?>
 +
 
This will generate the string
 
This will generate the string
 +
 
  The value of i is 5
 
  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.
+
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:
  
The correct way is to write a well defined HTML code
 
 
<code><pre>
 
<code><pre>
 
<html>
 
<html>
 
<body>
 
<body>
<?
+
<?php
 
   $i=5;
 
   $i=5;
print "The value of i is $i";
+
  print "The value of i is $i";
?>
+
?>
 
</body>
 
</body>
 
</html>
 
</html>
 
</pre>
 
</pre>
 
</code>
 
</code>
The code that the browser will receive is then be
+
 
 +
The code that the browser will receive is then:
 +
 
 
<code><pre>
 
<code><pre>
 
<html>
 
<html>
 
<body>
 
<body>
 
   The value of i is 5
 
   The value of i is 5
</body>
+
</body>
 
</html>
 
</html>
 
</pre>
 
</pre>
 
</code>
 
</code>
  
As html and php code are mixed together, you can receive the same effect with the following code
+
You can have any number of PHP segments and HTML segments in a PHP file. For example:
 +
 
 
<code><pre>
 
<code><pre>
 
<html>
 
<html>
 
<body>
 
<body>
<? $i=5; ?>
+
<?php $i=5; ?>
The value of i is <?  print "$i"; ?>
+
The value of i is <?php print "$i"; ?>
 
 
 
</body>
 
</body>
 
</html>
 
</html>
Line 134: Line 134:
 
</code>
 
</code>
  
For the rest of this document, I assume you have the HTML components there, so I will just look at PHP components.
+
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:
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.,
 
  
 
<code><pre>
 
<code><pre>
  <? print "This is a <b> test </b> ?>  
+
  <?php print "This is a <b> test </b> ?>  
 
</pre></code>
 
</pre></code>
  
would cause the browser to receive
+
This results in the following at the user's browser:
 +
 
 
<code><pre>
 
<code><pre>
 
  This is a <b> test </b>
 
  This is a <b> test </b>
 
</pre></code>
 
</pre></code>
which will then be rendered with a bold '''test'''.
+
 
 +
Which would then render ''test'' in bold.
  
 
===Arrays===
 
===Arrays===
  
Declaring arrays are very easy in PHP. Either you can enter all element one by one, or you can enter them together:
+
Declaring arrays is very easy in PHP. Either you can enter all elements one by one, or you can enter them together:
 
<code><pre>
 
<code><pre>
 
$student[0]="Alice";
 
$student[0]="Alice";
Line 156: Line 157:
 
$student[3]="Dan";
 
$student[3]="Dan";
 
</pre></code>
 
</pre></code>
or alternatively
+
 
 +
or alternatively
 +
 
 
<code><pre>
 
<code><pre>
 
$student=array("Alice","Bruce","Charlie","Dan");
 
$student=array("Alice","Bruce","Charlie","Dan");
 
</pre></code>
 
</pre></code>
  
Then you can access the contents with an array index
+
Then you can access the contents with an index into the array, as normal:
 
<code><pre>
 
<code><pre>
print $student[5]
+
print $student[2];
 
</pre></code>
 
</pre></code>
 
  
  
 
You can find the size of an array with ''count'' function, e.g., ''count($student)''
 
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
+
In PHP, you can also have associative arrays, which are arrays whose members can be accessible with string indices. Here is an example:
  
 
<code>
 
<code>
 
<pre>
 
<pre>
<?
+
<?php
 
$test["test1"]=1;
 
$test["test1"]=1;
 
$test["test2"]=2;
 
$test["test2"]=2;
Line 181: Line 183:
 
echo "test2=",$test[test2],"<br>";
 
echo "test2=",$test[test2],"<br>";
 
?>
 
?>
 +
</pre>
 +
</code>
  
 
You can access array keys through ''array_keys'' function.
 
You can access array keys through ''array_keys'' function.
 +
===Strings: Differences Between Java and PHP===
 +
 +
In php, unlike in java, you can enclose strings in single quotes or double quotes
 +
 +
e.g.
 +
The following is a valid string, just like in java.
 +
//A valid string in php and in java.
 +
$str="hey jeff!";
 +
 +
 +
And in PHP, the following is also a valid string
 +
//A valid string in PHP, but invalid in java.
 +
$str='hey jeff!'
 +
 +
However, there is a caveat when using the single quotes. If we want to then use MORE single quotes within the string We have to escape them
 +
To yield the string
 +
''I'm Jeff's string''
  
</pre>
+
we could use either of the following definitions:
</codE>
+
 
 +
$str="I'm Jeff's string"
 +
 
 +
OR
 +
 
 +
$str='I\'m Jeff\'s string'
 +
 
 +
Additionally, when enclosing the string in single quotes we can use unescaped double quotes inside the string in the manner shown below which is especially useful when outputting html:
 +
$str='The man said "yes."'
  
 
== Conditional Statements ==
 
== Conditional Statements ==
''if'' statements provide the conditional statements. The general format is
+
''if/elseif/else'' statements provide the conditional statements. The general format is
  if ( CONDITION ) {
+
  if ( CONDITION )
    some statements
+
{
} else {
+
  some statements
 
  }
 
  }
  You can use standard comparison operators such as ''=='',''<'',''>'' etc.
+
  elseif( ANOTHER_CONDITION )
 +
{
 +
  more statements
 +
}
 +
else
 +
{
 +
    yet more statements
 +
}
 +
 +
You can use standard comparison operators such as ''=='',''<'',''>'' etc.
  
 
  if ( $string == "this is my string") {
 
  if ( $string == "this is my string") {
Line 202: Line 240:
  
 
   if ($average_temperature>100) {
 
   if ($average_temperature>100) {
     echo "No, no, there is no such a thing called global warming!!!!";
+
     echo "No, no, there is no such thing as global warming!!!!";
 
   }
 
   }
  
 
== Loops ==
 
== Loops ==
You can use ''for'' or ''while'' loops. The formats are very similar to C.
+
PHP has ''for'' and ''while'' loops, similar to Java and C:
  
 
  for(initialization;condition;loop_increment){
 
  for(initialization;condition;loop_increment){
Line 214: Line 252:
 
  }
 
  }
  
For example, following code will print the sum of number 1 from 10.
+
For example, the following code will print the sum of numbers from 1 to 10.
 +
 
 
  <code><pre>
 
  <code><pre>
 
   $sum=0;
 
   $sum=0;
Line 226: Line 265:
 
  </pre></code>
 
  </pre></code>
  
The advantage of loops  become more obvious when you have to create a long table:
+
The advantage of loops  becomes more obvious when you have to create a long table:
  
 
<code><pre>
 
<code><pre>
 
<table border="1">
 
<table border="1">
<tr><td> Number</td><td>Square</td></tr>
+
<tr><td>Number</td><td>Square</td></tr>
 
<?
 
<?
 
for($i=0;$i<100;$i++) {
 
for($i=0;$i<100;$i++) {
Line 237: Line 276:
 
?>
 
?>
 
</table>
 
</table>
 
 
</pre></code>
 
</pre></code>
  
 
This creates a table with two columns, each row contains a number and its square.  
 
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.
+
''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.
  
 
== Functions ==
 
== Functions ==
PHP functions are identified with the keyword ''function'' followed by a function name and argument list.
+
PHP functions are identified with the keyword ''function'' followed by a function name and argument list for the function.
  
 
<code><pre>
 
<code><pre>
function name([$arg1 [= constant]],  
+
function name($arg1 [= constant], $arg2 [= constant], ...) {
                [$arg2 [= constant]], ...) {
 
 
}
 
}
 
 
</pre>
 
</pre>
 
</code>
 
</code>
 
  
 
For example  
 
For example  
  
<?  
+
<?php
function add($x,$y) {
+
  function add($x,$y) {
    return ($x+$y);
+
    return ($x+$y);
  }
+
  }
 +
  echo "Sum of 2+5=",add(2,5);  
 +
  ?>
  
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:
?>
 
if an argument has a default value, it could be specified at the argument list
 
  
  <?
+
<code><pre>
  function helloMsg($name="there") {
+
  <?php
       print "hello $name how are you today?</br>";
+
  function helloMsg($name="there") {
  }
+
       print "hello $name how are you today?<br>";
  helloMsg("Alice");
+
  }
  helloMsg();
+
  helloMsg("Alice");
 +
  helloMsg();
 
  ?>
 
  ?>
 +
</pre></code>
 +
 +
The above code will output:
 +
 +
<code><pre>
 +
hello Alice how are you today?<br>
 +
hello there how are you today?<br>
 +
</pre></code>
  
 
== Passing Variables ==
 
== 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.
+
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 the variable values in URL, the format is ''http://yourserver/yourphpfile.php?var1=value1&var2=value2.....''
+
Note that upon submitting a form, the page specified in the form tag's action attribute is loaded (with variables sent via post or get).
  
For example, the following PHP code would be used to print previous hello message according to the name received at URL:
+
===Get: Passing Variables via URL===
 +
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:
  
 
greeting.php:
 
greeting.php:
 
<code><pre>
 
<code><pre>
 
+
<?php
 
 
<?
 
 
  $person= $_GET['name'];
 
  $person= $_GET['name'];
 
  helloMsg($person);
 
  helloMsg($person);
Line 293: Line 338:
 
  }
 
  }
 
?>
 
?>
 +
</pre></code>
  
</pre>
+
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''.
  
</code>
+
===POST: Passing Variables via Form===
 +
In PHP one method for passing variables from page to page is by sending it to the other page via posting. The way post works in
 +
PHP is that PHP retrieves the variable names and values from a (slightly modified) html form and sends an those variables in the associative array named $_POST to the page specified in the FORM tag's ''action'' attribute.
  
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.
+
Note that receiving the data from a form is very similar to getting it from the URL. Consider the following form:
  
 
+
<code><pre>
 
 
Receiving the data from a form is also very similar. Consider following form:
 
<code>
 
<pre>
 
 
<FORM action="info.php" method="post">
 
<FORM action="info.php" method="post">
 
     <P>
 
     <P>
     <LABEL for="firstname">First name: </LABEL>
+
     <LABEL for="firstnamelabel">First name: </LABEL>
              <INPUT type="text" name="firstname"><BR>
+
    <INPUT type="text" name="firstname" id="firstnamelabel"><BR>
     <LABEL for="lastname">Last name: </LABEL>
+
     <LABEL for="lastnamelabel">Last name: </LABEL>
              <INPUT type="text" name="lastname"><BR>
+
    <INPUT type="text" name="lastname" id="lastnamelabel"><BR>
     <LABEL for="birthyear">Birth Year: </LABEL>
+
     <LABEL for="birthyearlabel">Birth Year: </LABEL>
              <INPUT type="text" name="birthyear"><BR>
+
    <INPUT type="text" name="birthyear" id="birthyearlabel"><BR>
 
     <INPUT type="radio" name="gender" value="Male"> Male<BR>
 
     <INPUT type="radio" name="gender" value="Male"> Male<BR>
 
     <INPUT type="radio" name="gender" value="Female"> Female<BR>
 
     <INPUT type="radio" name="gender" value="Female"> Female<BR>
     <INPUT type="submit" value="Send"> <INPUT type="reset">
+
     <INPUT type="submit" value="Send">
 +
    <INPUT type="reset">
 
     </P>
 
     </P>
</FORM>
+
</FORM>
</pre>
+
</pre></code>
</code>
 
  
This posts the form data to ''info.php''. Notice that, inputs firstname, lastname, birthyear and gender.
+
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 accessed in ''info.php'' with the $_POST array.
 +
*<label> : The label tag just provides a text label for the form inputs.
 +
*<input ''type="input_type_here"''> : The input tag provides various means of inputting information into the form, there are various types of inputs such as text, radio, submit, reset, etc.
 +
*<input ... ''name="input_name"''> :
 +
*<label ''for="identifying_string"''> and <INPUT ... ''id="identifying_string"'': The optional ''for'' attribute of the label tag associates the label with what we'll call an "identifying string", which should match the string specified in the corresponding ''id'' portion of the input tag. If both of these attributes are in place, then upon clicking on the label, the corresponding input will be selected.
  
Then we can access those variables through $_POST function in info.php
+
info.php:
 
+
<code><pre>
info.php
+
<?php
<code>
+
  echo  "Personal Data:", $_POST['firstname'], " ", $_POST['lastname'], "<br>";
<pre>
 
<?
 
  echo  "Personal Data:",$_POST['firstname'],' ', $_POST['lastname'], "<br>";
 
 
  $birthyear=$_POST['birthyear'];
 
  $birthyear=$_POST['birthyear'];
  echo  "Birth year:", $_birthyear, " (Age:",2007-$birthyear,")<br>";
+
  echo  "Birth year:", $_birthyear, " (Age:" , 2007-$birthyear, ")<br>";
 
  echo "Gender: ", $_POST['gender'];
 
  echo "Gender: ", $_POST['gender'];
 
?>
 
?>
 +
</pre></code>
  
</pre>
+
For further help with using HTML forms with PHP, we recommend [http://www.tizag.com/phpT/forms.php this tutorial]
</code>
+
 
 +
===Self-Submitting Forms===
 +
Oftentimes we don't want to pass form values to a different page, but rather to the same page as contains the form so that we can process the information and display output on that same page. The way we do this is to specify that the form should submit to $_SERVER['PHP_SELF'] and not say, other_page.php.
 +
Note that you can make self-submitting forms that use either the get or post method.
 +
 
 +
The following example simply takes the data input from a form and, via posting, echoes it back to the user as bold text on the same page:
 +
 
 +
bold_printer.php
 +
<code><pre>
 +
<html>
 +
<head><title>Bold Printer</title></head>
 +
<body>
 +
 
 +
<form action= <?php echo $_SERVER['PHP_SELF'] ?> method="post">
 +
    <label for="text_field">First name: </LABEL>
 +
    <input type="text" name="user_text" id="text_field"><BR>
 +
    <input type="submit" value="Print in Bold">
 +
</form>
 +
 
 +
<?php
 +
    if(isset($_POST['user_text']))
 +
    echo "<b>", $_POST['user_text'], "</b>";
 +
?>
 +
</pre></code>
  
 
==Session Variables==
 
==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).
+
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 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:
+
In order to access session values, in each php file, you should first initiate the session with the ''session_start()'' function call. After that, when you access a value with ''$_SESSION'', it will become a session values. For example:
  
 
setsessionvars.php
 
setsessionvars.php
<code>
+
<code><pre>
<pre>
+
<?php
<?
 
 
session_start();
 
session_start();
  
$_SESSION['SESSION']=1;
+
$_SESSION['SESSION']=42;
$_SESSION['UNAME']="burchan";
+
$_SESSION['username']="ArthurDent";
 
?>
 
?>
</pre>
+
</pre></code>
</code>
 
  
will set two variables, SESSION and UNAME to be accessible by other pages. In another page, you can access them with
+
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:
 
 
<code>
 
<pre>
 
<?
 
  
 +
<code><pre>
 +
<?php
 
session_start();
 
session_start();
if (!isset($_SESSION["SESSION"])) {
+
if (!isset($_SESSION['SESSION'])) {
 
   echo "error session is not registered";
 
   echo "error session is not registered";
  }
+
}
  else echo "Username=",$_SESSION['UNAME'];
+
else echo "username=",$_SESSION['username'];
 
?>
 
?>
</pre>
+
</pre></code>
</code>
 
  
You can also remove a session variable from the session with unset command
+
You can also remove a session variable from the session with unset command:
  
 
  unset($_SESSION['SESSION']);
 
  unset($_SESSION['SESSION']);
 +
 +
==Redirect the browser to a different page==
 +
 +
It is often useful to redirect the user's browser to a different webpage, for example, after processing inputs from a form.  Here is a simple example that shows how to do this, based on whether or not the ''LOGIN'' session variable is set:
 +
 +
<code><pre>
 +
<?php
 +
if(isset($_SESSION["LOGIN"])){
 +
Header("Location:/welcome.php");
 +
}else{
 +
Header("Location:/login.php");
 +
}
 +
?>
 +
</pre></code>
 +
 +
Note that anytime you call the ''Header'' function, it is adding information to the header section in the HTML object that is being requested.  As such, all ''Header'' calls should go before any other HTML output in the PHP script.
 +
 +
==Sending a file to the Browser==
 +
 +
Another useful function to know is the ''readfile'' function.  It takes a file on the webserver's file system and sends it to the web browser.  A simple example is given below, but note that you'll probably need to specify addition header fields in order to have the web browser download the file correctly.
 +
For those of you who have used previous versions of PHP, note that mime_content_type($path) is now deprecated, use finfo_file instead. '''IMPORTANT''' The examples presented below are susceptible to a simple injection attack and should not be used in practice for publicly accessible websites or with untrusted users.  For more information on building a secure file upload PHP script refer to the following websites: [http://www.linuxforu.com/2010/12/secure-upload-methods-in-php/ Secure PHP Uploading] [http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/ Sanitizing Input in PHP] [http://blog.triphp.com/lessons/php/filter PHP Filter] 
 +
 +
 +
<code><pre>
 +
<?php
 +
session_start();
 +
 +
$file=$_GET['file'];
 +
$name = $_SESSION["UNAME"];
 +
$path="/home/uploads/$name/$file";
 +
 +
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
 +
if (!$finfo) {
 +
echo "Opening fileinfo database failed";
 +
}
 +
 +
$mime=finfo_file($finfo, $path);
 +
finfo_close($finfo);
 +
 +
header('content-type:'. $mime);
 +
readfile($path);   
 +
?>
 +
</pre></code>
  
 
==Uploading files with PHP==
 
==Uploading files with PHP==
  
First, you should a form that contains the input type ''file''
+
This section describes one way to upload files with PHP.  First, you need an HTML form that contains an input with type ''file'':
 +
 
 
transfer.php
 
transfer.php
<code>
+
<code><pre>
<pre>
 
 
 
 
<form enctype="multipart/form-data" action="uploader.php" method="POST">
 
<form enctype="multipart/form-data" action="uploader.php" method="POST">
 
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
 
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
+
Choose a file to upload: <input name="uploadedfile" type="file" /><br>
 
<input type="submit" value="Upload File" />
 
<input type="submit" value="Upload File" />
 
</form>
 
</form>
</pre>
+
</pre></code>
</code>
 
  
 
+
When you use a ''file'' input in a form, PHP automatically adds an entry in the ''$_FILES'' array with information about the file. For example, transfer.php called the file ''uploadedfile'', so $_FILES['uploadedfile'] refers to file that the user selected in the form.  The name of the original file is $_FILES['uploadedfile']['name'].  When you upload a file, it is put in a temporary location by the web server. This temporary name is $_FILES['uploadedfile']['tmp_name']. In PHP, you can move a file from its original location to a new location by calling a built-in function, ''move_uploaded_file'', which takes an argument for the source (temporary location) and destination location. Note that relative paths in the destination location are relative to the location of the PHP script being executed.
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:
 
uploader.php:
<code>
+
<code><pre>
<pre>
 
 
$target_path = "uploads/";
 
$target_path = "uploads/";
 
+
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
 
  
 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
     echo "The file ".  basename( $_FILES['uploadedfile']['name']).
+
     echo "The file ".  basename( $_FILES['uploadedfile']['name']) . " has been uploaded";
    " has been uploaded";
 
 
} else{
 
} else{
 
     echo "There was an error uploading the file, please try again!";
 
     echo "There was an error uploading the file, please try again!";
 
}
 
}
</pre>
+
</pre></code>
</code>
 
 
 
== 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
 
 
 
=Teams for this module =
 
Team 0: Young Kook Park , Michael Frances Fahey Please use zoo.cse.wustl.edu
 
 
 
Team 1: Michael Rene , Vanetia Nikole Cannon Please use zoo.cse.wustl.edu
 
 
 
Team 2: Mark Evan Davis , Philip Jon Melzer Please use zoo.cse.wustl.edu
 
 
 
Team 3: Gail Crystal Burks , Paul Manfred Heider Please use zoo.cse.wustl.edu
 
 
 
Team 4: Benjamin Kozac , John Thomas Pizzini Please use oz.cse.wustl.edu
 
 
 
Team 5: Andrew Nemec Bort, Andrew Tateh Shaw Please use oz.cse.wustl.edu
 
  
Team 6: Adam Michael Basloe, Natalie Nikolayevna Sklobovskaya Please use oz.cse.wustl.edu
+
== Eclipse ==
  
Team 7: Jacqueline Rose Steege , Andrew David Kanyer Please use oz.cse.wustl.edu
+
For those of you who like programming with IDEs, Eclipse has support for PHP.  See:
 +
http://www.eclipse.org.
  
Team 8: Jonathan Matthew Wald , William Cannon Fargo Please use oz.cse.wustl.edu
+
[[Category:Obsolete Content]]

Latest revision as of 17:31, 24 August 2017

PHP5

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. 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/httpd/conf.d/php.conf file:

 AddType text/html .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
  PHP Code In Here
?>
<?php
  PHP Code In Here
php?>
<script language="php">
  PHP Code In Here
</script>

You may see the following shortcut syntax for declaring php, but it may not work unless the shortcut syntax is configured for your server, as such we generally recommend sticking with one of the first ways of declaring php.

<?
 PHP Code In Here
?>

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

<?php
  phpinfo();
?>

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">
 <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">
 ....

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.

<?php
  #this is an integer
  $i=5;
  #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):

<?php
  $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. 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:

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

The code that the browser will receive is then:

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

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

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

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:

 <?php 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.

Arrays

Declaring arrays is very easy in PHP. Either you can enter all elements 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 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:

<?php
$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.

Strings: Differences Between Java and PHP

In php, unlike in java, you can enclose strings in single quotes or double quotes

e.g. The following is a valid string, just like in java.

//A valid string in php and in java.
$str="hey jeff!";


And in PHP, the following is also a valid string

//A valid string in PHP, but invalid in java.
$str='hey jeff!' 

However, there is a caveat when using the single quotes. If we want to then use MORE single quotes within the string We have to escape them To yield the string I'm Jeff's string

we could use either of the following definitions:

$str="I'm Jeff's string"

OR

$str='I\'m Jeff\'s string'

Additionally, when enclosing the string in single quotes we can use unescaped double quotes inside the string in the manner shown below which is especially useful when outputting html:

$str='The man said "yes."'

Conditional Statements

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

if ( CONDITION )
{
  some statements
}
elseif( ANOTHER_CONDITION )
{
  more statements
}
else
{
   yet more statements
}

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 thing as global warming!!!!";
 }

Loops

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

for(initialization;condition;loop_increment){
}
 
while (condition){
}

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

  $sum=0;
  $i=1;
  while($i<=10) {
    $sum=$sum+$i;
    $i++;
  }
 
 echo "sum is $sum";
 

The advantage of loops becomes 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 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.

Functions

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

<?php 
  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:

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

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.

Note that upon submitting a form, the page specified in the form tag's action attribute is loaded (with variables sent via post or get).

Get: Passing Variables via URL

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:

greeting.php:

<?php
 $person= $_GET['name'];
 helloMsg($person);
 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.

POST: Passing Variables via Form

In PHP one method for passing variables from page to page is by sending it to the other page via posting. The way post works in PHP is that PHP retrieves the variable names and values from a (slightly modified) html form and sends an those variables in the associative array named $_POST to the page specified in the FORM tag's action attribute.

Note that receiving the data from a form is very similar to getting it from the URL. Consider the following form:

<FORM action="info.php" method="post">
    <P>
    <LABEL for="firstnamelabel">First name: </LABEL>
    <INPUT type="text" name="firstname" id="firstnamelabel"><BR>
    <LABEL for="lastnamelabel">Last name: </LABEL>
    <INPUT type="text" name="lastname" id="lastnamelabel"><BR>
    <LABEL for="birthyearlabel">Birth Year: </LABEL>
    <INPUT type="text" name="birthyear" id="birthyearlabel"><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, with inputs firstname, lastname, birthyear, and gender. The values passed through the form for each input can be accessed in info.php with the $_POST array.

  • <label> : The label tag just provides a text label for the form inputs.
  • <input type="input_type_here"> : The input tag provides various means of inputting information into the form, there are various types of inputs such as text, radio, submit, reset, etc.
  • <input ... name="input_name"> :
  • <label for="identifying_string"> and <INPUT ... id="identifying_string": The optional for attribute of the label tag associates the label with what we'll call an "identifying string", which should match the string specified in the corresponding id portion of the input tag. If both of these attributes are in place, then upon clicking on the label, the corresponding input will be selected.

info.php:

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

For further help with using HTML forms with PHP, we recommend this tutorial

Self-Submitting Forms

Oftentimes we don't want to pass form values to a different page, but rather to the same page as contains the form so that we can process the information and display output on that same page. The way we do this is to specify that the form should submit to $_SERVER['PHP_SELF'] and not say, other_page.php. Note that you can make self-submitting forms that use either the get or post method.

The following example simply takes the data input from a form and, via posting, echoes it back to the user as bold text on the same page:

bold_printer.php

<html>
<head><title>Bold Printer</title></head>
<body>

<form action= <?php echo $_SERVER['PHP_SELF'] ?> method="post">
    <label for="text_field">First name: </LABEL>
    <input type="text" name="user_text" id="text_field"><BR>
    <input type="submit" value="Print in Bold">
</form>

<?php
    if(isset($_POST['user_text']))
    echo "<b>", $_POST['user_text'], "</b>";
?>

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, in each php file, you should first initiate the session with the session_start() function call. After that, when you access a value with $_SESSION, it will become a session values. For example:

setsessionvars.php

<?php
session_start();

$_SESSION['SESSION']=42;
$_SESSION['username']="ArthurDent";
?>

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:

<?php
session_start();
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:

unset($_SESSION['SESSION']);

Redirect the browser to a different page

It is often useful to redirect the user's browser to a different webpage, for example, after processing inputs from a form. Here is a simple example that shows how to do this, based on whether or not the LOGIN session variable is set:

<?php
if(isset($_SESSION["LOGIN"])){
	Header("Location:/welcome.php");
}else{
	Header("Location:/login.php");
}
?>

Note that anytime you call the Header function, it is adding information to the header section in the HTML object that is being requested. As such, all Header calls should go before any other HTML output in the PHP script.

Sending a file to the Browser

Another useful function to know is the readfile function. It takes a file on the webserver's file system and sends it to the web browser. A simple example is given below, but note that you'll probably need to specify addition header fields in order to have the web browser download the file correctly. For those of you who have used previous versions of PHP, note that mime_content_type($path) is now deprecated, use finfo_file instead. IMPORTANT The examples presented below are susceptible to a simple injection attack and should not be used in practice for publicly accessible websites or with untrusted users. For more information on building a secure file upload PHP script refer to the following websites: Secure PHP Uploading Sanitizing Input in PHP PHP Filter


<?php
session_start();

$file=$_GET['file'];
$name = $_SESSION["UNAME"];
$path="/home/uploads/$name/$file";

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
if (!$finfo) {
 	echo "Opening fileinfo database failed";
}

$mime=finfo_file($finfo, $path);
finfo_close($finfo);

header('content-type:'. $mime);
readfile($path);    
?>

Uploading files with PHP

This section describes one way to upload files with PHP. First, you need an HTML form that contains an input with 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 you use a file input in a form, PHP automatically adds an entry in the $_FILES array with information about the file. For example, transfer.php called the file uploadedfile, so $_FILES['uploadedfile'] refers to file that the user selected in the form. The name of the original file is $_FILES['uploadedfile']['name']. When you upload a file, it is put in a temporary location by the web server. This temporary name is $_FILES['uploadedfile']['tmp_name']. In PHP, you can move a file from its original location to a new location by calling a built-in function, move_uploaded_file, which takes an argument for the source (temporary location) and destination location. Note that relative paths in the destination location are relative to the location of the PHP script being executed.

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

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