PHP Notes 01
PHP Notes 01
PHP Tutorial
Compiled by: Halil zmen (parts were written by Stig Sther Bakken //www.zend.com/zend/art/intro.php)
CONTENTS
What is PHP?......................................................................................................................................................1
Language Syntax................................................................................................................................................2
Embedding PHP Code......................................................................................................................................2
Dynamic vs. Static Web pages..........................................................................................................................2
Variables...........................................................................................................................................................2
Strings...............................................................................................................................................................3
Arrays................................................................................................................................................................3
Conditionals and Looping Constructs................................................................................................................4
Array Traverse Constructs:...............................................................................................................................4
Operators..........................................................................................................................................................4
Functions...........................................................................................................................................................5
File System Functions:.......................................................................................................................................6
Web Application Features..................................................................................................................................6
Working With Cookies.......................................................................................................................................6
Built-in Variables...............................................................................................................................................7
PHP internal variables...................................................................................................................................7
CGI / Web server provided variables.............................................................................................................7
HTTP Request Variables...............................................................................................................................7
Regular Expressions..........................................................................................................................................8
Regular Expression Functions in PHP..............................................................................................................8
Database Handling..............................................................................................................................................9
Communication with MySQL.............................................................................................................................9
MySQL Example...............................................................................................................................................9
Communication with Other Databases............................................................................................................10
What is PHP?
PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose
scripting language that is especially suited for Web development and can be embedded into HTML.
PHP Tutorial
Language Syntax
Most of PHP's syntax is borrowed from C, although there are elements borrowed from Perl, C++ and Java as
well. This article assumes that you are familiar with C's syntax. However, don't panic if you're not.
Variables
In PHP, a variable does not require formal declaration. It will automatically be declared when a value is
assigned to it. Variables are prefixed by a dollar sign: ($VariableName).
Variables do not have declared types. A variable's type does not have to be fixed, meaning it can be changed
over the variable's lifetime. The table below list's PHP's variable types:
Type
Description
Integer
integer number
Double
floating point number
bool1
Boolean (true or false), available from PHP 4.0
Array
hybrid of ordered array and associative array
object2
an object with properties and methods (not discussed in this article)
PHP Notes
PHP Tutorial
In the following example, four variables are automatically declared by assigning a value to them:
<?php
$number = 5;
$string1 = "this is a string\n";
$string2 = 'this is another "string"';
$real = 37.2;
?>
Strings
The string constants may be enclosed between double-quotes ( " ) or single-quotes ( ' ).
In a double-quote enclosed string, the variable conversion is done automatically.
$city = "Ankara";
print "I live in $city.";
$height = 182;
print "I am $height cm tall.";
String operators:
Concatenation: .
Concatenation to the end:
$str1 = $lastname . ", " . $firstname;
$str2 .= $str3;
.=
Arrays
PHP supports two type of arrays:
Numerically indexed arrays
Associative arrays.
Associative Arrays
Associative arrays has two part: keys and values. The keys are indices of the array.
Both the keys and values can be of any data type in the same array.
=> operator is used to combine the key and the value of an element of an associative array.
Creation of associative arrays:
keys
values
$as1 = array(24 => "Ali", "Ankara" => 844, "Pi" => 3.14159);
24
"Ali"
$as2 = array(20458444 => "Ali Ak", 20487542 => "Ayse Bal");
"Ankara"
844
Accessing array contents:
"Pi"
3.14159
print $as1["Ankara"]; // outputs: 844
$as1[24] = "Ayse";
// value of element with key=24 is changed.
$as2[20608888] = "Fatma Girik"; // a new element is added to array.
foreach ($as2 as $id => $name)
{ print "<b>$id</b>: $name<br />"; }
// all keys and values are used
foreach ($as4 as $k => $v)
{ $as4[$k] = $v + 7; }
// all values of array $as4 are increased by 7
PHP Notes
PHP Tutorial
$c = test_something();
} while ($c);
Operators
Assignment operators:
+=
-=
*=
/=
.= (string concatenation)
Arithmetic Operators
Example
$a + $b
$a - $b
$a * $b
$a / $b
$a % $b
Name
Addition
Subtraction
Multiplication
Division
Modulus
Result
Sum of $a and $b.
Difference of $a and $b.
Product of $a and $b.
Quotient of $a and $b.
Remainder of $a divided by $b.
Incrementing/Decrementing Operators
Example
++$a
$a++
--$a
$a-PHP Notes
Name
Pre-increment
Post-increment
Pre-decrement
Post-decrement
Effect
Increments $a by one, then returns $a.
Returns $a, then increments $a by one.
Decrements $a by one, then returns $a.
Returns $a, then decrements $a by one.
4
PHP Tutorial
Comparison Operators
Example
$a == $b
$a != $b
$a <> $b
$a < $b
$a <= $b
$a > $b
$a >= $b
$a === $b
Name
Equal
Not equal
Not equal
Less than
Less than or equal to
Greater than
Greater than or equal to
Identical
$a !== $b
Not identical
Result
TRUE if $a is equal to $b.
TRUE if $a is not equal to $b.
TRUE if $a is not equal to $b.
TRUE if $a is strictly less than $b.
TRUE if $a is less than or equal to $b.
TRUE if $a is strictly greater than $b.
TRUE if $a is greater than or equal to $b.
TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only)
TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4
only)
Logical Operators
Example
Name
Result
$a && $b
And
$a and $b
And
$a || $b
Or
$a or $b
Or
! $a
Not
$a xor $b
Xor
String operators:
Concatenation: .
Concatenation to the end:
$str1 = $lastname . ", " . $firstname;
$str2 .= $str3;
.=
Functions
Function declaration:
function my_func ()
{
print "Hello Ankara!";
} // end function my_func
PHP Notes
PHP Tutorial
Close File
fclose ($fp);
Delete a file
unlink ('filename');
See http://www.php.net/manual/en/ref.filesystem.php
submit.php
<?php
print "Hello, $myname!";
?>
PHP Tutorial
<html>
....
_A_;
....
?>
The following example displays all the cookies releated with the visited site:
<?php
if (!$_COOKIE) { $_COOKIE = $HTTP_COOKIE_VARS; }
foreach ($_COOKIE as $ck => $val)
{ print "<dd>Cookie name: $ck; value: $val<br />\n";
?>
Examples:
Webmail: store and use username.
Weather Site: store the selected city in a cookie, and next time the site is visited, the weather of the
stored city is automatically displayed.
Built-in Variables
PHP has a number of built-in variables that give you access to your Web server's CGI environment,
form/cookie data and PHP internals. Here are some of the most useful variables:
PHP Notes
PHP Tutorial
Regular Expressions
Regular expressions, a powerful tool for manipulating text and data, are found in scripting languages, editors,
programming environments, and specialized tools.
Special characters:
"/"
Equivalent
/abc/
/[akt]/
/[^akt]/
/[0-4]/
/.../i
*
+
\d
\D
\w
\W
\s
\S
\b
\r
\f
\n
\t
/^.../
/...$/
/\d{4}/
/\d{2,4}/
(...)
/[01234]/
[0-9]
[0-9A-Za-z_]
[ \r\t\n\f]
"-"
"^"
"."
"\"
"^"
"$"
"*"
"+"
Description or Meaning
search for substring "abc"
search for one of "a", "k" or "t".
true if string do not have any one of "a", "k" or "t".
search for one of "0", "1", "2", "3" or "4"
Case insensitive
Zero or more
One or more
Any decimal digit
[0123456789]
Any character that is not a decimal digit
Alphanumerics and underscore
Any "non-word" character
Any Whitespace character
Any character that is not a whitespace character
At word boundary (at the beginning or end)
Return (CR)
Linefeed (LF)
New line (CRLF)
Tab
Starts with
Ends with
4 digits
/\d\d\d\d/
2 to 4 digits
Grouping
"("
")"
Examples
/abck*pqr/
/abck+pqr/
/^klm/
/ali$/
/^good$/i
/[A-Z]{3}\d{3}/
/\d{2} [A-Z]{1,3} \d{2,4}/
Examples:
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice."))
{ print "A match was found."; }
else
{ print "A match was not found."; }
// The \b in the pattern indicates a word boundary, so only the distinct
// word "web" is matched, and not a word partial like "webbing" or "cobweb"
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice."))
{ print "A match was found."; }
else
{ print "A match was not found."; }
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of
choice."))
{ print "A match was found."; }
else
{ print "A match was not found."; }
preg_replace:
Examples:
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
print preg_replace($pattern, $replacement, $string);
PHP Notes
// April1,2003
PHP Tutorial
Database Handling
Communication with MySQL
PHP and MySQL are often referred to as the "dynamic duo" of dynamic Web scripting. PHP and MySQL work
very well together, in addition to the speed and features of each individual tool.
MySQL Example
The following is a simple example of how to dump the contents of a MySQL table using PHP. The example
assumes you have a MySQL user called "db_user" who can connect with password "my_password" from
localhost. In the example below, PHP implements the following procedure:
<?php
// Connect and select database:
$dblink = mysql_connect("localhost", "db_user", "my_password")
or die("Could not connect");
mysql_select_db("my_db") or die("Can not select database");
// Perform SQL query:
$query = "select * from user";
$qno = mysql_query($query)
or die("Query failed: $query<hr />" . mysql_error();
$n = mysql_num_rows ($qno);
PHP Tutorial
reset($user);
// Rewind for the next foreach
foreach ($fields as $field)
{ print " <th>$field</th>\n"; }
print " </tr>\n";
$header_printed = true;
} // end of print header.
// Output data in the record retrieved.
print "\t<tr>\n";
foreach ($user as $col_value)
{
print "\t\t<td>$col_value</td>\n";
}
print "\t</tr>\n";
}
print "</table>\n";
mysql_free_result($qno);
mysql_close($dblink);
?>
// Free resultset.
// Close connection.
PHP Notes
10