SlideShare a Scribd company logo
Personal Home Page (Old)
Hypertext Preprocessor (Now)
By: @sami_Khan
What is PHP……?
PHP is a server scripting language, and a powerful tool
for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to
competitors such as Microsoft's ASP.
Php intro by sami kz
Php intro by sami kz
Php intro by sami kz
Php intro by sami kz
Php intro by sami kz
XAMPP Server
Lecture#2
Download XAMPP: https://www.apachefriends.org/index.html
 Install XAMPP
 Start Apache Server and MySQL
 To Check that Apache server is running or not, we type
in Browser: http://localhost/
 XAMPP page should be opened
 Select language as English
XAMPP Home Page in English:
Notepad
Notepad++
Dreamweaver
Notepad
 Notepad is an Application in windows
 Path in Windows 8:
C:UsersManiAppDataRoamingMicrosoftWindowsStart
MenuProgramsAccessories
 Path in Windows 7
C:Windowssystem32
Start Menu:
Start > Programs > Accessories > Notepad
Notepad++
 Download Link:
https://notepad-plus-plus.org/download/v6.8.3.html
Notepad++
Adobe Dreamweaver
 Best Software for scripting
 Easy in use
PHP Syntax
Comment in PHP
Echo/Print
PHP Syntax
 Basic tags of PHP in which we type the whole code of
php.
Syntax:
<?php
// PHP code goes here
?>
PHP Coding
 During PHP coding we also need HTML, so normally we
use HTML & PHP together, (PHP in between HTML).
Comment in PHP
 In large programs we have to use ‘comments’, to
explain next code.
 In PHP we use
 // For One Whole Line
 # For One Whole Line
 /* For Multiple Lines
---
---
*/
Use of Comments in PHP
Echo/Print
 The echo/print function outputs one or more strings
 The echo function is slightly faster than print
Echo Syntax:
<?php
echo "Hello world!";
?>
Print Syntax:
<?php
print "Hello world!";
?>
echo “string”;
 String must be in double coats
 Semicolon ‘ ; ’ is used to end the line
PHP Code:
<?php
echo “I love Islam”;
?>
Php intro by sami kz
Rules for PHP variables:
 A variable defines with the $ (dollar sign)
 A variable name must start with a letter or the underscore
character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $Age are two
different variables)
Define a Variable
 Variable defines with ‘$’ (dollar sign):
$variable=value;
Example:
<?php
$txt = "Hello world!"; /* String Variable */
$x =35;
$y = 33.5;
?>
Note: When you assign a text value to a variable, put quotes around the value
Output Variables
 The PHP echo statement is often used to output data
to the screen.
 The following example will show how to output text
and a variable:
PHP Code:
<?php
$txt = “Islam";
echo "I love $txt";
?>
Scope of Variables
 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.
 PHP has three different variable scopes:
 Global Variable: A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function
 Local Variable: A variable declared within a function has a LOCAL SCOPE
and can only be accessed within that function
 Static Variable: when a function is completed/executed, its variables are
deleted. Sometimes we want a local variable.
We use the static keyword when you first declare the variable
static $x = 0;
PHP Data Types
Variables can store data of different types, and different
data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
String
 A string is a sequence of characters, like "Hello world!".
 A string can be any text inside quotes. You can use single or
double quotes:
Integer
An integer is a whole number (without decimals). It is a number
between -2,147,483,648 and +2,147,483,647.
Rules for integers:
 An integer must have at least one digit (0-9)
 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based -
prefixed with 0)
In the following example $x is an integer. The PHP var_dump()
function returns the data type and value:
Float
 A float (floating point number) is a number with a decimal
point or a number in exponential form.
 In the following example $x is a float. The PHP var_dump()
function returns the data type and value:
Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will
learn more about conditional testing in a later chapter of
this tutorial.
Array
 An array stores multiple values in one single variable.
 In the following example $cars is an array. The PHP var_dump()
function returns the data type and value:
PHP String Functions
 strlen() function returns the length of a string.
 str_word_count() function counts the number of words in a
string:
 strrev() function reverses a string:
 strpos() function searches for a specific text within a string.
The function returns the character position of the first match.
 str_replace() function replaces some characters with some
other characters in a string
PHP Constants
 To create a constant, use the define() function.
define(name, value, case-insensitive)
Parameters:
 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false
<html>
<body>
<?php
// Constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
</body>
</html>
<html>
<body>
<?php
// constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!");
echo greeting;
?>
</body>
</html>
<html>
<body>
<?php
// Constant name is case-sensitive by default(false)
define("GREETING", "Welcome to W3Schools.com!“, true);
echo greeting;
?>
</body>
</html>
Constants are Global
 Constants are automatically global and can be used across the
entire script.
The example below uses a constant inside a function, but it is
defined outside the function:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
Php intro by sami kz
PHP Operators
 Operators are used to perform operations on variables and
values.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
Arithmetic Operators
 The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
Assignment Operators
 The PHP assignment operators are used with numeric values
to write a value to a variable.
 The basic assignment operator in PHP is "=". It means that the
left operand gets set to the value of the assignment expression
on the right.
Comparison Operators
The PHP comparison operators are used to compare two values
(number or string):
Increment / Decrement Operators
 The PHP increment operators are used to increment a
variable's value.
 The PHP decrement operators are used to decrement a
variable's value.
Logical Operators
 The PHP logical operators are used to combine conditional
statements.
String Operators
 PHP has two operators that are specially designed for strings.
Array Operators
 The PHP array operators are used to compare arrays.
Php intro by sami kz
Conditional Statements
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional
statements in your code to do this.
 In PHP we have the following conditional statements:
 if statement - executes some code only if a specified condition is
true
 if...else statement - executes some code if a condition is true and
another code if the condition is false
 if...elseif....else statement - specifies a new condition to test, if the
first condition is false
 switch statement - selects one of many blocks of code to be
executed
The if Statement
The if statement is used to execute some code only if a
specified condition is true.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
if statement:
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
The if...else Statement
Use the if....else statement to execute some code if a condition
is true and another code if the condition is false.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The if...elseif....else Statement
Use the if....elseif...else statement to specify a new condition to
test, if the first condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
}
elseif (condition) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
PHP switch Statement
Use the switch statement to select one of many blocks of code
to be executed.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Note: Use break to prevent the code from running into the next case automatically.
Php intro by sami kz
PHP Loops
Instead of adding several almost equal code-lines in a script, we can
use loops to perform a task like this.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified
condition is true
 do...while - loops through a block of code once, and then repeats
the loop as long as the specified 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
While Loop
The while loop executes a block of code as long as the
specified condition is true.
Syntax:
while (condition is true)
{
code to be executed;
}
Php intro by sami kz
Do...While Loop
The Do...While loop will always execute the block of code once,
it will then check the condition, and repeat the loop while the
specified condition is true.
Syntax:
Do
{
code to be executed;
}
while (condition is true);
Php intro by sami kz
For Loop
The for loop is used when you know in advance how many times
the script should run.
Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
Foreach Loop
The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned
to $value and the array pointer is moved by one, until it reaches the last
array element.
Php intro by sami kz
The real power of PHP comes from its functions; it has
more than 1000 built-in functions.
Functions in PHP
 A function is a block of statements that can be used
repeatedly in a program.
 A function will not execute immediately when a page
loads.
 A function will be executed by a call to the function.
User Defined Function in PHP
A user defined function declaration starts with the word
"function":
Syntax:
function functionName()
{
code to be executed;
}
Note:
 A function name can start with a letter or underscore (not a number).
 Give the function a name that reflects what the function does!
 Function names are NOT case-sensitive.
// Calling a Function
// Creating a Function
Function Arguments
* Default Argument Values
Functions - Returning values
To let a function return a value, use the return statement:
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
Some Built-in Functions in PHP
Rais-to-power and Square-root Function:
$a = 3; Results:
$b = 4;
$c = pow($a, 2) + pow($b, 2);
echo “ ’a’ rais to power 2 is ".pow($a, 2); 9
echo “ 'b' rais to power 2 is ".pow($b, 2); 16
echo "C = ".(pow($a, 2) + pow($b, 2)); 25
echo “ Square Root of C is ". sqrt($c); 5
A special kind of variable
Arrays
An array is a special variable, which can hold many values under a single
name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like
this:
$cars = array("Volvo", "BMW", "Toyota");
Or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example
The following example creates an indexed array named $cars, assigns
three elements to it, and then prints a text containing the array values:
Get The Length of an Array
The count() Function:
The count() function is used to return the length (the
number of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array,
you could use a for loop, like this:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Associative Arrays
Associative arrays are arrays that use named keys that
you assign to them.
There are two ways to create an associative array:
Syntax:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Result: Peter is 35 years old.
Loop Through an Associative Array
To loop through and print all the values of an associative array,
you could use a foreach loop, like this:
Php intro by sami kz
Sort Functions For Arrays
The elements in an array can be sorted in alphabetical or
numerical order, descending or ascending.
PHP array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
} Result: BMW
?> Toyota
Volvo
Php intro by sami kz
PHP Global Variables - Superglobals
Several predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do
anything special.
The PHP superglobal variables are:
 $GLOBALS
 $_SERVER
 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION
$GLOBALS
$GLOBALS is a PHP super global variable which is used to access global
variables from anywhere in the PHP script (also from within functions or
methods).
PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
Example:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition(); Result: 100
echo $z;
?>
$_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
The example below shows how to use some of the elements in
$_SERVER:
The following table lists the most important elements that can go inside $_SERVER:
Php intro by sami kz
$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
The example below shows a form with an input field and a submit
button. We point to this file itself for processing form data. Then, we can
use the super global variable $_REQUEST to collect the value of the
input field:
$_POST
PHP $_POST is widely used to collect form data after submitting an
HTML form with method="post". $_POST is also widely used to pass
variables.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
$_GET
PHP $_GET can also be used to collect form data after submitting an
HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with
parameters:
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
When a user clicks on the link "Test $GET", the parameters "subject" and
"web" is sent to "test_get.php", and you can then access their values in
"test_get.php" with $_GET.
Php intro by sami kz
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect
form-data.
Simple HTML Form:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
When the user fills out the form above and clicks the submit
button, the form data is sent for processing to a PHP file named
"welcome.php". The form data is sent with the HTTP POST
method.
<html>
<body>
Welcome <?php echo $_POST["name"]; ?> <br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
GET vs. POST
Both GET and POST create an array [array( key => value, …)]. This
array holds key/value pairs, where keys are the names of the
form controls and values are the input data from the user.
 $_GET is an array of variables passed to the current script via the URL
parameters.
Information sent from a form with the GET method is visible to everyone.
 $_POST is an array of variables passed to the current script via the HTTP
POST method.
Information sent from a form with the POST method is invisible to others.
Note: Developers prefer POST for sending form data
Form Validation
Proper validation of form data is important to protect your form from
hackers and spammers!
The validation rules for the form above are as follows:
Form Element
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 The $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page.
 The htmlspecialchars() function converts special characters to HTML
entities. This means that it will replace HTML characters like < and > with
&lt; and &gt;. This prevents attackers from exploiting the code by
injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
PHP Forms - Validate E-mail and URL
Validate Name
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
Validate E-mail
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
If the URL address syntax is not valid, then store an error
message:
Validate URL
$website = test_input($_POST["website"]);
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-
9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
•With PHP, you can connect to and manipulate databases.
•MySQL is the most popular database system used with PHP.
What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle
Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My
MySQL Database
The data in a MySQL database are stored in tables. A table is a
collection of related data, and it consists of columns and rows.
Databases are useful for storing information categorically. A
company may have a database with the following tables:
 Employees
 Products
 Customers
 Orders
Note:
MySQL is the de-facto standard database system for web sites with
HUGE volumes of both data and end-users (like Facebook, Twitter, and
Wikipedia).
Database Queries
“A query is a question or a request.”
We can query a database for specific information and have a
recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees;
The query above selects all the data in the "LastName" column from
the "Employees" table.
Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can
download it for free here: http://www.mysql.com
Look at http://www.mysql.com/customers for an overview of
companies using MySQL.
Php intro by sami kz

More Related Content

PPTX
Lesson 4 constant
PPTX
Lesson 2 php data types
DOCX
Free PHP Book Online | PHP Development in India
PPTX
Lesson 6 php if...else...elseif statements
PDF
Php tutorial
PPTX
Lesson 3 php numbers
PPTX
Lesson 1 php syntax
PPTX
Learn PHP Basics
Lesson 4 constant
Lesson 2 php data types
Free PHP Book Online | PHP Development in India
Lesson 6 php if...else...elseif statements
Php tutorial
Lesson 3 php numbers
Lesson 1 php syntax
Learn PHP Basics

What's hot (20)

PPTX
Basic of PHP
PPTX
PHP Basics
PPT
P H P Part I, By Kian
ODP
PHP Web Programming
PDF
Php web development
PPTX
Data types in php
PPTX
PPSX
PHP Comprehensive Overview
PDF
03phpbldgblock
PDF
Ruby cheat sheet
PPTX
php basics
PDF
Materi Dasar PHP
PDF
Ruby quick ref
PDF
Cs3430 lecture 15
ODP
Php Learning show
PPT
Basic PHP
Basic of PHP
PHP Basics
P H P Part I, By Kian
PHP Web Programming
Php web development
Data types in php
PHP Comprehensive Overview
03phpbldgblock
Ruby cheat sheet
php basics
Materi Dasar PHP
Ruby quick ref
Cs3430 lecture 15
Php Learning show
Basic PHP
Ad

Similar to Php intro by sami kz (20)

PDF
Introduction to PHP - Basics of PHP
PDF
Programming in PHP Course Material BCA 6th Semester
PPTX
Php.ppt
PPTX
PHP Lecture 01 .pptx PHP Lecture 01 pptx
PDF
WT_PHP_PART1.pdf
PPTX
php Chapter 1.pptx
PPTX
Php basics
PPT
PHP - Introduction to PHP - Mazenet Solution
PPTX
Php Tutorial
PPTX
FYBSC IT Web Programming Unit IV PHP and MySQL
PDF
Web Development Course: PHP lecture 1
PPTX
PHP Basics
PPTX
PPT
php41.ppt
PPT
PHP InterLevel.ppt
PPT
php-I-slides.ppt
PPT
introduction to php web programming 2024.ppt
PPTX
Php by shivitomer
Introduction to PHP - Basics of PHP
Programming in PHP Course Material BCA 6th Semester
Php.ppt
PHP Lecture 01 .pptx PHP Lecture 01 pptx
WT_PHP_PART1.pdf
php Chapter 1.pptx
Php basics
PHP - Introduction to PHP - Mazenet Solution
Php Tutorial
FYBSC IT Web Programming Unit IV PHP and MySQL
Web Development Course: PHP lecture 1
PHP Basics
php41.ppt
PHP InterLevel.ppt
php-I-slides.ppt
introduction to php web programming 2024.ppt
Php by shivitomer
Ad

Recently uploaded (20)

DOCX
Unit-3 cyber security network security of internet system
PPTX
artificial intelligence overview of it and more
PDF
The New Creative Director: How AI Tools for Social Media Content Creation Are...
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
presentation_pfe-universite-molay-seltan.pptx
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PPTX
innovation process that make everything different.pptx
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PDF
RPKI Status Update, presented by Makito Lay at IDNOG 10
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PDF
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
PDF
Paper PDF World Game (s) Great Redesign.pdf
Unit-3 cyber security network security of internet system
artificial intelligence overview of it and more
The New Creative Director: How AI Tools for Social Media Content Creation Are...
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
An introduction to the IFRS (ISSB) Stndards.pdf
presentation_pfe-universite-molay-seltan.pptx
INTERNET------BASICS-------UPDATED PPT PRESENTATION
innovation process that make everything different.pptx
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
RPKI Status Update, presented by Makito Lay at IDNOG 10
Decoding a Decade: 10 Years of Applied CTI Discipline
Job_Card_System_Styled_lorem_ipsum_.pptx
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Design_with_Watersergyerge45hrbgre4top (1).ppt
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
Cloud-Scale Log Monitoring _ Datadog.pdf
Power Point - Lesson 3_2.pptx grad school presentation
Paper PDF World Game (s) Great Redesign.pdf

Php intro by sami kz

  • 1. Personal Home Page (Old) Hypertext Preprocessor (Now) By: @sami_Khan
  • 2. What is PHP……? PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
  • 10.  Install XAMPP  Start Apache Server and MySQL
  • 11.  To Check that Apache server is running or not, we type in Browser: http://localhost/  XAMPP page should be opened  Select language as English
  • 12. XAMPP Home Page in English:
  • 14. Notepad  Notepad is an Application in windows  Path in Windows 8: C:UsersManiAppDataRoamingMicrosoftWindowsStart MenuProgramsAccessories  Path in Windows 7 C:Windowssystem32 Start Menu: Start > Programs > Accessories > Notepad
  • 17. Adobe Dreamweaver  Best Software for scripting  Easy in use
  • 18. PHP Syntax Comment in PHP Echo/Print
  • 19. PHP Syntax  Basic tags of PHP in which we type the whole code of php. Syntax: <?php // PHP code goes here ?>
  • 20. PHP Coding  During PHP coding we also need HTML, so normally we use HTML & PHP together, (PHP in between HTML).
  • 21. Comment in PHP  In large programs we have to use ‘comments’, to explain next code.  In PHP we use  // For One Whole Line  # For One Whole Line  /* For Multiple Lines --- --- */
  • 22. Use of Comments in PHP
  • 23. Echo/Print  The echo/print function outputs one or more strings  The echo function is slightly faster than print Echo Syntax: <?php echo "Hello world!"; ?> Print Syntax: <?php print "Hello world!"; ?>
  • 24. echo “string”;  String must be in double coats  Semicolon ‘ ; ’ is used to end the line PHP Code: <?php echo “I love Islam”; ?>
  • 26. Rules for PHP variables:  A variable defines with the $ (dollar sign)  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive ($age and $Age are two different variables)
  • 27. Define a Variable  Variable defines with ‘$’ (dollar sign): $variable=value; Example: <?php $txt = "Hello world!"; /* String Variable */ $x =35; $y = 33.5; ?> Note: When you assign a text value to a variable, put quotes around the value
  • 28. Output Variables  The PHP echo statement is often used to output data to the screen.  The following example will show how to output text and a variable: PHP Code: <?php $txt = “Islam"; echo "I love $txt"; ?>
  • 29. Scope of Variables  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.  PHP has three different variable scopes:  Global Variable: A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function  Local Variable: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function  Static Variable: when a function is completed/executed, its variables are deleted. Sometimes we want a local variable. We use the static keyword when you first declare the variable static $x = 0;
  • 30. PHP Data Types Variables can store data of different types, and different data types can do different things. PHP supports the following data types:  String  Integer  Float (floating point numbers - also called double)  Boolean  Array
  • 31. String  A string is a sequence of characters, like "Hello world!".  A string can be any text inside quotes. You can use single or double quotes:
  • 32. Integer An integer is a whole number (without decimals). It is a number between -2,147,483,648 and +2,147,483,647. Rules for integers:  An integer must have at least one digit (0-9)  An integer cannot contain comma or blanks  An integer must not have a decimal point  An integer can be either positive or negative  Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
  • 33. In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
  • 34. Float  A float (floating point number) is a number with a decimal point or a number in exponential form.  In the following example $x is a float. The PHP var_dump() function returns the data type and value:
  • 35. Boolean A Boolean represents two possible states: TRUE or FALSE. $x = true; $y = false; Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.
  • 36. Array  An array stores multiple values in one single variable.  In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
  • 37. PHP String Functions  strlen() function returns the length of a string.  str_word_count() function counts the number of words in a string:  strrev() function reverses a string:  strpos() function searches for a specific text within a string. The function returns the character position of the first match.  str_replace() function replaces some characters with some other characters in a string
  • 38. PHP Constants  To create a constant, use the define() function. define(name, value, case-insensitive) Parameters:  name: Specifies the name of the constant  value: Specifies the value of the constant  case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
  • 39. <html> <body> <?php // Constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?> </body> </html>
  • 40. <html> <body> <?php // constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!"); echo greeting; ?> </body> </html>
  • 41. <html> <body> <?php // Constant name is case-sensitive by default(false) define("GREETING", "Welcome to W3Schools.com!“, true); echo greeting; ?> </body> </html>
  • 42. Constants are Global  Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, but it is defined outside the function: <?php define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest(); ?>
  • 44. PHP Operators  Operators are used to perform operations on variables and values. PHP divides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators
  • 45. Arithmetic Operators  The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
  • 46. Assignment Operators  The PHP assignment operators are used with numeric values to write a value to a variable.  The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
  • 47. Comparison Operators The PHP comparison operators are used to compare two values (number or string):
  • 48. Increment / Decrement Operators  The PHP increment operators are used to increment a variable's value.  The PHP decrement operators are used to decrement a variable's value.
  • 49. Logical Operators  The PHP logical operators are used to combine conditional statements.
  • 50. String Operators  PHP has two operators that are specially designed for strings.
  • 51. Array Operators  The PHP array operators are used to compare arrays.
  • 53. Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.  In PHP we have the following conditional statements:  if statement - executes some code only if a specified condition is true  if...else statement - executes some code if a condition is true and another code if the condition is false  if...elseif....else statement - specifies a new condition to test, if the first condition is false  switch statement - selects one of many blocks of code to be executed
  • 54. The if Statement The if statement is used to execute some code only if a specified condition is true. Syntax: if (condition) { code to be executed if condition is true; }
  • 55. if statement: <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?>
  • 56. The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is false. Syntax: if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 57. The if...elseif....else Statement Use the if....elseif...else statement to specify a new condition to test, if the first condition is false. Syntax: if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 58. PHP switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax: switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } Note: Use break to prevent the code from running into the next case automatically.
  • 60. PHP Loops Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements:  while - loops through a block of code as long as the specified condition is true  do...while - loops through a block of code once, and then repeats the loop as long as the specified 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
  • 61. While Loop The while loop executes a block of code as long as the specified condition is true. Syntax: while (condition is true) { code to be executed; }
  • 63. Do...While Loop The Do...While loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax: Do { code to be executed; } while (condition is true);
  • 65. For Loop The for loop is used when you know in advance how many times the script should run. Syntax: for (init counter; test counter; increment counter) { code to be executed; } Parameters: init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value
  • 66. The example below displays the numbers from 0 to 10:
  • 67. Foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax: foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
  • 69. The real power of PHP comes from its functions; it has more than 1000 built-in functions.
  • 70. Functions in PHP  A function is a block of statements that can be used repeatedly in a program.  A function will not execute immediately when a page loads.  A function will be executed by a call to the function.
  • 71. User Defined Function in PHP A user defined function declaration starts with the word "function": Syntax: function functionName() { code to be executed; } Note:  A function name can start with a letter or underscore (not a number).  Give the function a name that reflects what the function does!  Function names are NOT case-sensitive.
  • 72. // Calling a Function // Creating a Function
  • 73. Function Arguments * Default Argument Values
  • 74. Functions - Returning values To let a function return a value, use the return statement: <?php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5,10) . "<br>"; echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4); ?>
  • 75. Some Built-in Functions in PHP Rais-to-power and Square-root Function: $a = 3; Results: $b = 4; $c = pow($a, 2) + pow($b, 2); echo “ ’a’ rais to power 2 is ".pow($a, 2); 9 echo “ 'b' rais to power 2 is ".pow($b, 2); 16 echo "C = ".(pow($a, 2) + pow($b, 2)); 25 echo “ Square Root of C is ". sqrt($c); 5
  • 76. A special kind of variable
  • 77. Arrays An array is a special variable, which can hold many values under a single name, and you can access the values by referring to an index number.
  • 78. Create an Array in PHP In PHP, the array() function is used to create an array: array(); In PHP, there are three types of arrays:  Indexed arrays - Arrays with a numeric index  Associative arrays - Arrays with named keys  Multidimensional arrays - Arrays containing one or more arrays
  • 79. Indexed Arrays There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); Or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
  • 80. Example The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
  • 81. Get The Length of an Array The count() Function: The count() function is used to return the length (the number of elements) of an array: <?php $cars = array("Volvo", "BMW", "Toyota"); echo count($cars); ?>
  • 82. Loop Through an Indexed Array To loop through and print all the values of an indexed array, you could use a for loop, like this: <?php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?>
  • 83. Associative Arrays Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: Syntax: <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> Result: Peter is 35 years old.
  • 84. Loop Through an Associative Array To loop through and print all the values of an associative array, you could use a foreach loop, like this:
  • 86. Sort Functions For Arrays The elements in an array can be sorted in alphabetical or numerical order, descending or ascending. PHP array sort functions:  sort() - sort arrays in ascending order  rsort() - sort arrays in descending order  asort() - sort associative arrays in ascending order, according to the value  ksort() - sort associative arrays in ascending order, according to the key  arsort() - sort associative arrays in descending order, according to the value  krsort() - sort associative arrays in descending order, according to the key
  • 87. Example: <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); $clength = count($cars); for($x = 0; $x < $clength; $x++) { echo $cars[$x]; echo "<br>"; } Result: BMW ?> Toyota Volvo
  • 89. PHP Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are:  $GLOBALS  $_SERVER  $_REQUEST  $_POST  $_GET  $_FILES  $_ENV  $_COOKIE  $_SESSION
  • 90. $GLOBALS $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. Example: <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); Result: 100 echo $z; ?>
  • 91. $_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. The example below shows how to use some of the elements in $_SERVER:
  • 92. The following table lists the most important elements that can go inside $_SERVER:
  • 94. $_REQUEST PHP $_REQUEST is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. We point to this file itself for processing form data. Then, we can use the super global variable $_REQUEST to collect the value of the input field:
  • 95. $_POST PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?>
  • 96. $_GET PHP $_GET can also be used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a> When a user clicks on the link "Test $GET", the parameters "subject" and "web" is sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.
  • 98. PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. Simple HTML Form: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
  • 99. welcome.php When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. <html> <body> Welcome <?php echo $_POST["name"]; ?> <br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html>
  • 100. GET vs. POST Both GET and POST create an array [array( key => value, …)]. This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.  $_GET is an array of variables passed to the current script via the URL parameters. Information sent from a form with the GET method is visible to everyone.  $_POST is an array of variables passed to the current script via the HTTP POST method. Information sent from a form with the POST method is invisible to others. Note: Developers prefer POST for sending form data
  • 101. Form Validation Proper validation of form data is important to protect your form from hackers and spammers! The validation rules for the form above are as follows:
  • 102. Form Element <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  The $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page.  The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
  • 103. PHP Forms - Validate E-mail and URL Validate Name $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } Validate E-mail $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
  • 104. If the URL address syntax is not valid, then store an error message: Validate URL $website = test_input($_POST["website"]); if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0- 9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; }
  • 105. •With PHP, you can connect to and manipulate databases. •MySQL is the most popular database system used with PHP.
  • 106. What is MySQL?  MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications  MySQL is very fast, reliable, and easy to use  MySQL uses standard SQL  MySQL compiles on a number of platforms  MySQL is free to download and use  MySQL is developed, distributed, and supported by Oracle Corporation  MySQL is named after co-founder Monty Widenius's daughter: My
  • 107. MySQL Database The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Databases are useful for storing information categorically. A company may have a database with the following tables:  Employees  Products  Customers  Orders Note: MySQL is the de-facto standard database system for web sites with HUGE volumes of both data and end-users (like Facebook, Twitter, and Wikipedia).
  • 108. Database Queries “A query is a question or a request.” We can query a database for specific information and have a recordset returned. Look at the following query (using standard SQL): SELECT LastName FROM Employees; The query above selects all the data in the "LastName" column from the "Employees" table.
  • 109. Download MySQL Database If you don't have a PHP server with a MySQL Database, you can download it for free here: http://www.mysql.com Look at http://www.mysql.com/customers for an overview of companies using MySQL.