Chapter 1 - PHP Basics

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

Basics of PHP

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:

<?php if ($expression) { ?>


<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>
Language Basics (cont’d)…
 Comments in PHP
 In PHP, we use // to make a one-line comment
or /* and */ to make a comment block:
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
Variables in PHP
 Variables are used for storing values, such as
numbers, strings or function results, so that they
can be used many times in a script.
 Variables are used for storing a values, like text
strings, numbers or arrays.
 When a variable is set it can be used over and over
again in your script
 All variables in PHP start with a $ sign symbol.

Variables …
Declaring PHP variable (loosely typed)
 Syntax

$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

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal 5>=8 returns false


to
<= is less than or equal to 5<=8 returns true
Logical operators
Opera Descri
Example
tor ption
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
Control structures
 Conditional constructs
 If … else if ( condition1 )
{
statements
}elseif ( coditon2 )
{
statements
}
elseif( condition3 )
{

}else{
statements
}
Control structures (cont’d)
 Conditional statement
( condition ) ? True_value : False_value

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>

Welcome <?php echo $_GET[‘name’]; ?>.<br />


You are <?php echo $_GET[‘age’]; ?> years old!
String Manipulation And
Regular Expression
Formatting Strings
Trimming Strings:
trim() - strips whitespace from the start and end of a string
trim(str, ‘listChars’) – strips listChars from end/end
str
 Only the end will be cut if both start and end matches listchars
rtrim() – strips whitespace from end of a string
ltrim() – strips whitespace from start of a string
Formatting Strings for printing:
nl2br() – converts newlines (\n) to <br> html tag
print() – same as echo, but it can format a string
$total = 12.4;
printf(“Total = %.2f”, $total); //prints 12.40
Formatting Strings
Change cases:
strtoupper(str) – returns upper case of str
strtolower(str) – returns lower case of str
ucfirst(str) – returns str with first letter in
upper case
ucwords() – returns str with first letter in
each word in upper case
Formatting Strings for Storage – store
in DB:
addslashes() – adds escape character (\)
stripslashes() – removes escape character
 magic_quotes_gpc - is configured to add/remove
slashes automatically
Formatting Strings
Joining and Splitting Strings:
explode(separator, str) – returns an array of strings
by breaking str using separator
 $address=explode(‘@’, info@haramaya.edu.et)
returns an array containing “info” and “haramaya.edu.et”
implode() – does the opposite of explode(), joins
elements of an array using a string glue
 Implode(“@”, $address) returns info@haramaya.edu.et
join() – same as implode()
stroke() – returns a single fragment of the string
using the separator.
 Can take multiple separators
$token = stroke($str, “ .,;”);
while($token!=“ “){
echo$token;
$token = stroke($str, “ .,;”);
}
Formatting Strings
Joining and Splitting Strings:
string substr(string str, int start , int length )
– returns a substring starting from start
index to the last or the given length.
Comparing Strings:
int strcmp(string str1, string str2) – returns:
0 if they are equal, 1 if str1 is greater than
str2, less than 0 if str1 less than str2
 It is case sensitive
strcasecmp() – identical to strcmp() but it is
not case sensitive
Formatting Strings
Testing String Length:
int strlen(string str) – takes a string and
returns the number of characters
Finding Strings in Strings:
string strstr(string haystack, string needle) -
If an exact match of the needle is found,
the function returns the haystack from the
needle onward; otherwise, it returns false
 If the needle occurs more than once, the returned string
will start from the first occurrence of needle.
stristr() - identical but is not case sensitive
strrchr() – which is again nearly identical,
but returns the haystack from the last
occurrence of the needle onward.
Formatting Strings
Finding the Position of a Substring:
int strpos(string haystack, string needle, int
[offset] ) – returns the position of the first
occurrence of the needle within haystack
 Starts searching at offset
$test = ‘Hello world’;
strpos($test, ‘o’); - returns 4
strpos($test, ‘o’, 5); - returns 7
strrpos() – identical but returns the last
occurrence
 In both case, if the string is not available they return
false
Formatting Strings
Replacing Substrings:
mixed str_replace(mixed needle, mixed
new_needle, mixed haystack [,int count])) -
replaces all the instances of needle in haystack
with new_needle and returns the new version of
the haystack
 The optional fourth parameter, count, contains the
number of replacements made
string substr_replace(string string, string
replacement,int start, int [length] ) -
replaces part of the string string with the string
replacement. Which part is replaced depends on
the values of the start and optional length
Arrays and functions

Chapter 4- basics of PHP


Array
 An array is a special variable, that can store a
set or sequential value

 In PHP, there are three kind of arrays:


 Numeric array - An array with a numeric index
 Associative array - An array where each ID key
is associated with a value
 Multidimensional array - An array containing
one or more arrays
Numerically indexed array
 stores each array element with a numeric
index.
 Initializing
$product =array(“tires”, ”oil”, ”mirror”);
or
$product[0]=“tires”;
$product[1]= ”oil”;
$product[2]=”mirror”;
 Loop access
for($i=0; i<3; i++)
echo $product[i];
Associative array
 each ID key or index is associated with a value
 we can use values as keys and assign values to
them
 Initializing

$price =array(“tires”=>100, ”oil”=>10,


”mirror”=>50);
or
$price =array(“tires”=>100);
$price[ ”oil”]=10;
$price[ ”mirror”]=50;
 Accessing array elements

echo $price[ ”oil”];


Accessing array elements
foreach($price as $key => $value){
echo $key . “-”. $value. “<br>”;
}
while($element = each($price)){
echo $element[key];
echo “-”;
echo $element[value];
echo “<br>”
}
while(list( $product, $price)= each($price)){
echo “$product - $price <br>”;
}
Array operators
Multidimensional array
 each element in the main array can also
be an array
Code Description Price
TIR tires 100
OIL Oil 10
MIR Mirror 50
$product =array( array( ‘code’ =>’TIR’
description=>’tires’
price=>’100’),
array( ‘code’ =>’OIL’
description=>’oil’
price=>’10’),
array( ‘code’ =>’MIR’
description=>’mirror’
price=>’50’)
);
Accessing element of MD array
for($rows=0; $rows<3; $rows++){
echo “|”. $product[($rows][$code] . “-”.
$product[($rows]
[$description] . “-”.
$product[($rows][$price] . “|”. “<BR/>”;
}
Reusing Code
Using require() and include():
 allow you to reuse any type of code stored as a file
 The following code is stored in a file named reusable.php:
<?php
echo ‘Here is a very simple PHP statement.<br />’;
?>
 The following code is stored in a file named main.php:
<?php
echo ‘This is the main file.<br />’;
require( ‘reusable.php’ );
echo ‘The script will end now.<br />’;
?>
 Main.php displays the content of both files
 The statements require() and include() are almost
identical. The only difference between them is that when
they fail, the require() construct gives a fatal error,
whereas the include() construct gives only a warning
Functions
Calling Functions
 The following line is the simplest possible call to
a function:
function_name();
 This line calls a function that does not require
parameters and ignores any value that might be
returned by this function
 Another possible call is with parameters
function_name(parameterList);
$returnedValue=function_name(parameterList);
 The type of calling a function depends on the
definition of the function
 Calling a function is not case sensitive, be
consistent
FUnCtion_Name(); FUNCTION_NAME();
Functions
Function definition:
 The declaration begins with the keyword
function, provides the function name and
parameters required, and contains the code that
will be executed each time this function is
called.
function Function_name(parameters){
statements;
}
 It is a good idea to have a file or set of files
containing your commonly used functions. You
can then have a require() statement in your
scripts to make your functions available when
required.
Functions
Variable Scope
 Variables declared inside a function are in scope from the
statement in which they are declared to the closing brace
at the end of the function.
 This is called function scope. These variables are called local
variables.
 Variables declared outside functions are in scope from the
statement in which they are declared to the end of the
file, but not inside functions.
 This is called global scope. These variables are called global
variables.
 The special superglobal variables are visible both inside
and outside functions
 Using require() and include() statements does not affect
scope. If the statement is used within a function, function
scope applies. If it is not inside a function, global scope
applies.
 The keyword global can be used to manually specify that
a variable defined or used within a function will have
global scope.
Functions
Passing by Reference Versus Passing by Value
 Consider the following example
function increment($value, $amount = 1)
{ $value = $value +$amount; }
$value = 10;
increment ($value);
echo $value;
 This prints the value 10, which is not
incremented
 Can be modified in two ways
Pass by reference:
function increment(&$value, $amount = 1)
{ $value = $value +$amount; }
Modify the scope:
function increment($value, $amount = 1)
{ global $value; $value = $value +$amount; }
Functions
Returning from Functions:
 The keyword return stops the execution of a
function
function myfunction(){
statements;
if (condition)
return;
statements; }
Returning Values from Functions:
 To send some value use return followed by value
function add($x, $y){
$sum=$x+$y;
return $sum; }
Functions in PHP
 A function is a self contained module of code
that prescribe a calling interface, performs some
task and optionally return a result
Function declaration

unction functionName(parameter1, parameter2…){


Function body….
return
}
Example 1 : calling function
<html>
<body>

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

You might also like