SlideShare une entreprise Scribd logo
1  sur  41
PHP
                                  Workshop
                                  Day1




Prepared by :Ahmed Mahmoud Saad
Agenda

  1. Introduction

  2. Install

  2. Getting started


  3. Example
3




Introduction to PHP
 PHP: Hypertext Preprocessor
 Originally called “Personal Home          Page
  Tools”
 Popular server-side scripting
  technology
 Open-source
    Anyone may view, modify and redistribute
     source code
    Supported freely by community
 Platform   independent

                         G. Ochoa, G64HLL
Brief History of PHP
   As of August 2004, PHP is used on 16,946,328 Domains,
     1,348,793 IP Addresses http://www.php.net/usage.php
     This is roughly 32% of all domains on the web.
Why is PHP used?
3. Cost Benefits
  PHP is free. Open source code means that the entire PHP community will contribute
  towards bug fixes. There are several add-on technologies (libraries) for PHP that are
  also free.


                                PHP
   Software                     Free

   Platform                     Free (Linux)


   Development Tools            Free
                                PHP Coder, jEdit
Getting Started
                      How to escape from HTML and enter PHP mode                    .1
            PHP parses a file by looking for one of the special tags that           
       tells it to start interpreting the text as PHP code. The parser then
     executes all of the code it finds until it runs into a PHP closing tag.
               HTML                  PHP CODE                  HTML

                                <?php echo “Hello World”; ?>

Starting tag               Ending tag    Notes
<?php                      ?>            Preferred method as it allows the use of
                                         PHP with XHTML
<?                         ?>            Not recommended. Easier to type, but has
                                         to be enabled and may conflict with XML
<script language="php">    ?>            Always available, best if used when
                                         FrontPage is the HTML editor

<%                         %>            Not recommended. ASP tags support was
                                         added in 3.0.4
7




PHP reserved words
Keywords
   Reserved for language features
   if…elseif…else

PHP keywords
and            do        for        include   require   true
break          else      foreach    list      return    var
case           elseif    function   new       static    virtual
class          extends   global     not       switch    xor
continue       false     if         or        this      while
default




                                G. Ochoa, G64HLL
1    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4    <!-- Fig. 26.1: first.php -->
5    <!-- Our first PHP script -->
6                                               Scripting delimiters
7    <?php
8         $name = "LunaTic";   // declaration
9    ?>                                                           Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12        <head>
13           <title>A simple PHP document</title>Single-line   comment
14        </head>
15
16        <body style = "font-size: 2em">
17           <p>
18              <strong>
19
20                  <!-- print variable name’s value -->
21                  Welcome to PHP, <?php print( "$name" ); ?>!
22              </strong>
23           </p>
24        </body>
                                                               Function print outputs the value of variable
                                                               $name
25 </html>
Install
 If
   your server supports php you don‟t
  need to install php .
 You need only to create [*.php] files in the
  web directory of the server .
 Most of servers nowadays, support php
  parsing.
Install
 We  will use Wamp Server
 Install Wamp x64 or x32 .
 Install it in the default directory
  “c:Wamp”
 Within the install .. Installer will ask you the
  browser you want .. Choose it if you want
  or click open to choose the default action
      (as the image in the next slide).
 Run WampServer.exe from C:Wamp
Hello World
 Make  a new folder in the directory
  “C:WampWWW” named “my first
  project”
 Create a new file “Hello world.php” and
  open it using any text editor (notepad++
 recommended)

 Write this line then save:
<?php echo “Hello World” ?>
Server Parses the file
 Go   to local host (using wamp tray icon)
Variables in php
   Variables are used for storing a values, like text
    strings, numbers or arrays.
   A variable name must start with a letter or an
    underscore "_"
   A variable name can only contain alpha-numeric
    characters and underscores (a-z, A-Z, 0-9, and _ )
   A variable name should not contain spaces. If a
    variable name is more than
   one word, it should be separated with underscore
    ($my_string), or with
   All variables in PHP start with a $ sign symbol.
   $myText= “the text” ;
   $myNumber= 6 ;
   $myDate= date("d/m/Y");
   echo $myText."<br>".$myNumber."<br>".$myDate."<br>"."Hello!!";
Operations on variables
Strings:
 Strlen(“mystring”):returns the length of a string
 strpos(“hello world”,”hello”):returns the
  position of a substring in a string.
 Use „.‟ to concatenate 2 or more strings :
echo ”hello ”. “world”;
 $mystring[0]:returns first character
Operations on variables
Date:
 Date(“m”):returns month
  number(“d”day,”y”year in 2 digits (98
  stands for 1998))
 Date(“M”):returns month name („‟D”day
  name Ynormal 4 digits)
 Formatting date :Date(“d/m/Y”) , Date(“d-M-
  Y”) , Date(“D.M.Y”),…
 $tomorrow=mktime(0,0,0,date("m"),date("d")+
  1,date("Y"));
    echo “tomorrow is ”. Date(“d/M/Y”);
Operations on variables
 Arithmetic   operation on numbers
Operations on variables
 Assignment   operation
Operations on variables
 Comparing   operation




 Comparing   operation on numbers
Arrays
What is an array?
 When working with PHP, sooner or later, you might want
  to create many similar variables.
 Instead of having many similar variables, you can store
  the data as elements in an array.
   Numeric array - An array with a numeric ID key
   Associative array - An array where each ID key is associated
    with a value
   Multidimensional array - An array containing one or more
    arrays
Numeric arrays
 $names    = array("Peter","Quagmire","Joe");
assign the ID key manually:
 $names[0] = "Peter";
 $names[1] = "Quagmire";
 $names[2] = "Joe";
Example
 echo “first name is " . $names[0];
Output: first name is Peter
Associative array
 $ages array("Peter"=>32,"Quagmire"=>30,"Joe"=>34);
assign the ID key manually:
 $ages['Peter'] = "32";
 $ages['Quagmire'] = "30";
 $ages['Joe'] = "34"
Example:
echo "Peter is " . $ages['Peter'] . " years old.";
Output: Peter is 32 " years old.
Multidimensional array
  $families = array(
"Griffin"=>array("Peter","Lois","Megan"),
"Quagmire"=>array("Glenn"),
"Brown"=>array("Cleveland", "Loretta","Junior")
);
assign the ID key manually:
 $ families["Griffin“][1]="Lois";
 $ families[" Quagmire“][0]=" Glenn“;
 $ families[" Brown“][2]=" Junior“;
Example:

   echo "Is " . $families['Griffin'][2] ." a part of the Griffin family?";
If statement
if (condition1)
  code to be executed if condition1 is true;
Elseif (condition2)
  code to be executed if condition2 is true;
.
.
else
  code to be executed if neither condition1 nor condition2 is true;
Example:
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
elseif ($d=="Sun") echo "Have a nice Sunday!";
else echo "Have a nice day!";
?>
Output if today is Friday:Have a nice weekend!
Output if today is Sunday:Have a nice Sunday!
Else Output is: Have a nice day!
While loop
 while    (condition)
          code to be executed;
Example:
<?php
$i=1;
while($i<=5){
         echo "The number is " . $i . “ , ";
         $i++;}
?>
Output: 1 , 2 , 3 , 4 , 5 ,
For loop
 for (init; cond; incr){
 code to be executed;
}
Example:
<?php
for ($i=1; $i<=5; $i++){
  echo "Hello World!<br />";}
?>
//Prints Hello world 5 times
Printing array:
<?php
for ($i=0; $i<=5; $i++){
  echo arr[i] . "<br />";}
?>
//Prints first 5 items in the array ‘arr’
functions
   A function is a block of code that can be executed
    whenever we need it.
   Creating PHP functions:
   All functions start with the word "function()"
   Name the function - It should be possible to understand
    what the function does by its name. The name can start
    with a letter or underscore (not a number)
   after "{" - The function code starts
   after "}" - The function is finished
Function Examples
 Void function          (no return value):
function printHello(){
echo “Hello”;
}
printHello();

Output: Hello

function printName($name){
echo “Hello ”.$name.”!!”;
}
printName(“Hamada”);

Output: Hello Hamada!!
Function Examples
  Function returns value:
function add($first,$second){
$sum= $first+$second ;
return $sum;}
$K=add (1,2);

Output: K = 3

function concatenate($firstString,$secondString){
$newString= $firstString.$ secondString;
return $newString;}
$S = concatenate(“Hello ”,”World”);

Output: S =3
$_GET
   used to retrieve information from forms, like
    user input.
   The $_GET variable is used to collect values
    from a form with method="get".
   Information sent from a form with the GET
    method is visible to everyone (it will be
    displayed in the browser's address bar) and it
    has limits on the amount of information to
    send (max. 100 characters).
$_GET
 HTML file (Welcome.htm)
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
   PHP file (Welcome.php)
Welcome <?php echo $_GET["name"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
$_POST
 used  to retrieve information from forms,
  like user input.
 The $_POST variable is used to collect
  values from a form with method=“post".
 Information sent from a form with the
  POST method is invisible to everyone.
Cookies
   What is a Cookie?
   A cookie is often used to identify a user. A cookie is a small file that
    the
   server embeds on the user's computer. Each time the same
    computer requests
   a page with a browser, it will send the cookie too. With PHP, you
    can both
   create and retrieve cookie values.

How to Create a Cookie?
 The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax:
setcookie(name, value, expire, path, domain);
Cookies
     Setting cookie:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.
.
Getting cookie:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
 Checking if Cookies is set :
if( isset($_COOKIE["user"] )
 Deleting cookie: setcookie("user", "", time()-3600);
$_REQUEST
 The PHP $_REQUEST variable contains the
  contents of both $_GET, $_POST, and
  $_COOKIE.
 The PHP $_REQUEST variable can be used
  to get the result from form data sent with
  both the GET and POST methods.
Example (1):reversing a string
Reverse.htm:

 <form action="Reverse.php" method="get">
 the word: <input type="text" name=" TheWord" />
 <input type="submit" value = "reverse"/>
 </form>
Reverse.php


  The word Reversed is: <?php
  $myWord = $_GET["TheWord"];
  $newWord="";
  for ($i = strlen($myWord)-1 ;$i >= 0 ; $i--){
  $newWord .= $myWord[$i];
  }
  echo $newWord ;
  ?>
Example (1):reversing a string
(inside JavaScript)
  Reverse.htm:
   <form action="Reverse.php" method="get">
   the word: <input type="text" name=" TheWord" />
   <input type="submit" value = "reverse"/>
   </form>
  Reverse.php
    <script type = " text/javascript">
    window.alert("The word Reversed is: <?php
    $myWord = $_GET["TheWord"];
    $newWord="";
    for ($i = strlen($myWord)-1 ;$i >= 0 ; $i--){
    $newWord .= $myWord[$i];
    }
    echo $newWord ;
    ?>");
    </script>
     ..ThanQ
todo
   Write a form that user enter his name and birthday and php
    code that receives data and
 verify it (month number <=12 and so on )
 Calculate age (years ,days)
 Print all the leap years the user live in (year divisible by 4).
 Print a pyramid represents the user age in years
 Example:
if user is 3 years old (after calculation)
Output is:
.
..
…
Day1

Contenu connexe

Tendances

Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 
Unit 1 php_basics
Unit 1 php_basicsUnit 1 php_basics
Unit 1 php_basics
Kumar
 

Tendances (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
PHP
PHPPHP
PHP
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php
PhpPhp
Php
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Overview of PHP and MYSQL
Overview of PHP and MYSQLOverview of PHP and MYSQL
Overview of PHP and MYSQL
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Unit 1 php_basics
Unit 1 php_basicsUnit 1 php_basics
Unit 1 php_basics
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
01 Php Introduction
01 Php Introduction01 Php Introduction
01 Php Introduction
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 

Similaire à Day1

1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
jeeva indra
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 

Similaire à Day1 (20)

Php
PhpPhp
Php
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
php basics
php basicsphp basics
php basics
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Lecture8
Lecture8Lecture8
Lecture8
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
PHP
 PHP PHP
PHP
 

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Dernier (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 

Day1

  • 1. PHP Workshop Day1 Prepared by :Ahmed Mahmoud Saad
  • 2. Agenda 1. Introduction 2. Install 2. Getting started 3. Example
  • 3. 3 Introduction to PHP  PHP: Hypertext Preprocessor  Originally called “Personal Home Page Tools”  Popular server-side scripting technology  Open-source  Anyone may view, modify and redistribute source code  Supported freely by community  Platform independent G. Ochoa, G64HLL
  • 4. Brief History of PHP As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP Addresses http://www.php.net/usage.php This is roughly 32% of all domains on the web.
  • 5. Why is PHP used? 3. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free. PHP Software Free Platform Free (Linux) Development Tools Free PHP Coder, jEdit
  • 6. Getting Started How to escape from HTML and enter PHP mode .1 PHP parses a file by looking for one of the special tags that  tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. HTML PHP CODE HTML <?php echo “Hello World”; ?> Starting tag Ending tag Notes <?php ?> Preferred method as it allows the use of PHP with XHTML <? ?> Not recommended. Easier to type, but has to be enabled and may conflict with XML <script language="php"> ?> Always available, best if used when FrontPage is the HTML editor <% %> Not recommended. ASP tags support was added in 3.0.4
  • 7. 7 PHP reserved words Keywords Reserved for language features if…elseif…else PHP keywords and do for include require true break else foreach list return var case elseif function new static virtual class extends global not switch xor continue false if or this while default G. Ochoa, G64HLL
  • 8. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3 4 <!-- Fig. 26.1: first.php --> 5 <!-- Our first PHP script --> 6 Scripting delimiters 7 <?php 8 $name = "LunaTic"; // declaration 9 ?> Declare variable $name 10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 <head> 13 <title>A simple PHP document</title>Single-line comment 14 </head> 15 16 <body style = "font-size: 2em"> 17 <p> 18 <strong> 19 20 <!-- print variable name’s value --> 21 Welcome to PHP, <?php print( "$name" ); ?>! 22 </strong> 23 </p> 24 </body> Function print outputs the value of variable $name 25 </html>
  • 9. Install  If your server supports php you don‟t need to install php .  You need only to create [*.php] files in the web directory of the server .  Most of servers nowadays, support php parsing.
  • 10. Install  We will use Wamp Server  Install Wamp x64 or x32 .  Install it in the default directory “c:Wamp”  Within the install .. Installer will ask you the browser you want .. Choose it if you want or click open to choose the default action (as the image in the next slide).  Run WampServer.exe from C:Wamp
  • 11.
  • 12. Hello World  Make a new folder in the directory “C:WampWWW” named “my first project”  Create a new file “Hello world.php” and open it using any text editor (notepad++ recommended)  Write this line then save: <?php echo “Hello World” ?>
  • 13.
  • 14. Server Parses the file  Go to local host (using wamp tray icon)
  • 15.
  • 16. Variables in php  Variables are used for storing a values, like text strings, numbers or arrays.  A variable name must start with a letter or an underscore "_"  A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )  A variable name should not contain spaces. If a variable name is more than  one word, it should be separated with underscore ($my_string), or with  All variables in PHP start with a $ sign symbol.  $myText= “the text” ;  $myNumber= 6 ;  $myDate= date("d/m/Y");  echo $myText."<br>".$myNumber."<br>".$myDate."<br>"."Hello!!";
  • 17. Operations on variables Strings:  Strlen(“mystring”):returns the length of a string  strpos(“hello world”,”hello”):returns the position of a substring in a string.  Use „.‟ to concatenate 2 or more strings : echo ”hello ”. “world”;  $mystring[0]:returns first character
  • 18. Operations on variables Date:  Date(“m”):returns month number(“d”day,”y”year in 2 digits (98 stands for 1998))  Date(“M”):returns month name („‟D”day name Ynormal 4 digits)  Formatting date :Date(“d/m/Y”) , Date(“d-M- Y”) , Date(“D.M.Y”),…  $tomorrow=mktime(0,0,0,date("m"),date("d")+ 1,date("Y")); echo “tomorrow is ”. Date(“d/M/Y”);
  • 19. Operations on variables  Arithmetic operation on numbers
  • 20. Operations on variables  Assignment operation
  • 21. Operations on variables  Comparing operation  Comparing operation on numbers
  • 22. Arrays What is an array?  When working with PHP, sooner or later, you might want to create many similar variables.  Instead of having many similar variables, you can store the data as elements in an array.  Numeric array - An array with a numeric ID key  Associative array - An array where each ID key is associated with a value  Multidimensional array - An array containing one or more arrays
  • 23. Numeric arrays  $names = array("Peter","Quagmire","Joe"); assign the ID key manually:  $names[0] = "Peter";  $names[1] = "Quagmire";  $names[2] = "Joe"; Example  echo “first name is " . $names[0]; Output: first name is Peter
  • 24. Associative array  $ages array("Peter"=>32,"Quagmire"=>30,"Joe"=>34); assign the ID key manually:  $ages['Peter'] = "32";  $ages['Quagmire'] = "30";  $ages['Joe'] = "34" Example: echo "Peter is " . $ages['Peter'] . " years old."; Output: Peter is 32 " years old.
  • 25. Multidimensional array  $families = array( "Griffin"=>array("Peter","Lois","Megan"), "Quagmire"=>array("Glenn"), "Brown"=>array("Cleveland", "Loretta","Junior") ); assign the ID key manually:  $ families["Griffin“][1]="Lois";  $ families[" Quagmire“][0]=" Glenn“;  $ families[" Brown“][2]=" Junior“; Example:  echo "Is " . $families['Griffin'][2] ." a part of the Griffin family?";
  • 26. If statement if (condition1) code to be executed if condition1 is true; Elseif (condition2) code to be executed if condition2 is true; . . else code to be executed if neither condition1 nor condition2 is true; Example: <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> Output if today is Friday:Have a nice weekend! Output if today is Sunday:Have a nice Sunday! Else Output is: Have a nice day!
  • 27. While loop  while (condition) code to be executed; Example: <?php $i=1; while($i<=5){ echo "The number is " . $i . “ , "; $i++;} ?> Output: 1 , 2 , 3 , 4 , 5 ,
  • 28. For loop  for (init; cond; incr){ code to be executed; } Example: <?php for ($i=1; $i<=5; $i++){ echo "Hello World!<br />";} ?> //Prints Hello world 5 times Printing array: <?php for ($i=0; $i<=5; $i++){ echo arr[i] . "<br />";} ?> //Prints first 5 items in the array ‘arr’
  • 29. functions  A function is a block of code that can be executed whenever we need it.  Creating PHP functions:  All functions start with the word "function()"  Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)  after "{" - The function code starts  after "}" - The function is finished
  • 30. Function Examples  Void function (no return value): function printHello(){ echo “Hello”; } printHello(); Output: Hello function printName($name){ echo “Hello ”.$name.”!!”; } printName(“Hamada”); Output: Hello Hamada!!
  • 31. Function Examples  Function returns value: function add($first,$second){ $sum= $first+$second ; return $sum;} $K=add (1,2); Output: K = 3 function concatenate($firstString,$secondString){ $newString= $firstString.$ secondString; return $newString;} $S = concatenate(“Hello ”,”World”); Output: S =3
  • 32. $_GET  used to retrieve information from forms, like user input.  The $_GET variable is used to collect values from a form with method="get".  Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).
  • 33. $_GET  HTML file (Welcome.htm) <form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>  PHP file (Welcome.php) Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
  • 34. $_POST  used to retrieve information from forms, like user input.  The $_POST variable is used to collect values from a form with method=“post".  Information sent from a form with the POST method is invisible to everyone.
  • 35. Cookies  What is a Cookie?  A cookie is often used to identify a user. A cookie is a small file that the  server embeds on the user's computer. Each time the same computer requests  a page with a browser, it will send the cookie too. With PHP, you can both  create and retrieve cookie values. How to Create a Cookie?  The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax: setcookie(name, value, expire, path, domain);
  • 36. Cookies  Setting cookie: <?php setcookie("user", "Alex Porter", time()+3600); ?> <html> . . Getting cookie: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>  Checking if Cookies is set : if( isset($_COOKIE["user"] )  Deleting cookie: setcookie("user", "", time()-3600);
  • 37. $_REQUEST  The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.  The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
  • 38. Example (1):reversing a string Reverse.htm: <form action="Reverse.php" method="get"> the word: <input type="text" name=" TheWord" /> <input type="submit" value = "reverse"/> </form> Reverse.php The word Reversed is: <?php $myWord = $_GET["TheWord"]; $newWord=""; for ($i = strlen($myWord)-1 ;$i >= 0 ; $i--){ $newWord .= $myWord[$i]; } echo $newWord ; ?>
  • 39. Example (1):reversing a string (inside JavaScript) Reverse.htm: <form action="Reverse.php" method="get"> the word: <input type="text" name=" TheWord" /> <input type="submit" value = "reverse"/> </form> Reverse.php <script type = " text/javascript"> window.alert("The word Reversed is: <?php $myWord = $_GET["TheWord"]; $newWord=""; for ($i = strlen($myWord)-1 ;$i >= 0 ; $i--){ $newWord .= $myWord[$i]; } echo $newWord ; ?>"); </script> ..ThanQ
  • 40. todo  Write a form that user enter his name and birthday and php code that receives data and  verify it (month number <=12 and so on )  Calculate age (years ,days)  Print all the leap years the user live in (year divisible by 4).  Print a pyramid represents the user age in years  Example: if user is 3 years old (after calculation) Output is: . .. …