PHP tutorial for beginners

The PHP code starts with <?php and ends with ?>

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World! ";
?>
</body>
</html>

Declaring variables

In PHP it is not needed to declare the type of variable.

<?php

// comment
// example 1
$text = "Hello PHP";
$number = 3;

echo $text;
echo "<h4>I like PHP!</h4>";
echo "I say: $text";

// example 2
$my_string = <<<TEXT
This is example.
More text can be added.
Definiteyl!
TEXT;
echo $my_string;

# special characters
$newline = "A newline is \n <br>";
$return = "A carriage return is \r <br>";
$tab = "A tab is \t <br>";
$dollar = "A dollar sign is \$<br>";
$doublequote = "A double-quote is \"<br>";

// glue two strings into one
$string1 = "Hello ";
$string2 = "again";
echo $string1.$string2;

/*
* add two numbers and print sum
*/
$x1 = 4;
$x2 = 3;
$sum = $x1 + $x2;
echo "Sum is ".$sum;

?>

Arrays

<?php
$names = array("Jack", "Sally", "John", "Lucy");

// add some more names
$names[] = "Mark";
$names[] = "Wilma";
$names[] = "Frank";

for ($i = 0; $i < sizeof($names); $i++) {
echo $names[$i]."<br>";
}

// sort array in ascending order
sort($names);

// sort array in descending order
rsort($names);
?>

Hashtables

Hashtable is array of key-value pairs.

<?php
$person = array("name" => "Jack",
"age" => 25,
"job" => "PHP programmer");

// add some more key-value pairs
$person["bestFriend"] = "Mark";
$person["from"] = "Jupiter";

// print individual entry
echo "Name: ".$person["name"]."<br>";
echo "Age: ".$person["age"]."<br>";
echo "From: ".$person["from"]."<br>";

// print all entries
foreach ($person as $key => $value) {
echo $key." = ".$value."<br>";
}

// sort values in ascending order
asort($person);

// sort keys in ascending order
ksort($person);
?>

Conditions

Two strings are compared with ‘==’ operator. PHP is case sensitive!

<?php

$text = "php";
if ($text == "php") {
echo "php it is";
} else {
echo "oh nooo";
}

$color = "Green";
if ($color == "Blue") {
echo "I feel blue";
} elseif ($color == "Green") {
echo "I feel green";
} else {
echo "I don't feel any color";
}

$name = "John";
switch ($name){
case "Mike":
echo "Your name is Mike";
break;
case "Lucy":
echo "Lour name is Lucy";
break;
case "John":
echo "Your name is John";
break;
default:
echo "You have no name";
break;
}

?>

Loops

First create array. Arrays in PHP are key-value tables. In simple arrays you can use integers for indexing. Other type of array is associative array which is more like Hashtable.
Use different types of loops to iterate over the array: while, for, foreach and do-while loops.

<?php

// arrays
$animals[0] = "Cat";
$animals[1] = "Dog";
$animals[2] = "Monkey";
$animals[3] = "Zebra";

echo "I like ".$animals[2]."<br>";

// associative array
$size["Cat"] = 200;
$size["Dog"] = 400;
$size["Monkey"] = 600;
$size["Zebra"] = 1000;

echo "Dog has size ".$size["Dog"]."<br>";

// while
$counter = 0;
while ($counter < 4) {
echo "Animal: ".$animals[$counter]."<br>";
$counter++;
}

// for
for ( $counter = 0; $counter <= 4; $counter++) {
echo "Animal ".$counter." is: ".$animals[$counter]."<br>";
}

// foreach
foreach( $size as $a => $s) {
echo "Animal: $a, Size: $s <br>";
}

// do-while
$cookies = 0;
do {
echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);

?>

Functions

Create functions with no, one or two input parameters.

<?php

function sayHello(){
echo "Hello";
}

sayHello();


function sayGreeting($name) {
echo "Hello ". $name;
}

sayGreeting("John");


function sum($a, $b) {
$sum = $a + $b;
return $sum;
}

$result = sum(3, 4);
echo "I can add. Result is " . $result . ".";

?>

GET or POST

To transfer data from user to php script, you can choose between GET and POST methods. When using GET method all parameters from user will be sent as part of URL.
Example:

http://www.matjazcerkvenik.si/processOrder.php?item=Strawberries&quantity=3

Simple HTML form that provides input fields and calls processOrder.php script when submit button is clicked:

<html>
<body>
<h4>Order fruits</h4>
<form action="processOrder.php" method="get">
<select name="item">
<option>Apples</option>
<option>Grapes</option>
<option>Strawberries</option>
</select>
Quantity: <input name="quantity" type="text" /> kg <br><br>
<input type="submit" />
</form>
</body>
</html>

processOrder.php script:

<?php
$quantity = $_GET['quantity'];
$item = $_GET['item'];
echo "You ordered ". $quantity . " kilos of " . $item;
?>

GET method is not very convenient for sending sensitive data, such as passwords. Instead use POST method where data is sent as environmental variable, which is hidden from users view.

http://www.matjazcerkvenik.si/processOrder.php

<html>
<body>
<h4>Order fruits</h4>
<form action="processOrder.php" method="post">
<select name="item">
<option>Apples</option>
<option>Grapes</option>
<option>Strawberries</option>
</select>
Quantity: <input name="quantity" type="text" /> kg <br><br>
<input type="submit" />
</form>
</body>
</html>

processOrder.php script:

<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " kilos of " . $item;
?>

Disarm HTML entities

As a web developer, you should always think about security. Always validate the user input. A hacker could submit a maliscious code (like JavaScript), which can harm your website.

<?php
$userInput = "I am going to hax0r your site, hahaha!
<script type='text/javascript'>
window.location = 'http://www.example.com/'
</script>'";

//Lets make it safer before we use it
$userInputEntities = htmlentities($userInput);

//Now we can display it
echo $userInputEntities;
?>

Working with files

Set executable permissions to your PHP script before you creating or modifying files.

Create file

<?php
$filename = "testFile.txt";
$fileHandle = fopen($filename, 'w') or die("error: can't open file");
fclose($fileHandle);
echo $theData;
?>

Read file

<?php
$filename = "testFile.txt";
$fileHandle = fopen($filename, 'r') or die("error: can't open file");
$data = fread($fileHandle, filesize($filename));
fclose($fileHandle);
echo $data;
?>

Write to file

<?php
$filename = "testFile.txt";
$fileHandle = fopen($filename, 'w') or die("error: can't open file");
$data = "Hello PHP World!\n";
fwrite($fileHandle, $data);
fclose($fileHandle);
echo $theData;
?>

Append data

<?php
$filename = "testFile.txt";
$fileHandle = fopen($filename, 'a') or die("error: can't open file");
$newString = "New String is appended\n";
fwrite($fileHandle, $newString);
fclose($fileHandle);
?>

Working with strings

Searching string

<?php
$string = "1234567890";
echo $string."<br>";
$index = strpos($string, "5");
echo "The position of 5 is $index";
?>

Search string in loop (with offset)

<?php
$string = "1234567890123456789012345678901234567890";
$offset = 0;
$counter = 0;
echo $string."<br>";

// First check if there is a "5" at position 0.
if(strpos($string, "5") == 0){
$counter++;
echo "<br />Five #$counter is at position - 0";
}

// Check the rest of the string for 5's
while($offset = strpos($string, "5", $offset + 1)){
$counter++;
echo "<br />Five #$counter is at position - $offset";
}
?>

Replace string

<?php
$string = "I like oranges.";
echo $string."<br>";
$newstring = str_replace("oranges", "apples", $string);
echo $newstring."<br>";
?>

Changing characters case

<?php
$string = "abcdefg123 aaa";
$upperCase = strtoupper($string);
$lowerCase = strtolower($upperCase);
$ucCase = ucwords($lowerCase);
echo "Before: $string <br>";
echo "After: $upperCase <br>";
echo "Then again: $lowerCase <br>";
echo "...and: $ucCase <br>";
?>

Explode a string

<?php
$string = "This is a sentence.";

$stringArray = explode(" ", $string);

for($i = 0; $i < count($stringArray); $i++){
echo "$i = $stringArray[$i] <br>";
}

$stringArrayLimited = explode(" ", $string, 2);

for($i = 0; $i < count($stringArrayLimited); $i++){
echo "$i = $stringArrayLimited[$i] <br>";
}

?>

Implode

<?php
$colors = array("Green", "Blue,", "Red", "Cyan", "Gray");

$string = implode(", ", $colors);
for($i = 0; $i < count($colors); $i++){
echo "Color $i = $colors[$i] <br>";
}

echo "Single string: $string";
?>

Regular expressions

Using regular expressions for searching text patterns.

<?php
$string = "123ABC";

if (ereg("^[A-Za-z0-9]$", $string)) {
echo "ok";
} else {
echo "nok";
}
?>

Date

<?php
echo date("m/d/y");
?>

Customizing date

<?php
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
echo "Tomorrow is ".date("m/d/y", $tomorrow);
?>

Important Full Date and Time:

Time

  • r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")
  • a: am or pm depending on the time
  • A: AM or PM depending on the time
  • g: Hour without leading zeroes. Values are 1 through 12
  • G: Hour in 24-hour format without leading zeroes. Values are 0 through 23
  • h: Hour with leading zeroes. Values 01 through 12
  • H: Hour in 24-hour format with leading zeroes; values 00 through 23
  • i: Minute with leading zeroes. Values 00 through 59
  • s: Seconds with leading zeroes. Values 00 through 59

Day

  • d: Day of the month with leading zeroes. Values are 01 through 31
  • j: Day of the month without leading zeroes. Values 1 through 31
  • D: Day of the week abbreviations. Sun through Sat
  • l: Day of the week. Values Sunday through Saturday
  • w: Day of the week without leading zeroes. Values 0 through 6
  • z: Day of the year without leading zeroes. Values 0 through 365

Month

  • m: Month number with leading zeroes. Values 01 through 12
  • n: Month number without leading zeroes. Values 1 through 12
  • M: Abbreviation for the month. Values Jan through Dec
  • F: Normal month representation. Values January through December
  • t: The number of days in the month. Values 28 through 31

Year

  • L: 1 if it's a leap year and 0 if it isn't
  • Y: A four digit year format
  • y: A two digit year format. Values 00 through 99

Other Formats

  • U: The number of seconds since the Unix Epoch (January 1, 1970)
  • O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours

Error handling

Functions do fail. Face it. Lets say we try to write some data into file or database. If the file does not exist or the database is currently off, then you should definitely prevent further execution of the script. Example:

$fileHandle = fopen($filename, 'w') or die("error: can't open file");

'die($msg)' function stops the php script and displays the message to the user. Alternatively you can use 'exit()' function

PHP is object oriented

Create classes

<?php
class SomeClass {

private $message;

/** Constructor */
function __construct() {
}

public function setMessage($text) {
$this->message = $text;
}

public function getMessage() {
return $this->message;
}
}
?>

Make objects

<?php
// import class file
include 'someclass.php';
// instance new object
$SomeClazz = new SomeClass();
// call functions
$SomeClazz->setMessage("Hello PHP world!");
$response = $SomeClazz->getMessage();
// print result
echo $response;
?>

PHP is close friend with MySQL

Let’s say you have DB with users and their passwords. Here are example functions how to list all users in DB, create new user, authenticate user, change users password and finally delete user.

<?php
$result = getAllUsers();
while ($row = mysql_fetch_array($result)) {
echo $row["user"]." - ".$row["pass"]."<br>";
}

/**
* Get list of all DB entries (username - password).
*
* @return $query
*/
function getAllUsers() {
// get connection
$con = mysql_connect("localhost", "dbusername", "dbpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// set db name
mysql_select_db("dbName", $con);
// execute query
$query = mysql_query("SELECT * FROM users");
// close connection
mysql_close($con);
return $query;
}

/**
* Insert new user with password into DB.
*
* @param $user
* @param $pass
*/
function insertNewUser($user, $pass) {
$con = mysql_connect("localhost", "dbusername", "dbpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbName", $con);
mysql_query("INSERT INTO users (user, pass) VALUES ('".$user."', '".$pass."')");
mysql_close($con);
}

/**
* Check if username and password matches with DB entries.
*
* @param $user
* @param $pass
* @return true if user/pass matches
*/
function authenticateUser($user, $pass) {
$userAuthenticated = false;
$con = mysql_connect("localhost", "dbusername", "dbpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM users WHERE user='".$user."'");
while($row = mysql_fetch_array($result)) {
if ($row['user'] == $user && $row['pass'] == $pass) {
$userAuthenticated = true;
break;
}
}
mysql_close($con);
return $userAuthenticated;
}

/**
* Change users password.
*
* @param $user
* @param $pass
*/
function changePassword($user, $pass) {
$con = mysql_connect("localhost", "dbusername", "dbpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbName", $con);
mysql_query("UPDATE users SET pass='".$pass."' WHERE user='".$user."'");
mysql_close($con);
}

/**
* Delete user from DB.
*
* @param $user
*/
function deleteUser($user) {
$con = mysql_connect("localhost", "dbusername", "dbpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbName", $con);
mysql_query("DELETE FROM users WHERE user='$user'");
mysql_close($con);
}
?>

PHP & AJAX

While PHP is processing requests on the server side, JavaScript is processing requests on the user side inside web browser. Combination of both makes perfect AJAX technology. Benefit of AJAX technology is that only a fragment of web page can be reloaded, rather than whole page.

PHP & JSON

JSON is lightweight interchange data format, an alternative to XML. JSON is well supported by PHP - there are methods for encoding and decoding JSON formated data.

Here is a tutorial showing JSON in action. The server is written in PHP and responds to requests sent from Java application (client).

JSON in Java