PHP
PHP is an open-source language used widely for writing server-side code for web servers. PHP is a good starting point for web developers, as it is straightforward to learn and yet powerful at the same time. Indeed, some of the internet's most popular web sites are written using PHP as their language of choice! This article introduces the syntax of PHP and how to make a basis PHP web application.
Contents
Why use a server-side scripting language?
Server-side scripting languages like PHP are what turn your web site from a static fileserver to a dynamic web application.
By default, Apache only knows how to serve static HTML pages to the client. You can write as many HTML pages as you want, which is fine for basic web sites. But if you want to have users post to a forum, or process credit card transactions, or make your own online calendar, a server-side language like PHP is what you need.
Installing PHP
To install PHP, you need both the PHP interpreter and the Apache module that runs PHP code. In yum, the package name is php; in Debian, there are two packages: php5 and libapache2-mod-php5.
Once you install the required packages, restart Apache for the changes to take effect.
PHP Configurations
The PHP configuration file is called php.ini. In RHEL, it is located at /etc/php.ini; in Debian, it is located at /etc/php5/apache2/php.ini.
The configuration file is largely self-documenting as to what the different options mean. There is one value in particular that we want to change for the purposes of CSE330. Open php.ini in your favorite text editor, find the display_errors option, and set it to On:
display_errors = On
You will need to restart Apache for any php.ini changes to take effect.
Your First PHP Script
By default, all files that have the *.php extension will be interpreted as containing PHP code. Here is the most basic PHP script:
<?php
phpinfo();
?>
Save that code into a file named phpinfo.php, and save it in your web server directory. Load it up in your browser like this: http://ec2-blah-blah.compute-1.amazonaws.com/phpinfo.php
If you see something like this, your PHP installation is working!
Look at the source code of that page. Notice that even though there were only three lines of code in our PHP file, PHP filled it up with hundreds of lines of HTML!
Your own PHP scripts will probably look something more like this:
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<?php
echo "\t<p>Hello World!</p>\n";
?>
</body>
</html>
The above code will send the following HTML to the browser:
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Here's the take-home message of this section. To run PHP code, enclose it in <?php ?>
tags; HTML code can be used in a PHP file (although not inside the PHP code block!); and just a few lines of code can generate an arbitrary amount of HTML.
PHP Language Components
PHP is a programming language much like others you have learned: it has variables, arrays, functions, objects etc. However, the syntax for PHP and the way PHP handles variables may be new to you. This section gives an overview of PHP the language.
Variables
All variables start with the currency $ symbol. The $ is necessary for both setting and accessing.
PHP is a weak-typed language; that is, you can set any type of value to a variable (string, array, number, etc), and PHP will accept it, even if that variable previously contained a different data type. In some ways this is convenient, but in others it can lead to hard-to-detect bugs, so be careful.
<?php
$i = 5; # Set the integer 5 to the variable $i
$msg = "Hello World"; # Set the string Hello World to the variable $msg
?>
Notice that all lines in PHP necessarily end with a semicolon. If you forget a semicolon, the PHP will fail to parse!
Outputting Data
What's the point of a web language if we can't output data? The most basic method for outputting data is using either the echo or print statement:
<?php
echo "Hello World"; # outputs Hello World to the browser
?>
You often find yourself wanting to print all information associated with a variable for debugging purposes. PHP provides the handy var_dump function for that:
<?php
var_dump($myvar);
?>
Strings
Strings in PHP can be either single-quoted or double-quoted. Single-quoted strings are always taken literally; double-quoted strings allow for additional elements.
<?php
$a = "Apple";
$b = "Banana";
$fruits_double = "$a\n$b"; # $fruits_double now contains the string Apple (line break) Banana
$fruits_single = '$a\n$b'; # $fruits_single now contains the string $a\n$b
?>
If you want to use special characters in a double-quoted strings, escape them using the backslash operator:
<?php
$a = "Apple";
$b = "Banana";
$fruits = "\$a\\n$b"; # $fruits now contains the string $a\nBanana
?>
You can concatenate multiple strings together using the concatenation operator, which in php is a period:
<?php
$c = "Cherry";
$g = "Grapefruit";
$fruits = $c."\n".$g; # $fruits contains the string Cherry (line break) Grapefruit
?>
Arrays
Declaring arrays is very simple in PHP.
<?php
$fruits = array("Apple", "Banana", "Cherry", "Grapefruit"); # $arr now contains an array with 4 items
echo $fruits[1]; # displays Banana
echo count($fruits); # displays 4
array_shift($fruits); # remove the first element of the array
echo $fruits[1]; # displays Cherry
echo count($fruits); # displays 3
?>
PHP also supports associative arrays. Associative arrays are arrays whose keys are strings rather than numbers; in some languages, they are called Dictionaries.
<?php
$fruits["a"] = "Apple";
$fruits["b"] = "Banana";
$fruits["c"] = "Cherry";
$fruits["g"] = "Grapefruit";
echo $fruits["b"]; # displays Cherry
$keys = array_keys($fruits); # get an array containing indexed values of the fruits' keys
echo $keys[3]; # displays g
?>
Conditional Statements
Conditional statements work similarly to how they do in other languages.
<?php
$grade = 85;
if ($grade < 60) {
echo "F";
} elseif ($grade < 70) {
echo "D";
} elseif ($grade < 80) {
echo "C";
} elseif ($grade < 90) {
echo "B";
} else {
echo "A";
}
?>
PHP also supports switch statements, which are convenient for simplifying long if/elseid/else blocks:
<?php
$food = "Apple";
switch ($food) {
case "Apple":
case "Banana":
case "Cherry":
case "Grapefruit":
echo "You must like fruit!";
break;
case "Broccoli":
case "Spinach":
echo "You must like vegetables!";
break;
default:
echo "You don't like fruits or vegetables!";
break;
}
?>
Loops
PHP supports several different kinds of loops, including while, for, and foreach:
<?php
$mystring = "";
$i = 0;
while ($i < 5) {
$mystring .= "Blah";
}
echo $mystring; # displays BlahBlahBlahBlahBlah
$myarray = array("Apple", "Banana", "Cherry", "Grapefruit");
# The following two loops are functionally equivalent.
$mystring = "";
for($i=0; $i<count($myarray); $i++){
$mystring .= $i.": ".$myarray[$i].", ";
}
echo $mystring; # displays 0: Apple, 1: Banana, 2: Cherry, 3: Grapefruit
$mystring = "";
foreach($myarray as $key => $value){
$mystring .= $key.": ".$value;
}
echo $mystring; #displays 0: Apple, 1: Banana, 2: Cherry, 3: Grapefruit
?>
Functions
Just like with all modern programming languages, you can define your own functions with PHP.
<?php
function add($x, $y){
return $x + $y;
}
echo add(3, 5); # displays 8
?>
A neat shortcut for PHP is that you can specify default parameter values directly in the argument list:
<?php
function sayHello($name="John Doe"){
return "Hello, $name... how do you do?";
}
echo sayHello("Todd"); # displays Hello, Todd... how do you do?
echo sayHello(); # displays Hello, John Doe... how do you do?
?>
Object-Oriented Programming
PHP5 supports object-oriented programming, and many new libraries come as classes rather than simple functions. Here is an example class definition:
<?php
class Food {
protected $name;
function __construct($name){
$this->name = $name;
}
static function getDefinition(){
return "Food is nourishment for carbon-based lifeforms.";
}
function getName(){
return $this->name;
}
}
class Fruit extends Food {
function getName(){
return $this->name." (fruit)";
}
}
$fruit = new Fruit("Cherry");
echo $fruit->getName(); # displays Cherry (fruit)
echo Fruit::getDefinition(); # displays Food is nourishment for carbon-based lifeforms.
?>
Things to notice:
- All methods in a class must be preceded by the function keyword.
- Static methods require the static keyword
- Instance methods can refer to the current instance through the implicit variable $this
- To access properties and methods from an instance, use an arrow: $instance->property
- To access static properties and methods from a class, use two colons: Class::StaticProperty
- Instances of classes are defined using the syntax $instance = new Class(); like in Java
PHP Reference
If you ever have a question about PHP, first check the well-written documentation. To skip immediately to the documentation on any function, simply visit http://php.net/functionname. For example: http://php.net/var_dump