Chapter 1 - PHP Basics
Chapter 1 - PHP Basics
Chapter 1 - PHP Basics
Chapter 1
Objective of the chapter
What is PHP?
Features of PHP
Setting up PHP with apache
Basic PHP syntax
PHP comments
Predefined and user variables
Variable types in PHP
Retrieve data from html forms
Displaying errors
Using numbers and strings in PHP
Control structures
Conditional and loop statements
Introducing References
References and arrays
Functions
Function reuse
passing arguments by Reference
Functions : returning by Reference
Prerequisites:
basic understanding of computer programming,
Internet, Database
Tools
WAMP
PHP
MySQL
Apache
Macromedia Dreamweaver
Browser
What is PHP?
PHP is a popular high-level scripting language used by a range of
organizations and developers.
Originally developed as a small Perl project by Rasmus Lerdorf in late
1995, PHP was intended as a means to assist in developing his home
page, and as such he named it Personal Home Page (PHP) Tools.
When Lerdorf was contracted to work for the University of Toronto to
build a dial-up system for students to access the Internet, he had no
means of connecting Web sites to databases. To solve this problem, the
enterprising Lerdorf replaced his Perl code with a C wrapper that added
the capability to connect his Web pages to a MySQL database.
As his small project grew, he gave away his changes on the Internet as
an Open Source project and cordially received improvements from other
programmers with an interest in PHP.
The language was later renamed to the current recursive acronym PHP:
Hypertext Preprocessor by Zeev Suraski and Andi Gutmans after they
rewrote the parser in 1997.
The software continued to develop and now forms the comprehensive
PHP platform we know today.
Introduction
PHP is an acronym for "PHP: Hypertext Preprocessor“
PHP is a robust, server-side, open source scripting
language
PHP is cross platform
PHP is a server side scripting language that is embedded
in HTML
It is used to manage dynamic content, databases, session
tracking, even build entire e-commerce sites
PHP provides a solid and well-defined programming
language that includes support for
object-orientated programming,
conditions,
file handling,
arithmetic, and more
Introduction
It is integrated with a number of popular
databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL
Server
PHP supports a large number of major
protocols
PHP4 added support for Java and distributed
object architectures (COM and CORBA),
making n-tier development a possibility
PHP Syntax is C-Like
Introduction….
Common uses of PHP
PHP performs system functions, i.e. it can
create, open, read, write, and close from files
on a system
PHP can handle forms, i.e.
gather data from files, save data to a file, send
data through email, and return data to the user
PHP allows to add, delete, modify elements
within your database
Access cookies variables and set cookies
restrict users to access some pages of your
website
Introduction….
What is a PHP File?
PHP files may contain text, HTML tags and
scripts
PHP files are returned to the browser as plain
HTML
PHP files have a file extension of ".php"
Introduction
Why PHP?
PHP runs on different platforms (Windows,
Linux, Unix, etc.)
PHP is compatible with almost all servers
used today (Apache, IIS, etc.)
PHP is FREE to download from the official
PHP resource: www.php.net
PHP is easy to learn and runs efficiently on
the server side
PHP Environment Setup
In order to develop and run PHP Web pages three
vital components need to be installed on your
computer system.
Web Server - PHP will work with virtually all Web
Server software, including Microsoft's Internet
Information Server (IIS) but then most often used is
freely available Apache Server.
Database - PHP will work with virtually all database
software, including Oracle and Sybase but most
commonly used is freely available MySQL database.
PHP Parser - In order to process PHP script
instructions a parser must be installed to generate
HTML output that can be sent to the Web Browser.
Where to Start?
To get access to a web server with PHP support, you can:
Install Apache (or IIS) on your own server, install PHP, and
MySQL
Or find a web hosting plan with PHP and MySQL support
___________________________________________________________
_________________
Install an Apache server
Install PHP
Install MySQL
________________________________________________________________
___________________
WampServer
EasyPhp
XAMPP
Dynamic webpage request response procedure
Request/ response …. Con’t…
1. You enter http://server.com into your
browser’s address bar.
2. Your browser looks up the IP address for
server.com.
3. Your browser issues a request to that address
for the web server’s home page.
4. The request crosses the Internet and arrives
at the server.com web server.
5. The web server, having received the request,
fetches the home page from its hard disk.
6. With the home page now in memory, the web
server notices that it is a file incorporating PHP
Request/ response …. Con’t…
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements,
which the PHP interpreter now passes to the
MySQL database engine.
9. The MySQL database returns the results of the
statements back to the PHP interpreter.
10. The PHP interpreter returns the results of the
executed PHP code, along with the results from
the MySQL database, to the web server.
11. The web server returns the page to the
requesting client, which displays it.
PHP – Language Basics
A PHP script always
starts with <?php and
ends with ?>
A PHP script can be placed anywhere in
the document.
Syntax
PHP code should enclosed within:
<?php and ?> So that it is distinguished
from HTML.
Hence, the PHP parser only parses code
which is in between <?php and ?>
Language Basics (cont’d)…
A PHP file normally contains HTML tags, and some
PHP scripting code.
Below, we have an example of a simple PHP script
that sends the text "Hello World" back to the browser:
<html>
<body>
<?php echo "Hello
World"; ?>
</body>
</html>
Each code line in PHP must end with a semicolon.
The semicolon is a separator and is used to
distinguish one set of instructions from another.
Language Basics (cont’d)…
A more complex example:
$var_name = value;
Example
<?php
$txt = "Hello World!";
$number = 16;
?>
Variable Naming Rules
A variable name must start with a letter or
an underscore "_"
A variable name can only contain alpha-
numeric characters and underscores (a-Z, 0-
9, and _ )
A variable name should not contain spaces.
If a variable name is more than one word,
separated with underscore ($my_string), or
capitalization ($myString)
Data types
Boolean (bool or boolean)
Simplest of all
Can be either TRUE or FALSE
Integer (int or integer)
Hold integer values (signed or unsigned)
Floating point (float or double or real)
Hold floating point values
String (string)
Hold strings of characters within either ‘ or ‘’
Escaping of special characters can be done using \
Ex. “this is a string”, ‘this is another string’,
“yet \”another\” one”
Data types (cont’d)
Array
Collection of values of the same data type
Object
Instance of a class
Resource
Hold a reference to an external resource created by
some functions
NULL
Represents that a variable has no value
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
Type Casting
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
String in PHP
variable is used to store and
manipulate text.
<?php
$txt="Hello World";
echo $txt;
?>
String…
The concatenation operator (.) is used to put
two string values together
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
The strlen() function is used to find the length
of a string.
<?php
echo strlen("Hello world!");
?>
String….
The strpos() function is used to search for a
string or character within a string
<?php
echo strpos("Hello world!","world");
?>
Arithmetic operator
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division 5%2 1
remainder) 10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment operator
Opera
Example Is The Same As
tor
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Comparison operator
Operato
Description Example
r
== is equal to 5==8 returns false
Example:
…
<?php
$year = (int)date( “Y”);
echo ( $year % 4 == 0 ) ? “Leap Year” : “Not Leap
Year”;
?>
…
Control structures (cont’d)
Switch
switch ( expression ){
case value 1:
statements
break;
…
case value n:
statements
break;
default:
statements
}
Switch…
<?php
$x=2;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
Control structures (cont’d)
Looping constructs
while - loops through a block of code if and
as long as a specified condition is true
do...while - loops through a block of code
once, and then repeats the loop as long as a
special condition is true
for - loops through a block of code a specified
number of times
foreach - loops through a block of code for
each element in an array
Control structures (cont’d)…
for loop
for( initialization; condition; increment ){
loop body
<html>
}
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
Control structures (cont’d)…
foreach loop <html>
<body>
foreach( array as [key=>]value ){
<?php
loop body $x=array("one","two","thr
} ee");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Example
…
$arr = array(“name”=>”Abebe”, “dept”=>”CS”,
“year”=>3, “cgpa”=>3.5);
foreach( $arr as $key=>$value ){
echo $key . “ = “ . $value . “<br>”;
}
//output
name = Abebe
dept = CS
year = 3
cgpa = 3.5
Control structures (cont’d)
While loop <html>
<body>
while( condition ){
<?php
loop body $i=1;
} while($i<=5)
{
echo "The number is " . $i .
"<br />";
$i++;
}
?>
</body>
</html>
do….while
Do-while loop <html>
do{ <body>
loop body <?php
$i=0;
}while( condition );
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
</html>
Control structures (cont’d)
break
ends execution of the current for, foreach,
while, do-while or switch structure.
accepts an optional numeric argument
which tells it how many nested enclosing
structures are to be broken out of.
continue
used within looping structures to skip the
rest of the current loop iteration
execution continues at the condition
evaluation and then the beginning of the
next iteration
Control structures (cont’d)
return
If called from within a function, the
return statement immediately ends
execution of the current function, and
returns its argument as the value of the
function call
If return is called from within the main
script file, then script execution ends.
Form and php
PHP Forms and User Input
The PHP $_GET and $_POST variables are used
to retrieve information from forms, like user
input.
PHP Form Handling
The most important thing to notice when
dealing with HTML forms and PHP is that any
form element in an HTML page will
automatically be available to your PHP
scripts.
Form….
<html>
<body>
Welcome <?php echo $_POST[‘name’]; ?>.<br
You are <?php echo $_POST[‘age’]; ?> years o
</body>
</html>
Form …. GET method
<form action=“register.php"
method="get">
salary: <input type="text"
name=“salary" />
<input type="submit" />
</form>
<?php
function Sum($x, $z)
{
echo “the sum is= ”. $x+$z<br />";
}
?>
<h1>add two numbers</h1>
<?php
Sum(4,6);// calling the function
?>
</body>
</html>
Example 2: passing value to function
<?php
<?php
function createTable($data)
$sampleArray = array("mango",
{
"banana",
echo "<table border=\"1\">";
"orange");
reset($data);
createTable($sampleArray);
$value=current($data);
?>
while($value){
Passing argument to function
echo "<tr><td>".$value."</td></tr>\n";
$value=next($data);
}
echo "</tabel>";
}
Output
?>
Reading assignment
Read the following concepts in PHP
Passing by value
Passing by reference
Recursive function
Namespaces
Question