AIP Chapter 1
AIP Chapter 1
• Home page -is a default page that is loaded into a browser when it is opened.
• Web site -is a collection of related web pages. Has a globally unique name.
• HTTP- used to exchange request/response message between web browser and web server.
• Web Browser- an application software that used to view pages available over internet.
Cont.…
Web server- is a software which provides documents when requested by web browsers via HTTP.
URL- The exact address of a resource on the web. It have its own formats. (Protocol, hostname(Domain),
path ).
ISP- is a commercial company that sells Internet connections to users. (e.g.: Ethio telecom)
Internet- network of networks that connects millions of computers across the world.
Cont.…
Scripts- are a series of commands that are able to be executed without the need for compiling.
The content of the web page will not be the same every time you look at it;
It will change dynamically depending on certain factors such as the actions of the person
Static Websites
Written in HTML and CSS only – web pages
Pages are separate documents
No database that draws to it
In a nutshell:
Dynamic Websites
Requires more complex coding
Web pages can do much more – they are interactive!
Examples – login page, search pages, querying a backend database
Uses three major technologies:
Static Dynamic
Scripts are stored on the client (engine is in Scripts are stored on the server (engine is on
browser) server)
Scripts can be modified by the end user Scripts cannot be modified by the end user
Browser-dependent Browser-independent
Processing is done by the browser - fast Processing is done by the server - slower
9
What is PHP ?
10
What is a PHP file?
11
Cont.…
• An embedded scripting language, meaning that it can exist within HTML code.
• Compatible with almost all servers used today (Apache, IIS, etc.)
12
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
13
PHP Does Not…
• Do anything within the Web browser until a request from the client has been
made (e.g., submitting a form, clicking a link, etc.).
14
Why Use PHP?
• PHP has been described as being “better, faster, and easier to learn than the
alternatives”
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, Microsoft SQL Server etc)
15
Cont..
• Accessibility: You can reach the internet from any browser, any device, anytime,
anywhere.
• Security: The source code is not exposed. Once user is authenticated, can only
allow certain actions. It also allows encryption.
Open htdocs\.
Install text editor (notepad, notepad++,sublime text…) , open and write code
• Start your PHP code with <?php and end it with ?>.
• If most of the page content is HTML, the PHP code is usually embedded.
• The code itself is defined within PHP delimiters: <?php and end ?>.
18
PHP Basic Syntax
The PHP parsing engine needs a way to differentiate PHP code from other elements
in the page. The mechanism for doing so is known as ‘escaping to PHP.’ There are four
ways to do this:
1. Canonical PHP tags
The most universally effective PHP tag style is:
If you use this style, you can be positive that your tags will always be correctly interpreted.
2. Short-open (SGML-style) tags: Short tags are, as one might expect, the shortest option.
We must do one of two things to enable PHP to recognize the tags:
19
PHP Basic Syntax
Choose the --enable-short-tags configuration option when building PHP.
Set the short_open_tag setting in php.ini file to on. This option must be disabled to parse
XML with PHP because the same syntax is used for XML tags.
3. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. To use ASP-style tags, we should set the configuration option in your php.ini
file.
• 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.
1. echo
2. print.
22
PHP Output Statement
• The returned value represents whether the print statement is succeeded or not.
• echo can take multiple parameters but print can only take one argument.
echo is marginally faster than print.
echo or echo().
23
Cont..
24
echo/print
• Example: different ways of echo and print
echo 123; //output: 123
echo “Hello World!”; //output: Hello world!
echo (“Hello World!”); //output: Hello world!
echo “Hello”,”World!”; //output: Hello World!
echo Hello World!; //output: error, string should be enclosed in quotes
print (“Hello world!”); //output: Hello world!
26
Cont..
27
PHP variables
• Variables are "containers" for storing information.
• A variable can hold numbers, doubles, strings, Booleans, objects, arrays,
resources or it can be NULL.
• The syntax for PHP variables is similar to C++ and most other programming
languages Like, Java.
28
Cont..
• They are dynamically typed, so you do not need to specify the type .
29
PHP Variable Naming Conventions
A variable starts with the $ sign, followed by the name of the variable
Variable names are case-sensitive ($age and $AGE are two different variables)
30
Cont…
PHP variables can only contain alpha-numeric characters and underscores. a-z, A-Z,
0-9, or _ .
Variables with more than one word should be separated with underscores:
$my_variable. (not contain space)
Variables with more than one word can also be distinguished with capitalization:
$myVariable.
31
What you say the following variable name rules?
1. $information technology Invalid (no spaces allowed)
• It allows you to create aliases for variables, and it also allows you to have
variables whose name is a variable.
33
Cont.…
34
Predefined / Environment Variables
• Beyond the variables you declare in your code, PHP has a collection of
environment variables, which are system defined variables that are accessible
from anywhere inside the PHP code.
• These variables allow the script access to server information, form parameters,
environment information, etc.
• Some you can address directly by using the name of the index position as a
variable name. Other can only be accessed through their arrays.
35
Cont.…
• $GLOBALS — References all variables available in global scope
• Superglobals — Superglobals are built-in variables that are always available in all scopes
• $_SERVER — Server and execution environment information
• $_GET — HTTP GET variables
• $_POST — HTTP POST variables
• $_FILES — HTTP File Upload variables
• $_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and $_COOKIE
variables
• $_SESSION — Session variables
• $_COOKIE — HTTP Cookies
• $php_errormsg — The previous error message
• $HTTP_RAW_POST_DATA — Raw POST data
• $http_response_header — HTTP response headers
• $argc — The number of arguments passed to script
• $argv — Array of arguments passed to script 36
Display Variables
The following example shows how to output text and variables with
the print statement:
<?php
$txt1 = “Students ";
$txt2 = “Third Year ";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>//output ??? 37
Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
Local
Global
Static
38
Global Scope
• A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
• Example
• Variable with global scope:
• <?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
echo "$y"."<br>";
}
myTest();
echo $y; // outputs what will be the code if the outputs = 15 15 and ??
?> 41
Cont.…
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable. This array is also accessible from within functions and can be used
to update global variables directly.
The example above can be rewritten like this:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS["y"] = $GLOBALS['x'] + $GLOBALS['y'];
echo $GLOBALS["y"] . "<br>";
}
myTest();
echo $x; // outputs 15
5 42
static keyword
When a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest(); // Outputs 0
myTest(); // Outputs 1
myTest(); // Outputs 2 //the out put is 012 what about the code of this out put?
?> Then, each time the function is called, that variable will still have the information it contained from the
last time the function was called. The variable is still local to the function.
43
Data Types
• PHP has a total of eight data types which we use to construct our variables:
integers, floats, Booleans, strings, arrays, objects, null, and resources.
• The first four are simple types, and the next two (arrays and
objects) are compound - the compound types can package up other arbitrary
values of arbitrary type, whereas the simple types cannot. The last two are
Special types.
• PHP has a useful function named var_dump() that prints the current data
type and value for one or more variables.
44
string
• A string is a sequence of characters, like "Hello world!".
• <?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
45
Cont.…
• Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>//My $variable will not print!\n
My name will print 46
String Concatenation Operator
• To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
47
integers
48
Rules for integers
• An integer must have at least one digit
• Integers can be specified in: base 10, base 16, base 8, or base 2 notation
• <?php
$x = 5985;
var_dump($x);
?>
49
Float
• <?php
• $x = 10.365;
• var_dump($x);
• $x = true;
$y = false;
• <?php
• $x=true;
• var_dump($x);
• ?> 51
Array
• An array is a data structure that stores one or more similar type of values in a
single value.
• The PHP var_dump() function returns the data type and value:
• <?php
• var_dump($cars);
• ?> 52
Cont..
• <?php
• $cars = array("Volvo","BMW","Toyota"); <?php
• foreach ($cars as $key => $value) {
$cars = array("Volvo", "BMW", "Toyota");
• echo $value ."<br>";
echo $cars[0]."<br>";
• }
• //var_dump($cars); echo $cars[1]."<br>";
• ?> echo $cars[2]; //Method 1 to create an array
?>
• <?php
• $cars = array("Volvo","BMW","Toyota");
• foreach ($cars as $key => $value) {
• echo $key." ". $value ."<br>";
• }
• //var_dump($cars);
• ?> 53
Cont.…
• There are three different kind of arrays and each array value is accessed using an
ID which is called array index.
– Numeric array - An array with a numeric index. Values are stored and accessed
in linear fashion.
– Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
• These arrays can store numbers, strings and any object but their index will
be presented by numbers. By default array index starts from zero.
Example
• Following is the example showing how to create and access numeric arrays.
55
Cont.…
<?php /* Second method to create array. */
/* First method to create array. */ <?php
$numbers = array( 1, 2, 3, 4, 5); $numbers[0] = 1;
foreach( $numbers as $value ) $numbers[1] = 2;
{ $numbers[2] = 3;
echo "Value is $value <br/>"; $numbers[3] = 4;
} // out puts are $numbers[4] = 5;
foreach( $numbers as $value ){
echo "Value is". $value ."<br/>";
}
?>
56
Associative Arrays
• The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
• Associative array will have their index as string so that you can establish a
strong association between key and values.
• There are two ways to create an associative array:
• //The first method to create this array
<?php
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
?> output is
58
Multidimensional Arrays
• A multi-dimensional array each element in the main array can also be an array.
Example
• This example is an associative array, you can create numeric array in the same
fashion.
59
Cont.…
<?php
$marks = array( "mohammad" => array("physics" => 35,"maths" => 30,"chemistry" =>39),
"qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ("physics" => 31, "maths" => 22, "chemistry" => 39 ) );
• <?php
• $numbers=array(4, 6, 2, 22, 11);
• rsort($numbers);
• for($i=0;$i<count($numbers)-1;$i++)
• echo $numbers[$i]."<br>";
• ?>
63
Sort Array (Ascending Order), According to Value - asort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• asort($course);
• foreach($course as $x => $x_value) {
• echo $x_value ;
• }
• ?> out put=405060
• Sort Array (Ascending Order), According to Key - ksort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• ksort($course);
• foreach($course as $x => $x_value) {
• echo $x . "<br>";
• }
• ?> 64
Sort Array (Descending Order), According to Value - arsort()
• <?php
• $course= array("OS"=>"50", "IP"=>"40", "SAD"=>"60");
• arsort($course);
• foreach($course as $x => $x_value) {
• echo $x_value . "<br>";
• }
• ?>
• Classes and objects are the two main aspects of object-oriented programming.
• An object is a data type which stores data and information on how to process that
data. An object is an instance of a class.
• A variable of data type NULL is a variable that has no value assigned to it.
• Example
• <?php
• $x = "Hello world!"; string(12) "Hello world!"
• $y = null; How can yow write the php code, if the output is= Hello world!"; ?
• var_dump($x);
• ?>
• // string(12) "Hello world!“
67
Resource
68
.
PHP String Functions
Commonly used functions to manipulate strings.
1. strlen()
<?php
?>// outputs 12
2. str_word_count()
<?php
• <?php
echo str_replace("world", "Center", " Hello world") ."<br>";
?> // outputs Hello Center!
• One thing to notice about PHP is that it provides automatic data type
conversion.
• So, if you assign an integer value to a variable, the type of that variable will
automatically be an integer. Then, if you assign a string to the same variable,
the type will change to a string.
73
PHP Integers
• An integer is a number without any decimal part.
• 2, 256, -256, 10358, -179567 are all integers. While 7.56, 10.0, 150.67 are
floats.
• 4 * 2.5 is 10, the result is stored as -------?, because one of the operands is a ---
----- (-----).
• PHP has the following functions to check if the type of a variable is integer:
• is_int()
• is_integer() - alias of is_int()
• is_long() - alias of is_int() 74
Cont..
• Example
• <?php
$x = 5985;
var_dump(is_int($x));
$x = 59.85;
var_dump(is_int($x));
?>// outputs
75
PHP Floats
• A float is a number with a decimal point or a number in exponential form.
• PHP has the following functions to check if the type of a variable is float:
• is_float() • <?php
$x = 10.365;
• is_double() - alias of is_float() var_dump(is_float($x));
?>// 76
PHP Infinity
• A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
• PHP has the following functions to check if a numeric value is finite or infinite:
• is_finite()
• is_infinite()
• Example:
• Check if a numeric value is finite or infinite:
• <?php
$x = 1.9e411;
var_dump($x);
?>// output is
77
PHP Numerical Strings
• The PHP is_numeric() function can be used to find whether a variable is
numeric. The function returns true if the variable is a number or a numeric
string, false otherwise.
• Check if the variable is numeric:
• <?php
• $x =5985;
• var_dump(is_numeric($x)) ;
• $x ="5985.5";
• var_dump(is_numeric($x)) ;
• $x ="Hello";
• var_dump(is_numeric($x));
• ?>
78
PHP Casting Strings and Floats to Integers
• Sometimes you need to cast a numerical value into another data type.
• The (int), (integer), or intval() function are often used to convert a value to an integer.
• Cast float and string to integer:
• <?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;
echo "<br>";
// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
?>//
79
PHP Math
• PHP has a set of math functions that allows you to perform mathematical tasks
on numbers.
1. pi() Function:The pi() function returns the value of PI:
<?php
echo(pi()); // returns 3.1415926535898
?>
2. min() and max() Functions:The min() and max() functions can be used to find
the lowest or highest value in a list of arguments:
<?php
echo(min(0,150,30,20,-8,-200)."<br>");
echo(max(0,150,30,20,-8,-200));
?> 80
Cont.
3. abs() Function: The abs() function returns the absolute (positive) value of a
number:
<?php
echo(abs(-6.7)); // returns 6.7
?>
4. sqrt() Function: The sqrt() function returns the square root of a number:
<?php
echo(sqrt(64)); // returns 8
?>
81
Cont.
5. round() Function: The round() function rounds a floating-point number to its
nearest integer:
<?php
echo(round(0.60)); // returns 1
echo(round(0.49)); // returns 0
?>
83
Constants
• A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script.
Syntax:
• You can also use the function constant() to read a constant's value if you
wish to obtain the constant's name dynamically.
• constant() function
• As indicated by the name, this function will return the value of the constant.
85
Cont…
• Parameters:
87
Cont..
• Constants are automatically global and can be used across the entire script.
• This example uses a constant inside a function, even if it is defined outside
the function:
• <?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>// 88
Cont.…
• Once the Constants have been set, may not be redefined or undefined.
89
PHP Operators
• Operators are used to perform operations on variables and values.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
Reading Assignment
PHP Operators
91
Questions?
92