SlideShare une entreprise Scribd logo
1  sur  250
Télécharger pour lire hors ligne
Enjoy PHPing!




                 PHP Beginner & Intermediate
          ATHENA TRAINING & EDUCATION CENTER
                                               2
TABLE OF CONTENTS

   Chapter 1. Web Design Basic ..........................................................................................7
      Web Design Toolbox..................................................................................................... 9
      HTML Editor – Dreamweaver CS3 .............................................................................. 16
      HTML Basics................................................................................................................ 22
      HTML Form ................................................................................................................. 23
      CSS .............................................................................................................................. 27
      Javascript .................................................................................................................... 28

   Chapter 2. PHP Workspace ...........................................................................................31
      PHP Introduction ........................................................................................................ 33
      AppServ Installation ................................................................................................... 35
      Using AppServ ............................................................................................................ 37
      PHP IDE - PhpEd.......................................................................................................... 38
      Using PHP Interactive ................................................................................................. 42

   Chapter 3. PHP Basics ...................................................................................................45
      PHP Syntax.................................................................................................................. 47
      Data Types .................................................................................................................. 48
      Variable & Constant ................................................................................................... 49
      Operators ................................................................................................................... 50
      Control Structure ........................................................................................................ 51

   Chapter 4. Function ......................................................................................................55
      Introduction................................................................................................................ 57
      Syntax ......................................................................................................................... 57
      Parameter & Argument .............................................................................................. 58
      Useful Functions ......................................................................................................... 61

   Chapter 5. Array ...........................................................................................................63
      Declaration ................................................................................................................. 65
      Array Operation .......................................................................................................... 65
      Iteration (Looping)...................................................................................................... 67
      Sorting ........................................................................................................................ 68
      More Functions .......................................................................................................... 70

   Chapter 6. String Manipulation ....................................................................................73
      Declaration ................................................................................................................. 75
      Comparision ............................................................................................................... 75
      Searching .................................................................................................................... 76
      Replacement............................................................................................................... 76
      Splitting....................................................................................................................... 77
      Formatting .................................................................................................................. 78
      Regular Expression – RegEx ........................................................................................ 79
                                                                                                     PHP Beginner & Intermediate
                                                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                                                                              3
Chapter 7. HTTP Basic...................................................................................................83
   HTTP Fundamentals.................................................................................................... 85
   File Upload.................................................................................................................. 88
   Cookie ......................................................................................................................... 90
   Session ........................................................................................................................ 91

Chapter 8. OOP – Object Oriented Programming .........................................................93
   OOP Fundamentals..................................................................................................... 95
   Properties ................................................................................................................... 96
   Methods ..................................................................................................................... 97
   Inheritance & Overriding .......................................................................................... 101

Chapter 9. File Handling ............................................................................................. 107
   File Handle ................................................................................................................ 109
   File Manipulation...................................................................................................... 110
   Directory ................................................................................................................... 112
   File & Directory Constants........................................................................................ 113

Chapter 10. MySQL..................................................................................................... 115
   DBMS Fundamentals ................................................................................................ 117
   MySQL Fundamentals............................................................................................... 118
   MySQL Basics ............................................................................................................ 122
   Using phpMyAdmin .................................................................................................. 125
   MySQL in PHP ........................................................................................................... 138

Chapter 11. Logging & Debugging .............................................................................. 141
   Log Configuration ..................................................................................................... 143
   PhpEd Debugger Installation .................................................................................... 143
   Debugging................................................................................................................. 145

Chapter 12. OOP Advanced ........................................................................................ 149
   Interface ................................................................................................................... 151
   Abstract Class, Method ............................................................................................ 152
   Final Class, Method .................................................................................................. 153
   Lazy Loading ............................................................................................................. 154
   Magic Methods......................................................................................................... 154

Chapter 13. MySQL Advanced .................................................................................... 159
   Table Joining ............................................................................................................. 161
   PHP Data Object (PDO) ............................................................................................. 164

Chapter 14. Software Engineering Basic ..................................................................... 167
   Requirement Gathering............................................................................................ 169
   Use-Case Diagram .................................................................................................... 171
   Class Diagram ........................................................................................................... 177

                                                                                                 PHP Beginner & Intermediate
                                                                                     ATHENA TRAINING & EDUCATION CENTER
                                                                                                                                         4
Chapter 15. XML & Web Service ................................................................................. 181
   XML Basics ................................................................................................................ 183
   SimpleXML Class ....................................................................................................... 184
   Web Services Basics.................................................................................................. 185
   SOAP ......................................................................................................................... 186
   JSON Overview ......................................................................................................... 189

Chapter 16. Security ................................................................................................... 191
   Security Basics .......................................................................................................... 193
   Database Security ..................................................................................................... 193
   Website Security....................................................................................................... 194
   Session Security ........................................................................................................ 199
   File System Security.................................................................................................. 201

Chapter 17. Advanced PHP Topics .............................................................................. 203
   PHP.INI File Overview ............................................................................................... 205
   Date & Time.............................................................................................................. 206
   Email Sending ........................................................................................................... 208
   Image Processing ...................................................................................................... 209
   cURL library .............................................................................................................. 210
   Smarty ...................................................................................................................... 211
   Different between PHP5 & PHP4 ............................................................................. 212

Chapter 18. Design Pattern ........................................................................................ 215
   Fundamentals ........................................................................................................... 217
   Singleton Pattern ...................................................................................................... 217
   Factory Pattern ......................................................................................................... 218
   Strategy Pattern ....................................................................................................... 220
   Model-View-Controller (MVC) Pattern .................................................................... 221

Chapter 19. E-Commerce Website .............................................................................. 225
   E-Commerce Fundamentals ..................................................................................... 227
   Website Optimization............................................................................................... 228
   SEO Basics ................................................................................................................. 228
   Website Analytic – Google Analytic Setup ............................................................... 230

Chapter 20. Zend PHP 5 Certification – ZCE (Zend Certified Engineer)........................ 243
   Zend Certification Introduction ................................................................................ 245
   Zend PHP 5 Certification Exam ................................................................................. 246

Further Reading.......................................................................................................... 249
UseFul Websites ......................................................................................................... 250




                                                                                                PHP Beginner & Intermediate
                                                                                     ATHENA TRAINING & EDUCATION CENTER
                                                                                                                                        5
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     6
Chapter 1
Web Design
Basics
Keywords: Web design, editor, tool, photo, form, html, tag, style,
  javascript.


Subjects:
  1.1. Web Design Toolbox
  1.2. HTML Editor – Dreamweaver CS3
  1.3. HTML Basics
  1.4. HTML Form
  1.5. CSS
  1.6. Javascript




                                                      PHP Beginner & Intermediate
                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                    7
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     8
1.1. Web Design Toolbox:
   1.1.1. Image Manipulating: Photoshop, GIMP, Illustrator…




                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      9
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     10
1.1.2. Animation Creator: Photoshop, Flash, Flex, Maya, 3DS Max…




                                                    PHP Beginner & Intermediate
                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                  11
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     12
1.1.3. HTML Editor: Dreamweaver, Notepad++…




                                                PHP Beginner & Intermediate
                                         ATHENA TRAINING & EDUCATION CENTER
                                                                              13
1.1.4. CSS Editor: Dreamweaver, Rapid CSS, Notepad++…




                                                  PHP Beginner & Intermediate
                                           ATHENA TRAINING & EDUCATION CENTER
                                                                                14
1.1.5. Javascript Editor: Dreamweaver, 1st Javascript Editor, Notepad++…




                                                      PHP Beginner & Intermediate
                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                    15
1.2. HTML Editor – Dreamweaver CS3:
  - Main Dreamweaver CS3 interface




  - Auto-complete function




  - Collapse selected script:




                                             PHP Beginner & Intermediate
                                      ATHENA TRAINING & EDUCATION CENTER
                                                                           16
- Property Inspector Panel:




- Create a Local Site:




Or:




                                     PHP Beginner & Intermediate
                              ATHENA TRAINING & EDUCATION CENTER
                                                                   17
Or:




- After creating site, the FILES panel will become:




                                                             PHP Beginner & Intermediate
                                                      ATHENA TRAINING & EDUCATION CENTER
                                                                                           18
- Open an Local Site:




- Manage Site Files: In the Files Panel, right click the root (top level) and select your function
   (New File, New Folder…)




                                                                      PHP Beginner & Intermediate
                                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                                     19
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     20
- Create new file




                           PHP Beginner & Intermediate
                    ATHENA TRAINING & EDUCATION CENTER
                                                         21
1.3. HTML Basics:
  1.3.1. HTML Structure:
    <html>
       <head>
       <title>Four Square Cafe</title>
       </head>

       <body>
       Four Square Café is located at the intersection of Melrose and Sunset Avenues in Los
       Angeles. We are a cafe with our own bakery, and also have a charcuterie for your favorite
       meats and cheeses. We offer breakfasts and made to order sandwiches. You can buy fresh,
       hot from the oven bread for your home twice a day, at 8 am and 5 am daily. In our Café,
       we are also famous for fresh organic coffee and tea made with mountain water. Each cup
       is in its own single cone and paper filter and dripped right into your cup. We then start
       over for the next customer.

       Today's Specials
       ....................content deleted ..............................


       </body>
       </html>




                                                                              PHP Beginner & Intermediate
                                                                       ATHENA TRAINING & EDUCATION CENTER
                                                                                                            22
1.3.2. Popular HTML Tag:
  - Break line: br

  - Heading: h1, h2, h3, h4, h5, h6.

  - Paragraph: p

  - Link: a

  - Image: img

  - Text formatting: b, i, strong

  - Tables: table, tr, th, td

  - List: ul, ol, dl, li

  - Form: form, input, textarea, select

  - DIV, SPAN Tag: div, span

  1.3.3. HTML Meta Tag:
      <meta name="description" content="Free Web tutorials" />
         <meta name="keywords" content="HTML,CSS,XML,JavaScript" />
         <meta name="author" content="Duy Tuan" />
      <meta http-equiv="refresh" content="4;URL=http://example.com/">
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />



1.4. HTML Form:
      1.4.1. Using Dreamweaver to insert Form element:




                                                          PHP Beginner & Intermediate
                                                   ATHENA TRAINING & EDUCATION CENTER
                                                                                        23
1.4.2. Form Elements:
  1.4.2.1. Text Field:
      <form method="post" action="mailto:youremail@email.com">
      Name: <input type="text" size="10" maxlength="40" name="name">
         <br />
      Password: <input type="password" size="10" maxlength="10"
         name="password">
      </form>




  1.4.2.2. Button:
      <form method="post" action="mailto:youremail@email.com">
      Name: <input type="text" size="10" maxlength="40" name="name">
         <br />
      Password: <input type="password" size="10"
      maxlength="10" name="password"><br />


                                                   PHP Beginner & Intermediate
                                            ATHENA TRAINING & EDUCATION CENTER
                                                                                 24
<input type="submit" value="Send">
    </form>




1.4.2.3. Radio button:
    <form method="post" action="mailto:youremail@email.com">
     What kind of shirt are you wearing? <br />
     Shade:

      <input type="radio" name="shade" value="dark">Dark
      <input type="radio" name="shade" value="light">Light <br />
      Size:

     <input   type="radio" name="size" value="small">Small
     <input   type="radio" name="size" value="medium">Medium
     <input   type="radio" name="size" value="large">Large <br />
     <input   type="submit" value="Email Myself">
    </form>




1.4.2.4. Check box:
    <form method="post" action="mailto:youremail@email.com">
    Select your favorite cartoon characters.
     <input type="checkbox" name="toon" value="Goofy">Goofy
     <input type="checkbox" name="toon" value="Donald">Donald
     <input type="checkbox" name="toon" value="Bugs">Bugs Bunny
     <input type="checkbox" name="toon" value="Scoob">Scooby Doo
     <input type="submit" value="Email Myself">
    </form>




1.4.2.5. Dropdown list:
    <form method="post" action="mailto:youremail@email.com">
    College Degree?
     <select name="degree">
       <option>Choose One</option>
       <option>Some High School</option>
       <option>High School Degree</option>
                                                   PHP Beginner & Intermediate
                                            ATHENA TRAINING & EDUCATION CENTER
                                                                                 25
<option>Some College</option>
       <option>Bachelor's Degree</option>
       <option>Doctorate</option>
     </select>
       <input type="submit" value="Email Yourself">
    </form>




1.4.2.6. Selection form:
    <form method="post" action="mailto:youremail@email.com">
    Musical Taste
     <select multiple name="music" size="4">
       <option value="emo" selected>Emo</option>
       <option value="metal/rock" >Metal/Rock</option>
       <option value="hiphop" >Hip Hop</option>
       <option value="ska" >Ska</option>
       <option value="jazz" >Jazz</option>
       <option value="country" >Country</option>
       <option value="classical" >Classical</option>
       <option value="alternative" >Alternative</option>
       <option value="oldies" >Oldies</option>
       <option value="techno" >Techno</option>
     </select>
     <input type="submit" value="Email Yourself">
    </form>




1.4.2.7. Upload form:
    <input type="hidden" name="MAX_FILE_SIZE" value="100" />
    <input name="file" type="file" />




1.4.2.8. Text Area:
    <form method="post" action="mailto:youremail@email.com">
    <textarea rows="5" cols="20" name="comments">
    Enter Comments Here
    </textarea>
    <input type="submit" value="Email Yourself">
    </form>
                                                 PHP Beginner & Intermediate
                                          ATHENA TRAINING & EDUCATION CENTER
                                                                               26
1.5. CSS:
 1.5.1. CSS Selector:
 - The selector name creates a direct relationship with the HTML tag you want to edit.

 - Many types of selector: type, class, id, child, universal…

 - Ex: <div id="container" class="bluebox largebox">…</div>



 1.5.2. CSS Syntax:
 SELECTOR { PROPERTY: VALUE }




 1.5.3. Embed CSS to HTML page:
 - Internal CSS:
     <style type="text/css">
        p {color: white; }
        body {background-color: black; }
     </style>

 - External CSS:
     <link rel="stylesheet" type="text/css" href="test.css" />

 - Inline CSS:
     <p style="background: blue; color: white;">
        Text
     </p>




                                                                       PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                     27
1.6. Javascript:
 1.6.1. Embed Javascript to HTML page:
 - Internal:
      <script type="text/javascript">
         //script here
      </script>

 - External:
      <script type="text/javascript" src="file.js"></script>

 - Inline:
      <img src="button.gif" onclick="alert('test');" />




 1.6.2. Javascript Basics:
   1.6.2.1. Comments:
               // this is a comment
               /* so is
               this */

   1.6.2.2. Function:
               function anExample(param1,param2)
               {
               alert(param1+param2);
               }
               <a href="javascript:void(0)" onClick="anExample("Ec","Lios") >
                  Example </a>

   1.6.2.3. IF Statement:
               function anIfExample(param)
               {
                 if (param==1)
                  {alert("Hello Philip");}
                 else if (param==2)
                  {alert("Hello Terrance");}
                 else
                  {alert("Hello everyone");}
               }
               <a href="javascript:void(0)" onClick="anIfExample(1)" > Example
                  1</a> <br>
               <a href="javascript:void(0)" onClick="anIfExample(1)" > Example
                  2</a> <br>
               <a href="javascript:void(0)" onClick="anIfExample(2)" > Example
                  3</a>

                                                             PHP Beginner & Intermediate
                                                      ATHENA TRAINING & EDUCATION CENTER
                                                                                           28
1.6.2.4. SWITCH Statement:
         function aSwitchExample(param)
         {
           switch(param)
           {
           case 1:
             alert("Hello John");
             break;
           case 2:
             alert("Hello Peter");

           case 3:
             alert("Hello Moose");
             break;
           default:
             alert("ahhh no moosi");
           break;
           }
         }
         <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example
            1</a> <br>
         <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example
            2</a> <br>
         <a href="javascript:void(0)" onClick="aSwitchExample(2)" > Example
            3</a>

1.6.2.5. WHILE Statement:
         function aWhileExample(param)
         {

           counter=0;
           while(counter<param)
           {
             alert("round we go " + counter);
             counter++;
             // this adds one to the counter, could have typed
             // counter=counter+1;
           }
         }
         <a href="javascript:void(0)" onClick="aWhileExample(0)" > Example
            1</a> <br>
         <a href="javascript:void(0)" onClick="aWhileExample(1)" > Example
            2</a> <br>
         <a href="javascript:void(0)" onClick="aWhileExample(3)" > Example
            3</a>

1.6.2.6. DO Statement:
         function aDoExample(param)
         {

           counter=0;
           do
           {
              alert("round we go " + counter);
              counter++;

                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      29
// this adds one to the counter, could have typed
             // counter=counter+1;
           }
           while (counter<param)
        }
        <a href="javascript:void(0)" onClick="aDoExample(0)" > Example
           1</a> <br>
        <a href="javascript:void(0)" onClick="aDoExample(1)" > Example
           2</a> <br>
        <a href="javascript:void(0)" onClick="aDoExample(3)" > Example
           3</a>

1.6.2.7. FOR Statement:
        function aForExample(param)
        {
          for(counter=0; counter<param; counter++)
          {
             alert("round we go " + counter);
          }
        }
        <a href="javascript:void(0)" onClick="aForExample(0)" > Example
            1</a> <br>
        <a href="javascript:void(0)" onClick="aForExample(1)" > Example
            2</a> <br>
        <a href="javascript:void(0)" onClick="aForExample(3)" > Example
            3</a>




                                                       PHP Beginner & Intermediate
                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                     30
Chapter 2
PHP
Workspace
Keywords: installation, IDE, server-side, scripting, interpreter,
  opensource, CLI, service, GUI, code navigator, DB Client, php
  interactive, request, response.


Subjects:
  2.1. PHP Introduction
  2.2. AppServ Installation
  2.3. Using AppServ
  2.4. PHP IDE - PhpEd
  2.5. Using PHP Interactive




                                                      PHP Beginner & Intermediate
                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                    31
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     32
2.1. PHP Introduction:
- How PHP Works:




- PHP stands for "PHP Hypertext Preprocessor"
- PHP is a widely used open source. Stable version is PHP 5.3.0 (PHP6 beta)
- Runs on Server -> Server-Side Scripting language
- It's fast, free, easy to use, run on many Operating Systems(OS), secure, customizable, support
     community.
- PHP supports many database (MySQL, Oracle, Sybase, PostgreSQL…)
- File extension: ".php", ".php3", ".php5" or ".phtml"




                                                                       PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                     33
interacting via browser




Working via CLI (command-line interface)




Working via GUI(Graphical User Interface) – Desktop Application




                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      34
Working via web services (no need interface)




2.2. AppServ Installation:
- It will install Apache, PHP, MySQL in one window executive file (.exe)
- Best solution for creating an environment to learning, developing and testing website.
- Download AppServ at: http://www.appservnetwork.com/
- Install like a normal window application.




                                                                       PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                     35
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     36
2.3. Using AppServ:
 2.3.1. AppServ 2.10 Directory Structure:




                                                   PHP Beginner & Intermediate
                                            ATHENA TRAINING & EDUCATION CENTER
                                                                                 37
2.3.2. Edit Server config using start menu:




 2.3.3. Restart/ Stop / Start Apache / MySQL Services using start menu:




2.4. PHP IDE - PhpEd
 - Main Software interface:

    + Menu Bar

    + Toolbar (File, navigator, HTML element, Debugger…)

    + Code Explorer Panel (Left)

    + Source code editor (Center)

    + Code navigator Panel (Rignt)




                                                                  PHP Beginner & Intermediate
                                                           ATHENA TRAINING & EDUCATION CENTER
                                                                                                38
- Some main features:

   + Autocomplete code:




                                 PHP Beginner & Intermediate
                          ATHENA TRAINING & EDUCATION CENTER
                                                               39
+ Full screen support

+ Database Client




+ Support HTML, CSS, JS language


                                          PHP Beginner & Intermediate
                                   ATHENA TRAINING & EDUCATION CENTER
                                                                        40
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     41
+ Debuging & Profiling tool




    + Collapse / Expand Selected code.




2.5. Using PHP Interactive
 2.5.1. Introduction:
 PHP Interactive is a simple PHP program that lets the user to write code in a text area (actually
   multiple text areas, with tabs to switch), and see the output of the code just pressing the
   update button. The scripts are persistent, and the program supports a raw and html output
   mode, in order to see the raw script output or to interpret it as html.




                                                                      PHP Beginner & Intermediate
                                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                                     42
2.5.2. Installation:
- Download at: http://www.hping.org/phpinteractive/

- Unzip and copy to www folder and rename to "phpa".




                                                              PHP Beginner & Intermediate
                                                       ATHENA TRAINING & EDUCATION CENTER
                                                                                            43
- Access php interactive using URL: http://localhost/phpa/




                                                                    PHP Beginner & Intermediate
                                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                                  44
Chapter 3
PHP Basics
Keywords: syntax, data type, variable, constant, type casting, operator,
  control structure, condition, loop, precidence, priority, expression.


Subjects:
  3.1. PHP Syntax
  3.2. Data Types
  3.3. Variable & Constant
  3.4. Operators
  3.5. Control Structure




                                                       PHP Beginner & Intermediate
                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                     45
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     46
3.1. PHP Syntax:
 3.1.1. PHP Tags:
 - PHP code can be inserted directly into a text file (.php…). The interpreter will output any
     text outside the tags, and execute the code that is between the tags




 3.1.2. PHP Source code:
 - Every PHP script is made up of statements: function calls, variable assignments, data
     output…Most of the time, these statements must be terminatd with a semicolon(;). PHP is
     whitespace-intensitive.

 3.1.3. Comments:
 - PHP has many types of comment
     //Single line comment

     #Single line comment

     /* Multi-line
     comment
     */

     /**
     * API Documentation Example
     *
     * @param string $bar
     */
     Function foo($bar){}



    <?php    //this is the end tag "?>" of PHP ?>
                                                                      PHP Beginner & Intermediate
                                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                                    47
3.1.4. Code Block: is a series of statements enclosed between two braces
     {
             //Some comments
             f(); //a function call
     }


3.2. Data Types:
 3.2.1. Numeric Value:
 - Integer numbers:

 . Decimal: normally used numbers. Ex: 10; -100… (invalid: 1 000)

    . Octal: begin with zero. Ex: 0666; 0777…

    . Hexadecimal: Begin with "0x" or "0X". Ex: 0x12; 0xAF; 0XFF…

 - Floating-point numbers: have a fractional component.

    . Decimal: 0.12; 3.45…

    . Exponential: 4E6; 1e2…

 3.2.2. String: A series of single characters, such as Vietnam.

 3.2.3. Boolean: A TRUE or FALSE value.

 3.2.4. Array: can store any other data type.

 3.2.5. Object: containers of both data and code.

 3.2.6. Other types:
 - NULL : indicates that a variable has no value.

 - resource: used to indicate external resources. Such as handing files, manipulating images

 3.2.7.Type casting: can be done automatically or manually.
 Ex: $a = 1.5; $b = (int)$a; // $b will be assigned 1




                                                                    PHP Beginner & Intermediate
                                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                                  48
3.3. Variable & Constant:
 3.3.1. Variables:
 - Can contain any type of data, such as strings, integers, objects, arrays…PHP is loosely typed.

 - Identified by a dollar sign $

 - Variable name must be using only letters (a-z, A-Z), numbers and the underscore character
    "_".

 - Variable name must start with a letter or an underscore

 - Case-sensitive.

 - Examples:
      $var = "ok"; // Valid name
      $_var = "ok"; // Valid name
      $4var = "not ok"; //Invalid name, starts with a number

 3.3.2. Variable Variables:
 - Variable whose name is contained in another variable. Example:
      $var = 'name';
      $$var = 'I love php';
      echo $name; // Displays 'I love php'

 3.3.3. Constants:
 - Can be accessed for any scope within a script

 - They can only contain numeric values, strings and booleans.

 - Naming like rule of variable name, but not start with dollar sign $

 - It's usually defined constants using only upper-case names.

 - Examples:
      define('EMAIL', 'myemail@example.com');
      echo EMAIL; // Displays 'myemail@example.com'
      define('5CLASS, 'some value); // Invalid name




                                                                         PHP Beginner & Intermediate
                                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                                       49
3.4. Operators:
 3.4.1. Assignment Operator: assigning data to variables. Ex:
     $a = 1; // Assign the integer 1 to $a
 3.4.2. Arithmetic Operators: performing basic math functions. Ex:
     $a = 5 + 6;
     $b = $a – 1;
 3.4.3. String Operators: joining two or more strings. Ex:
     $myString = 'hello' . '-' . 'world';
     // $myString will be string 'hello-world'
 3.4.4. Comparison Operators: comparing two pieces of data. Ex:
     $a = 10;
     echo $a == 10;      // outputs 1
 3.4.5. Logical Operators: performing logical operations on Boolean values.
     $a = false;
     echo !$a; //outputs 1

 3.4.6. Bitwise Operators: manipulating bits using boolean math. Ex:
     $x = 1;
     echo $x << 1; // Outputs 2;
     echo $x << 2; // Outputs 4;

 3.4.7. Error Control Operators: Suppressing errors. Prepending @ to an expression,
    this operator causes PHP to ignore almost all error messages that occur that expression is
    being evaluated. Ex:
     $x = @mysql_connect();

 3.4.8. Execution Operators: executing system commands. Backtick operator (`) makes
    it possible to execute a shell command and retrieve its output. Ex:
     echo `dir c:`;
     // outputs info like open command window, type "dir c:"

 3.4.9. Incrementing/Decrementing Operators: incrementing and decrementing
    numerical values. Ex:
     $a = 1;
     echo $a++;     // Outputs 1, $a is now equal to 2
     echo ++$a;     //Outputs 3, $a is now equal to 3




                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                   50
3.4.10. Type Operators:       instanceof operator       is used to determine whether a PHP
    variable is an instantiated object of a certain class. Ex:
     echo $a instanceof MyClass;

 3.4.11. Operator Precedence and Associativity:




3.5. Control Structure:
 3.5.1. Conditional Structures:
   3.5.1.1. If…Else Statement:
     if (condition_1) {
            statement_1
        }
        [elseif (condition_2) {
            statement_2
        }]
        ...
        [elseif (condition_n_1) {
            statement_n_1

                                                                      PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                    51
}]
        [else {
           statement_n
        }]



  3.5.1.2. Switch Statement:
   switch (expression) {
         case label_1:
             statements_1
             [break;]
         case label_2:
             statements_2
             [break;]
         ...
         default:
           statements_n
           [break;]
      }




3.5.2. Loop Structures:
  3.5.2.1. While Loop:
   while (condition)
      {
        code to be executed;
      }



  3.5.2.2. Do…While Loop:
   do
        {
            code to be exected;
        }
        while (condition);



  3.5.2.3. For Loop:
   for (initialization; condition; increment)
      {
         code to be executed;
      }




                                                       PHP Beginner & Intermediate
                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                     52
3.5.2.4. Foreach Loop:
      foreach (array as value)
         {
            code to be executed;
         }

          foreach (array as key => value)
          {
             code to be executed;
          }




  3.5.3. Break & Continue Statements
    3.5.3.1. break: used to immediately exit a loop. It takes an optional parameter, which
        allows you to exit from multiple nested loops. Ex:
      $i = 0;
         $j = 0;

          while ($i < 10) {
            while ($j < 10) {
              if ($j == 5) {break 2;} // breaks out of two while loops
              $j++;
            }
            $i++;
          }



    3.5.3.2. continue: want to skip over the remainder of an iteration and immediately skip
        over to the next. Like with break, you can provide it an integer parameter to specify the
        level of nesting to which the it applies. Ex:
      for ($i=0; $i<=10; $i++) {
            if (i==3){continue;}
            echo "The number is ".$i;
            echo "<br />";
         }




Chapter Exercise:

   A> Research typing casting on resource data type.

   B> What is the function used to check a declared variable? Is it always true in all situations?



                                                                        PHP Beginner & Intermediate
                                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                                      53
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     54
Chapter 4
Functions
Keywords: function, parameter, argument, reference, value, global,
  static, scope, return, null, empty, language construct.


Subjects:
  4.1. Introduction
  4.2. Syntax
  4.3. Parameter & Argument
  4.4. Useful Functions




                                                     PHP Beginner & Intermediate
                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                   55
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     56
4.1. Introduction:
   - Function is the heart of PHP programming.

   - Encapsulate any piece of code in a way that it can be called again and again.

   - Classify between Language constructs and Functions.

           •   Fastest things in PHP are the language constructs.
           •   They are highly optimized in the interpreter
           •   Don’t require calling external libraries
           •   Don’t call a function if there is a language construct. As an example, using a
               casting operator like (int) $total is much more efficient than using the function
               intval($foo)
           •   Function calling generate considerably amount of overhead. Using a language
               construct avoid
           •   isset() and unset() are both language constructs, even though they mostly act like
               functions. However calling them does not generate the function overhead.
           •   Common language construct:
                        echo()
                        empty()
                        isset()
                        unset()
                        eval()
                        exit()
                        die()
                        include()
                        include_once()
                        require()
                        require_once()
                        return

4.2. Syntax:
 4.2.1. Create function: function name is case-intensitive.
     function name()
     {
     //your code here
     }


     Ex:
     function hello()
     {
        echo 'Hello World';
     }
     hello(); // Displays "Hello World";
     HeLLo(); // Displays "Hello World";

                                                                       PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                     57
4.2.2. Return values:
 - All functions in PHP return a value (event if you don't using return keyword, it will return
     NULL)

 - return keyword allows you to interrupt the execution of a function and exit it.

 - Ex:
     function hello()
     {
        return 'Hello World';
     }
     $str = hello(); // Assigns return value "Hello World" to $str
     echo hello(); // Displays "Hello World"



 - Functions can be declared so that they return by reference, usually resource type. Ex:
     function &query()
     {
        $result = mysql_query('SELECT email FROM users');
        return $result;
     }




4.3. Parameter & Argument:
 4.3.1. Different between Parameter and Argument:

 - The term parameter refers to any declaration within the parentheses following the function
     name in a function declaration or definition; the term argument refers to any expression
     within the parentheses of a function call.

  - This example demonstrates the difference between a parameter and an argument:


         // $var is a parameter
         function test($var)
         {
               foo(5, 'a'); //5 and 'a' are arguments
               return 0;
         }




 4.3.2. Passing by value: by default, function arguments are passed by value (so that if the
    value of the argument within the function is changed, it does not get changed outside of
    the function). Ex:

                                                                      PHP Beginner & Intermediate
                                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                                    58
function myFunc($str)
    {
       $str = 'bob';
       echo $str;
    }
    $str = 'jack';
    myFunc($str); // Displays "bob"
    echo $str; // Displays 'jack'



4.3.3. Passing by reference: to allow function to modify its arguments, they must be
   passed by reference.Ex:
    function myFunc(&$str)
    {
       $str = 'bob';
       echo $str;
    }
    $str = 'jack';
    myFunc($str); // Displays "bob"
    echo $str; // Displays 'bob


4.3.4. Default argument values: Set default value for an argument if it's not passed to
   function. Ex:
    function myFunc($str = 'mother')
    {
       echo $str;
    }
    $str = 'jack';
    myFunc($str); // Displays "jack"
    myFunc(); // Displays "mother"



   Question: What will output when running this script?
    function myFunc(&$str = 'mother')
    {
       //
    }
    $str = 'jack';
    myFunc($str);
    echo $str;


4.3.5. Variable Scope: is the context within which it is defined. Most part all PHP
   variables only have a single scope. View this script:
    $a = 1; /* global scope */
       function test()
       {

                                                                  PHP Beginner & Intermediate
                                                           ATHENA TRAINING & EDUCATION CENTER
                                                                                                59
echo $a; /* reference to local scope variable */
        }

        test();    // Not display "1"


  4.3.5.1. Using global scope variables:

  - Using global keyword. Ex:
    $a = 1;
       $b = 2;

        function Sum()
        {
            global $a, $b;

             $b = $a + $b;
        }

        Sum();
        echo $b;     // Display "3"

  - Using $GLOBALS   variable. Ex:
    $a = 1;
       $b = 2;

        function Sum()
        {
            $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
        }

        Sum();
        echo $b;     // Display "3"


4.3.6. Static variables: A static variable exists only in a local function scope, but it does
   not lose its value when program execution leaves this scope.

    - Ex1:
    function test()
       {
           $a = 0;
           echo $a;
           $a++;
       }
    test(); // Display "0";
    test(); // Display "0";


    - Ex2:
    function test()
       {
                                                                    PHP Beginner & Intermediate
                                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                                  60
static $a = 0;
                echo $a;
                $a++;
         }
      test();    // Display "0";
      test();    // Display "1";


      - Note: static variable must not be declared as the result of an expression, it will cause a
         parse error. Ex:

      static $var = 1+2; // wrong (as it is an expression)
      static $var = sqrt(2); //wrong (as it is an expression)



4.4. Useful Functions:

  4.4.1. func_num_args(): returns the number of arguments passed to the function.

  4.4.2. func_get_arg(int $index): returns an item from the argument list.

  4.4.3. func_get_args(): returns an array comprising a function's argument list.

  4.4.4. function_exists(string $function_name): return TRUE if the given function
     has been defined.




Chapter Exercise:

   A> Write a script to calculate and return the sum of all arguments (the number of argument is
      unknown) of a function.
   Example: $a = calculate(1,2,3,4,6,2); // $a = 18

   B> List 3 global scope variables beside $GLOBALS




                                                                        PHP Beginner & Intermediate
                                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                                      61
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     62
Chapter 5
Array
Keywords: array, element, index, key, value, associate, sort, shuffle,
  random, iteration, loop, stack, queue, pop, push, shift.


Subjects:
  5.1. Declaration
  5.2. Array Operation
  5.3. Iteration (Looping)
  5.4. Sorting
  5.5. More Functions




                                                       PHP Beginner & Intermediate
                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                     63
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     64
5.1. Declaration:
  5.1.1. Declare an array variable:
     $a   =   array(10, 20, 30);
     $a   =   array('a' => 10, 'b' => 20, 'key' => 30);
     $a   =   array(5 => 1, 3=> 2, 1=>3, );
     $a   =   array();


  5.1.2. Array operator []:
     $a[] = 10;
     $a['key'] = 'value';
     echo $a['key']; // Displays "value"


 5.1.3. Multi-dimension Arrays: element of an array is an array too. Ex:
     $a = array(
        array('red', 'green', 'blue'),
        array('small', 'medium', 'large')
     );


5.2. Array Operation:
 5.2.1. Printing array:
 - Using print_r() to print only one array. Ex:
     $a = array ('a' => 'apple',
        'b' => 'banana',
        'c' => array ('x', 'y', 'z'));
     print_r($a);

     // Outputs:
     Array
     (
         [a] => apple
         [b] => banana
         [c] => Array
             (
                 [0] => x
                 [1] => y
                 [2] => z
             )
     )

 - Using var_dump() can print more than one array.
     $a = array ('a' => 'apple',
     'b' => 'banana',
     'c' => array ('x', 'y', 'z'));
     $b = array('x', 'y');
                                                               PHP Beginner & Intermediate
                                                        ATHENA TRAINING & EDUCATION CENTER
                                                                                             65
var_dump($a, $b);

    // Outputs:
    array(3) {
      ["a"]=>
      string(5) "apple"
      ["b"]=>
      string(6) "banana"
      ["c"]=>
      array(3) {
        [0]=>
        string(1) "x"
        [1]=>
        string(1) "y"
        [2]=>
        string(1) "z"
      }
    }
    array(2) {
      [0]=>
      string(1) "x"
      [1]=>
      string(1) "y"
    }



5.2.2. Counting array elements: using count() function. Ex:
    $a = array(5,6,7);
    $element = count($a);         // $element will be 3


5.2.3. Checking a variable is an array: using is_array() function. Ex:
    $a = array(5,6,7);
    $result = is_array($a);
    var_dump($result); // Displays "bool(true)"



5.2.4. Checking an element exists: using isset() function.
- Note: if element value equal NULL, isset() still return FALSE. Ex:
    $a = array('a' => NULL, 'b' => 2);
    $test = isset($a['a']); // $test will be assigned FALSE

In this case, using array_key_exists() function. Ex:

    $a = array('a' => NULL, 'b' => 2);
    $test = array_key_exists('a', $a);            // $test will be TRUE



                                                                       PHP Beginner & Intermediate
                                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                                     66
5.2.5. Deleting an element: using unset() function. Ex:
     $a = array('a', 'b', 'c');
     unset($a[1]);
     print_r($a);

     // Outputs:
     Array
     (
        [0] => a
        [2] => c
     )


5.3. Iteration (Looping):
 5.3.1. Array Pointer: using key(),           current(), next(), prev(), reset(), end()
    function. Ex:
     $a = array('a', 'b', 'c');

     while(key($a) !== null)
     {
        echo key($a) . ': ' . current($a) . PHP_EOL;

            // Move pointer to next element
            next($a);
     }


     //     Outputs:
     0:     a
     1:     b
     2:     c
           It's not a common way for iteration array.

 5.3.2. Using for() and foreach() function:
 - Ex 1:
     $a = array(3, 5, 7);

     $iCount = count($a);

     for($i = 0; $i < $iCount; $i++)
     {
     echo $a[$i] . '.';
     }

     // Displays "3, 5, 7, "



                                                                    PHP Beginner & Intermediate
                                                             ATHENA TRAINING & EDUCATION CENTER
                                                                                                  67
- Ex 2:
     $a = array('blue' => 'small', 'green' => 'large');

     foreach($a as $key => $value)
     {
        echo $key. ' : ' . $value . ',';
     }

     //Displays
     "blue : small, green : large, "




5.4. Sorting:
       Function name         Sorts by   Maintains key    Order of sort     Related functions
                                         association
      sort()                  Value         No          Low to high       rsort()
      rsort()                 Value         No          High to low       sort()
      asort()                 Value         Yes         Low to high       arsort()
      arsort()                Value         Yes         High to low       asort()
      natsort()               Value         Yes         Natural           natcasesort()
      natcasesort()           Value         Yes         Natural, case     natsort()
                                                        insensitive
      ksort()                 Key            Yes        Low to high       asort()
      krsort()                Key            Yes        High to low       ksort()
      usort()                 Value          No         User defined      uasort()
      uasort()                Value          Yes        User defined      uksort()
      uksort()                Key            Yes        User defined      uasort()
      shuffle()               Value          No         Random            array_rand()
      array_multisort()       Value     Associative     First array or    array_walk()
                                        yes, numeric    sort options
                                             no
    Example of using sort() function:
     $fruits = array(        'a' => 'lemon',
                          'c' => 'orange',
                          'd' => 'banana',
                          'b' => 'apple');
     sort($fruits);

     foreach ($fruits as $key => $val)
     {
        echo "fruits[" . $key . "] = " . $val . "n";
     }


                                                               PHP Beginner & Intermediate
                                                        ATHENA TRAINING & EDUCATION CENTER
                                                                                               68
// Outputs:
    fruits[0] =   apple
    fruits[1] =   banana
    fruits[2] =   lemon
    fruits[3] =   orange



Example of using asort():
    $fruits = array(      'a' => 'lemon',
                    'c' => 'orange',
                    'd' => 'banana',
                    'b' => 'apple');
    asort($fruits);

    foreach ($fruits as $key => $val)
    {
       echo "fruits[" . $key . "] = " . $val . "n";
    }

    // Outputs:
    fruits[b] =   apple
    fruits[d] =   banana
    fruits[a] =   lemon
    fruits[c] =   orange




Example of using ksort():
    $fruits = array(      'a' => 'lemon',
                    'c' => 'orange',
                    'd' => 'banana',
                    'b' => 'apple');
    ksort($fruits);

    foreach ($fruits as $key => $val)
    {
       echo "fruits[" . $key . "] = " . $val . "n";
    }

    // Outputs:
    fruits[a] =   lemon
    fruits[b] =   apple
    fruits[c] =   orange
    fruits[d] =   banana




                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      69
5.5. More Functions:
 5.5.1. list() : assign variables as if they were an array.

 5.5.2. array_merge(): merge one or more arrays.

 5.5.3. array_slice(): extract a slice of the array.

 5.5.4. array_diff_*() group: computes the difference of arrays

 5.5.5. array_intersect_*() group: computes the intersection of arrays.

 5.5.6. array_push(),     array_pop(), array_shift(), array_unshift(): insert/
    remove an element from array using queue and stack operation.

                                   STACK OPERATION




                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                   70
QUEUE OPERATION




Chapter Exercise:

   A> Can we use arithmetic operator (+, -, *, /) between 2 arrays. If yes, what is the result?

   B> Simulate the game " ánh bài Ti n lên" of Vietnamese, there are 4 people in game, each
      has 13 cards. Using functions from beginning to this chapter to write the action of shuffle
      cards and give each one 13 random cards.
   ***** difficult : write the function to find the number of "3 ôi thông" in 13 cards of each
      person.




                                                                        PHP Beginner & Intermediate
                                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                                      71
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     72
Chapter 6
String
Manipulation
Keywords: string, haystack, needle, text, character, case-sensitive, case-
  insensitive, HEREDOC, escape character, compare, search, extract,
  replace, position, format, regular expression, expression, match,
  pattern, delimiter, PCRE, overhead.


Subjects:
  6.1. Declaration
  6.2. Comparision
  6.3. Searching
  6.4. Replacement
  6.5. Splitting
  6.6. Formatting
  6.7. Regular Expression – RegEx


                                                       PHP Beginner & Intermediate
                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                     73
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     74
6.1. Declaration:
 6.1.1. Normal Assignment:
          1.   $a = "Using double quote";
          2.   $b = 'Using single quote';
          3.   $c = "control characters in n double quote only";
          4.   $c2 = "052";
          5.   $c3 = "x2a";
          6.   $num = 1;
          7.   $d = "$num is parsed"; // $d equals "1 is parsed"
          8.   $e = "$numx is not parsed"; // $e equals " is not parsed"
          9.   $f = "{$num}x is parsed"; // $f equals "1x is parsed"


 6.1.2. HEREDOC:
     $who = "World";
     $str = <<<TEXT
     Hello $who
     TEXT;
     // Displays "Hello World"




6.2. Comparision:
 6.2.1. Comparison Operator : using operators      == , !=, ===, !==    . Ex:

     $a = '123abc';
     $b = '123Abc';
     $c = 123;
     $test1 = ($a == $b); // $test1 equals FALSE
     $test2 = ($a == $c); // $test2 equals TRUE
     $test3 = ($a === $c); // $test3 equals FALSE


 6.2.2. Using strcmp() : compare two string, it's case-sensitive. Using strcasecmp() to
    compare two string, it's case-insensitive.

    Ex:
     $str =    'Hello world';
     $test1    = strcmp($str, 'hello world'); // $test1 equals -1
     $test2    = strcasecmp($str, 'hello world'); // $test2 equals 0
     $test3    = strcmp('a', 'A'); // $test3 equals 1;




                                                                 PHP Beginner & Intermediate
                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                               75
6.3. Searching:
  6.3.1. strpos(): Find position of first occurrence of a string. It's case-sensitive.
     - Ex:
     $pos = strpos('mystring', 'str'); // $pos equals 2
     $pos = strpos('mystring', 'hi'); // $pos === FALSE


  6.3.2. strrpos(): Find position of last occurrence of a char in a string. It's case-sensitive.
     Ex:
     $pos = strrpos('mystringmy', 'my');             // $pos equals 8


  6.3.3. strstr(): Find first occurrence of a string. It's case-sensitive.
     Ex:
     $pos = strstr('mystring', 'str'); // $pos equals "string"
     $pos = strstr('mystring', 'hi'); // $pos === FALSE


  6.3.4. stripos() is the case-insensitive version of strpos().

  6.3.5. strripos() is the case-insensitive version of strrpos().

  6.3.6. stristr() is the case-insensitive version of strstr().



6.4. Replacement:
 6.4.1. str_replace(): replace all occurrences of the search string with the replacement
    string, it's case-sensitive. str_ireplace() is the case-insensitive of str_replace(). Ex:
     echo str_replace('abc', 'z', 'abcdef' );              //Displays "zdef"
     echo str_replace('ABC', 'z', 'abcdef');               // Displays "abcdef"
     echo str_ireplace('ABC', 'z', 'abcdef');              // Display "zdef"


 6.4.2. substr_replace(): replace text within a portion of a string.
    Ex:
     echo substr_replace('012345abcdef', 'zzz', 5);
     // Displays "01234zzz"




                                                                      PHP Beginner & Intermediate
                                                               ATHENA TRAINING & EDUCATION CENTER
                                                                                                    76
6.5. Splitting:
  6.5.1. Retun part of string: using     substr().

     Ex:
      echo substr('abcdef', 1);     //        bcdef
         echo substr('abcdef', 1, 3);         // bcd
         echo substr('abcdef', 0, 4);         // abcd
         echo substr('abcdef', 0, 8);         // abcdef
         echo substr('abcdef', -1, 1);        // f


  6.5.2. Split string to array: using explode() and split() function.
     Ex:
      $s1 = 'a,b,c,d';
      $a1 = explode(',', $s1);
      print_r($a1);

      $s2 = '1,2,3,4';
      $a2 = split(',', $s2, 2);
      print_r($a2);

      //Displays:
      Array
      (
          [0] => a
          [1] => b
          [2] => c
          [3] => d
      )
      Array
      (
          [0] => 1
          [1] => 2,3,4
      )

      Question: what displays when running this script:

      echo count(split('/', '///'));


  6.5.3. Join array elements to a string: using implode() and join() function.
     Ex:
      $array = array('lastname', 'email', 'phone');
         $comma_separated = implode(",", $array);

         echo $comma_separated;
      // displays "lastname,email,phone"
                                                                 PHP Beginner & Intermediate
                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                               77
6.6. Formatting:
 6.6.1. Number formatting: using number_format() to formatting numerical value.
    Ex:
     echo number_format("100000.123", 2, '.', ',');
     // Displays "100,000.12"

 6.6.2. Output formatting: using printf() to print a string in a specified format.
    Ex:




 - %s, %d, %f: Specifiers.

       Specifier      Format
       b              The argument is treated as an integer and is presented as an integer in binary
                      form.
       c              The argument is treated as an integer and is presented as the ASCII character
                      for that value.
       d              The argument is treated as an integer and presented as a signed integer.
       u              The argument is treated as an integer and presented as an unsigned integer.
       f              The argument is treated as a floating-point number and presented as a
                      floating-point number.
       o              The argument is treated as an integer and presented as its octal
                      representation.
       x              The argument is treated as an integer and presented as a hexadecimal
                      number (using lowercase letters).
       X              The argument is treated as an integer and presented as a hexadecimal
                      number (using uppercase letters).


 - Formatting functions:

       Function       Arguments                                Result
       printf         Format, args                             Writes output
       sprintf        Format, args                             Return result
       vprintf        Format, array of args                    Writes output
       vsprintf       Format, array of args                    Returns result
       fprintf        Stream resource, format, args            Writes output to stream

                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                       78
6.7. Regular Expression – RegEx:
     - The most powerful tools in the string manipulation toolbox are regular expressions

 6.7.1. Introduction:




 6.7.2. Character Class: allow a pattern to match multiple characters simultaneously

     Metacharacter       Characters Matched
     d                  Digits 0-9
     D                  Anything not a digit
     w                  Any alphanumeric character or an underscore (_)
     W                  Anything not an alphanumeric character or an underscore
     s                  Any whitespace (spaces, tabs, newlines)
     S                  Any non-whitespace character
     .                   Any character except for a newline
     ^                   Match the start of the string
     $                   Match the end of the string

 Ex 1: the expression /ab[cd]e/ matches abce and abde.
 Ex 2: the expression /ab[c-ed]/ will match abc, abd, abe and any combination of ab
    followed by a digit.



 6.7.3. Quantifiers: allows you to specify the number of times a particular character or
    metacharacter can appear in a matched string. 4 types of quantifiers:
                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                   79
*                 The character can appear zero or more times
    +                 The character can appear one or more times
    ?                 The character can appear zero or one times
    {n,m}             The character can appear at least n times, and no more than m. Either
                      parameter can be omitted to indicated a minimum limit with no
                      maximum, or a maximum limit without a minimum, but not both

   Ex: the expression /ab?c/ matches both ac and abc, while ab{1,3}c matches abc, abbc,
   abbbc.


6.7.4. Match & Extract strings: preg_match() and preg_match_all(). Ex:

   $str = 'foobar: 2008 - hello: 2009';
   preg_match('/(?<name>w+): (?<digit>d+)/', $str, $matches);
   print_r($matches);

   //Displays:
   Array
   (
       [0] => foobar: 2008
       [name] => foobar
       [1] => foobar
       [digit] => 2008
       [2] => 2008
   )

    Ex 2:
   $str = 'foobar: 2008 - hello: 2009';
   preg_match_all('/(w+): (d+)/', $str, $matches);
   print_r($matches);
   //Displays:
   Array
   (
       [0] => Array
           (
               [0] => foobar: 2008
               [1] => hello: 2009
           )

        [1] => Array
            (
                [0] => foobar
                [1] => hello
            )

        [2] => Array
            (
                [0] => 2008
                [1] => 2009
            )

   )
                                                                 PHP Beginner & Intermediate
                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                               80
6.7.5. Replace string with Regex: preg_replace().

     Ex:
      $string = 'April 15, 2003';
         $pattern = '/(w+) (d+), (d+)/i';
         $replacement = '${1}x,$3';
         echo preg_replace($pattern, $replacement, $string);
      // Displays "Aprilx,2003"


  6.7.6. Split string by a regular expression: using preg_split().

     Ex:
      $keywords = preg_split("/[ds,]+/", "hyper1 lang2, prog");
      print_r($keywords);

      // Displays
      Array
      (
          [0] => hyper
          [1] => lang
          [2] => prog
      )




Chapter Exercise:

   A> Write the function to check the file is the image or not.
   Input: filename, return TRUE/FALSE. Valid image type: jpg, jpeg, png, gif, bmp.

   B> Write the regular expression pattern to match an URI of an image. Example:
      http://www.example.com/photo/some-directory/imagename.gif

   C> Write the regular expression pattern to match an email address.




                                                                        PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                      81
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     82
Chapter 7
HTTP Basic
Keywords: http, html, header, form, request, response, get, post, cookie,
  session, authentication, domain, timeout, expire, redirect, caching, file
  upload, apache, rewrite rule, htaccess.


Subjects:
  7.1. HTTP Fundamentals
  7.2. File Upload
  7.3. Cookie
  7.4. Session




                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      83
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     84
7.1. HTTP Fundamentals:
 7.1.1. How HTTP works: (RFC 2616)




 7.1.2. GET Method:
 - Change URL after submit form

 - using global variable $_GET or $_REQUEST to access data in form.

    Ex:
     $firstName = $_GET['FirstName'];
     $salary = $_GET['Salary'];
     $contractor = $_GET['Contractor'];


 7.1.3. POST Method:
 - Not change URL after submit form

 - using global variable $_POST or $_REQUEST to access data in form.

    Ex:
     $firstName = $_POST['FirstName'];
     $salary = $_POST['Salary'];
     $contractor = $_POST['Contractor'];
                                                                 PHP Beginner & Intermediate
                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                               85
7.1.4. HTTP Request:
- Sample of request:




--------------------------------------------------------------------------------------------------------

GET Header Request:

GET /dumprequest HTTP/1.1
Host: djce.org.uk
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.12)
   Gecko/2009070611 Firefox/3.0.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.google.com.vn/search?hl=vi&client=firefox-a&rls=org.mozilla:en-
   US:official&um=1&q=http%20request&ndsp=21&ie=UTF-8&sa=N&tab=iw




POST Header Request:

POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Mosby&favorite+flavor=flies




                                                                                  PHP Beginner & Intermediate
                                                                         ATHENA TRAINING & EDUCATION CENTER
                                                                                                                86
7.1.5. HTTP Response:




HTTP/1.1 200 OK
   Date: Sun, 08 Oct 2000 18:46:12 GMT
   Server: Apache/1.3.6 (Unix)
   Keep-Alive: timeout=5, max=120
   Connection: Keep-Alive
   Content-Type: text/html
   <html>...



Some HTTP 1.1 status code:
    Status   Reason           Description
    Code     Phrase
    200      OK               Generic successful request message response. This is the code
                              sent most often when a request is filled normally.
    201        Created        The request was successful and resulted in a resource being
                              created. This would be a typical response to a PUT method.
    301        Moved          The resource requested has been moved to a new URL
               Permanently    permanently. Any future requests for this resource should use
                              the new URL.

                              This is the proper method of handling situations where a file on
                              a server is renamed or moved to a new directory. Most people
                              don't bother setting this up, which is why URLs “break” so
                              often, resulting in 404 errors as discussed below.
    302        Found          The resource requested is temporarily using a different URL.
                              The client should continue to use the original URL.
    304        Not Modified   The client sent a conditional GET request, but the resource has
                              not been modified since the specified date/time, so the server
                              has not sent it.
    400        Bad request    Server says, “huh?” Generic response when the request cannot
                              be understood or carried out due to a problem on the client's
                              end.
                                                                PHP Beginner & Intermediate
                                                         ATHENA TRAINING & EDUCATION CENTER
                                                                                                 87
401        Unauthorized     The client is not authorized to access the resource. Often
                                  returned if an attempt is made to access a resource protected by
                                  a password or some other means without the appropriate
                                  credentials.
      404        Not Found        The most common HTTP error message, returned when the
                                  server cannot locate the requested resource. Usually occurs due
                                  to either the server having moved/removed the resource, or the
                                  client giving an invalid URL (misspellings being the most
                                  common cause.)
      500        Internal         Generic error message indicating that the request could not be
                 Server Error     fulfilled due to a server problem.
      502        Bad Gateway      The server, while acting as a gateway or proxy, received an
                                  invalid response from another server it tried to access on the
                                  client's behalf.
      503        Service          The server is temporarily unable to fulfill the request for internal
                 Unavailable      reasons. This is often returned when a server is overloaded or
                                  down for maintenance.
      504        Gateway          The server, while acting as a gateway or proxy, timed out while
                 Timeout          waiting for a response from another server it tried to access on
                                  the client's behalf.


 7.1.6. Header:
 - Using function header() to send a HTTP header.

    Ex:
     header('Location: http://www.php.net/');
     header("HTTP/1.0 404 Not Found");




7.2. File Upload:
 7.2.1. Prepare form:
     <form method="post" enctype="multipart/form-data" action="upload.php">
     File to upload: <input type="file" name="myfile"><BR>
     <input type="submit" value="Submit">
     </FORM>




                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                         88
7.2.2. Upload a file:
- Get uploaded file's data using $_FILES. Ex:
    $name = $_FILES[myfile]['name'];
    $type = $_FILES[myfile][type];
    $size = $_FILES[myfile][size];
    $tmpname = $_FILES[myfile][tmp_name];
    $error = $_FILES[myfile][error];
    $uploadPath = 'uploads/photos/'.$name;

    // Begin to upload fileif (move_uploaded_file($tmpname, $uploadPath))
    {
       echo 'Upload successfully!';
    }



7.2.3. Upload multiple files:
- HTML form:
    …
    File to upload: <input type="file" name="myfile[]"><BR>
    File to upload: <input type="file" name="myfile[]"><BR>
    …

- PHP script:
    $nameA = $_FILES[myfile]['name'][0];
    $tmpnameA = $_FILES[myfile][tmp_name][0];
    $uploadPathA = 'uploads/photos/'.$nameA;

    $nameB = $_FILES[myfile]['name'][1];
    $tmpnameA = $_FILES[myfile][tmp_name][1];
    $uploadPathB = 'uploads/photos/'.$nameB;

    // Begin to upload files
       …




                                                        PHP Beginner & Intermediate
                                                 ATHENA TRAINING & EDUCATION CENTER
                                                                                      89
7.3. Cookie:
 7.3.1. How cookies work:




 7.3.2. Create cookies: using setcookie() function. Ex:
     $value = 'something from somewhere';

           setcookie("test", $value);
           setcookie("test", $value, time()+3600); /* expire in 1 hour */
           setcookie("test", $value, time()+3600, "/~test/", ".example.com", 1);




 7.3.3. Get cookies data: using global variables $_COOKIES or $_REQUEST.

     Ex:

     echo $_COOKIE["test"];

 7.3.4. Delete a cookie:
     setcookie ("test", "", time() - 3600);
                                                                 PHP Beginner & Intermediate
                                                          ATHENA TRAINING & EDUCATION CENTER
                                                                                               90
7.4. Session:
 7.4.1. How sessions work:




 7.4.2. Create sessions: If you are using cookie-based sessions, you must call
    session_start() before anything is outputted to the browser.
     session_start();
     $_SESSION['username'] = 'testing';


 7.4.3. Session ID processing:
   7.4.3.1. Get the current Session ID:
   - session_id() : used to get or set the session id for the current session. Ex:

     $currentSessID = session_id();


   7.4.3.2. Re-generate Session ID:
   - session_regenerate_id() : Update the current session id with a newly generated one.

   7.4.3.3. Example:

     session_start();
        $old_sessionid = session_id();

                                                                        PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                      91
session_regenerate_id();
            $new_sessionid = session_id();

            echo "Old Session: $old_sessionid<br />";
            echo "New Session: $new_sessionid<br />";


  7.4.4. Delete a session:
       session_destroy();




Chapter Exercise:

   A> Design a webpage to display form for user login. The username is an email, and the password
      must be at least 6 characters. Password must be alphanumerical characters (a-z, A-Z, 0-9). If login
      success, displays the name of the user (extract from email) and the number of page which is
      refreshed by user.

   Ex: enter email: rasmus@myemail.com, password: abc3456ad5, website will display:

       Hello rasmus !

       You refreshed 3 times.

   B> Write photo album function for the user (after login) from question A.

      a.   Upload images (png,gif,jpeg) – 5 images in a submit form
      b.   Store images in directory "uploads/images/".
      c.   Max file size: 300KB
      d.   File name: USERNAME_imagename
      e.   If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be
           renamed to rasmus_image1i.gif




                                                                              PHP Beginner & Intermediate
                                                                      ATHENA TRAINING & EDUCATION CENTER
                                                                                                            92
Chapter 8
OOP
Object-Oriented Programming
Keywords: object, class, instance, inheritance, encapsulation, access,
  constructor, destructor, property, method, visibility, parent, self, this,
  override, public, protected, private.


Subjects:
  8.1. OOP Fundamentals
  8.2. Properties
  8.3. Methods
  8.4. Inheritance & Overriding




                                                         PHP Beginner & Intermediate
                                                  ATHENA TRAINING & EDUCATION CENTER
                                                                                       93
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
                                     94
8.1. OOP Fundamentals:
 8.1.1. What is OOP ?




 - As we mentioned previously, the basic element of OOP is the class. A class contains the
     definition of data elements (or properties) and functions (or methods) that share some
     common trait and can be encapsulated in a single structure.

 8.1.2. Declaring Class: Class name is case-insensitive
     class ClassName
     {
        // Some Properties

           // Some Methods
     }

 8.1.3. Instantiating an Object: To create an instance of a class, a new object must be
    created and assigned to a variable. An object will always be assigned when creating a new
    object unless the object has a constructor defined that throws an exception on error.
    Classes should be defined before instantiation.

 - In the class context, it is possible to create a new object by new self and new parent.

     Ex:
     $myClassInstance = new MyClass();
     $copyInstance = $myClassInstance;


                                                                        PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                      95
8.2. Properties:
 8.2.1. Declaration & Visibility: The default value must be a constant expression, not
    (for example) a variable, a class member or a function call.

     Ex:
     class foo
     {
        //valid declaration
        public $name;
        protected $age;
        private $type;

           public $var1 = "Test"; // String
           public $var2 = 1.23; // Numeric value
           public $var3 = array(1, 2, 3); // Array

           //invalid declaration
           $var4 = TRUE;
           public $var1 = 'hello '.'world';
                 public $var2 = <<<EOD
                       hello world
                       EOD;
                 public $var3 = 1+2;
                 public $var4 = self::myStaticMethod();
                 public $var5 = $myVar;
     }



 8.2.2. Constant:
    Ex:
     class foo
     {
        const BAR = 'Hello World';
     }

     echo foo::BAR;




                                                                     PHP Beginner & Intermediate
                                                              ATHENA TRAINING & EDUCATION CENTER
                                                                                                   96
8.3. Methods:
 8.3.1. Declaration:
 - A class method/functions is the behavior/functionality of a class i.e. they provide the
     necessary code for the class in which it is defined.

 - A class method is exactly similar to PHP functions, it’s just that class functions are declared
     inside classes and accessed using the -> (arrow operator / dereferencing operator).

 - Methods can also be declared as either public, protected or private.

 - Example:
     class MyClass
     {
        public function myFunction()
        {
              echo 'You called MyClass::myFunction';

                 //call the private function
                 $this->myPrivate();
         }

         private function myPrivate()
         {
               echo "nThis is a private function.";
         }
     }
     $obj = new MyClass();
     $obj->myFunction();

     //Displays:
     You called MyClass::myFunction
     This is a private function.



 - A pseudo-variable, $this is available when a method is called from within an object context.
     Ex:

     class Shirt
     {
        public $color;

         private function getColor()
         {
               echo $this->color;
         }

         public function say()
                                                                       PHP Beginner & Intermediate
                                                                ATHENA TRAINING & EDUCATION CENTER
                                                                                                     97
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final
Giao trinh php 2009   vo duy tuan - final

Contenu connexe

Tendances

Artificial neural network_tutorial
Artificial neural network_tutorialArtificial neural network_tutorial
Artificial neural network_tutorialHarikaReddy115
 
Software performance testing handbook a comprehensive guide for begineers
Software performance testing handbook   a comprehensive guide for begineers Software performance testing handbook   a comprehensive guide for begineers
Software performance testing handbook a comprehensive guide for begineers Rav Kiran
 
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...stannventures.Pvt.Ltd
 
Language in leadership and management: ACE School Management and Leadership (...
Language in leadership and management: ACE School Management and Leadership (...Language in leadership and management: ACE School Management and Leadership (...
Language in leadership and management: ACE School Management and Leadership (...Saide OER Africa
 
A byte of python (2005)
A byte of python (2005)A byte of python (2005)
A byte of python (2005)vaibhsss
 

Tendances (7)

Artificial neural network_tutorial
Artificial neural network_tutorialArtificial neural network_tutorial
Artificial neural network_tutorial
 
Project caponera lssgb
Project caponera lssgbProject caponera lssgb
Project caponera lssgb
 
Software performance testing handbook a comprehensive guide for begineers
Software performance testing handbook   a comprehensive guide for begineers Software performance testing handbook   a comprehensive guide for begineers
Software performance testing handbook a comprehensive guide for begineers
 
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...
Getting started with licensing | Tally.NET Services | Tally Intergation | Tal...
 
Language in leadership and management: ACE School Management and Leadership (...
Language in leadership and management: ACE School Management and Leadership (...Language in leadership and management: ACE School Management and Leadership (...
Language in leadership and management: ACE School Management and Leadership (...
 
Composer 6.7 user
Composer 6.7 userComposer 6.7 user
Composer 6.7 user
 
A byte of python (2005)
A byte of python (2005)A byte of python (2005)
A byte of python (2005)
 

En vedette

Presentatie Brixx
Presentatie BrixxPresentatie Brixx
Presentatie BrixxBrixx_CPO
 
Projecte disseny gràfic 2013
Projecte disseny gràfic 2013Projecte disseny gràfic 2013
Projecte disseny gràfic 2013Epv Artistica
 
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)Barry_Rosen
 
Mahesh dukudu infilm branding
Mahesh dukudu infilm brandingMahesh dukudu infilm branding
Mahesh dukudu infilm brandingmanojkumarvadde
 
Süryay Mevzuat Uygulaması Tanıtım Kılavuzu
Süryay Mevzuat Uygulaması Tanıtım KılavuzuSüryay Mevzuat Uygulaması Tanıtım Kılavuzu
Süryay Mevzuat Uygulaması Tanıtım Kılavuzukolormatik
 
The Flying Scotsman - Trailer em fotos
The Flying Scotsman - Trailer em fotosThe Flying Scotsman - Trailer em fotos
The Flying Scotsman - Trailer em fotosJonisousa Campos
 
Iconic ppt with comparison blank
Iconic ppt with comparison blankIconic ppt with comparison blank
Iconic ppt with comparison blankmillionsproperty
 
Memorandum and letters
Memorandum and lettersMemorandum and letters
Memorandum and lettersHatesh Kumar
 
Логан 2016
Логан 2016Логан 2016
Логан 2016Al Maks
 

En vedette (20)

Turk resimpiyasasi
Turk resimpiyasasiTurk resimpiyasasi
Turk resimpiyasasi
 
Cl@sse 2 marcello
Cl@sse 2 marcelloCl@sse 2 marcello
Cl@sse 2 marcello
 
females and hcv
females and hcvfemales and hcv
females and hcv
 
Baum2
Baum2Baum2
Baum2
 
Presentatie Brixx
Presentatie BrixxPresentatie Brixx
Presentatie Brixx
 
Cartas Proibidas
Cartas ProibidasCartas Proibidas
Cartas Proibidas
 
Uruguay
UruguayUruguay
Uruguay
 
การสังเกต Sn
การสังเกต Snการสังเกต Sn
การสังเกต Sn
 
Projecte disseny gràfic 2013
Projecte disseny gràfic 2013Projecte disseny gràfic 2013
Projecte disseny gràfic 2013
 
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)
Everything You Need to Know About Health Care Reform (But Are Afraid to Ask)
 
Mahesh dukudu infilm branding
Mahesh dukudu infilm brandingMahesh dukudu infilm branding
Mahesh dukudu infilm branding
 
Süryay Mevzuat Uygulaması Tanıtım Kılavuzu
Süryay Mevzuat Uygulaması Tanıtım KılavuzuSüryay Mevzuat Uygulaması Tanıtım Kılavuzu
Süryay Mevzuat Uygulaması Tanıtım Kılavuzu
 
Sn ps
Sn psSn ps
Sn ps
 
The Flying Scotsman - Trailer em fotos
The Flying Scotsman - Trailer em fotosThe Flying Scotsman - Trailer em fotos
The Flying Scotsman - Trailer em fotos
 
Iconic ppt with comparison blank
Iconic ppt with comparison blankIconic ppt with comparison blank
Iconic ppt with comparison blank
 
Memorandum and letters
Memorandum and lettersMemorandum and letters
Memorandum and letters
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
Brigadoon Program
Brigadoon ProgramBrigadoon Program
Brigadoon Program
 
Daftarhadir&nilai kapita selekta
Daftarhadir&nilai kapita selektaDaftarhadir&nilai kapita selekta
Daftarhadir&nilai kapita selekta
 
Логан 2016
Логан 2016Логан 2016
Логан 2016
 

Similaire à Giao trinh php 2009 vo duy tuan - final

Similaire à Giao trinh php 2009 vo duy tuan - final (20)

PHP-Nuke-HOWTO
PHP-Nuke-HOWTOPHP-Nuke-HOWTO
PHP-Nuke-HOWTO
 
PHP-Nuke-HOWTO
PHP-Nuke-HOWTOPHP-Nuke-HOWTO
PHP-Nuke-HOWTO
 
Zend Server Ce Reference Manual V403
Zend Server Ce Reference Manual V403Zend Server Ce Reference Manual V403
Zend Server Ce Reference Manual V403
 
How To Create PowerShell Function
How To Create PowerShell FunctionHow To Create PowerShell Function
How To Create PowerShell Function
 
cpanel.pdf
cpanel.pdfcpanel.pdf
cpanel.pdf
 
Access 2007 Notes-All Chapters.pdf
Access 2007 Notes-All Chapters.pdfAccess 2007 Notes-All Chapters.pdf
Access 2007 Notes-All Chapters.pdf
 
Cpanel
CpanelCpanel
Cpanel
 
Entitlements and balancing
Entitlements and balancingEntitlements and balancing
Entitlements and balancing
 
Getting Started Guide
Getting Started GuideGetting Started Guide
Getting Started Guide
 
fundamentals of linux
fundamentals of linuxfundamentals of linux
fundamentals of linux
 
fundamentals of linux
fundamentals of linuxfundamentals of linux
fundamentals of linux
 
fundamentals of linux
fundamentals of linuxfundamentals of linux
fundamentals of linux
 
Teamviewer manual by PW
Teamviewer manual by PWTeamviewer manual by PW
Teamviewer manual by PW
 
Linux_kernelmodule
Linux_kernelmodule Linux_kernelmodule
Linux_kernelmodule
 
Oracle Web Conferencing - Release 2.0.4
Oracle Web Conferencing - Release 2.0.4Oracle Web Conferencing - Release 2.0.4
Oracle Web Conferencing - Release 2.0.4
 
Firstcup
FirstcupFirstcup
Firstcup
 
Profit platformsitemanagementarea
Profit platformsitemanagementareaProfit platformsitemanagementarea
Profit platformsitemanagementarea
 
Computer fundamentals tutorial
Computer fundamentals tutorialComputer fundamentals tutorial
Computer fundamentals tutorial
 
Cake php cookbook
Cake php cookbookCake php cookbook
Cake php cookbook
 
Pengenalan kepada Pentaho
Pengenalan kepada PentahoPengenalan kepada Pentaho
Pengenalan kepada Pentaho
 

Plus de hieusy

Thảo luận logic học
Thảo luận logic họcThảo luận logic học
Thảo luận logic họchieusy
 
Tcs p2
Tcs p2Tcs p2
Tcs p2hieusy
 
Tcs p1
Tcs p1Tcs p1
Tcs p1hieusy
 
Ngan hang de thi (du thao)
Ngan hang de thi (du thao)Ngan hang de thi (du thao)
Ngan hang de thi (du thao)hieusy
 
Logic tl(01 k5)
Logic tl(01 k5)Logic tl(01 k5)
Logic tl(01 k5)hieusy
 
Logic chuong5
Logic chuong5Logic chuong5
Logic chuong5hieusy
 
Logic chuong4
Logic chuong4Logic chuong4
Logic chuong4hieusy
 
Logic chuong3
Logic chuong3Logic chuong3
Logic chuong3hieusy
 
Logic chuong2
Logic chuong2Logic chuong2
Logic chuong2hieusy
 
Logic chuong1
Logic chuong1Logic chuong1
Logic chuong1hieusy
 
Logic hoc dai cuong (vuong tat dat)
Logic hoc dai cuong (vuong tat dat)Logic hoc dai cuong (vuong tat dat)
Logic hoc dai cuong (vuong tat dat)hieusy
 
Giao trinh logic dc(trần văn toàn)
Giao trinh logic dc(trần văn toàn)Giao trinh logic dc(trần văn toàn)
Giao trinh logic dc(trần văn toàn)hieusy
 
Giao trinh logic dc(trần väƒn toă n)
Giao trinh logic dc(trần väƒn toă n)Giao trinh logic dc(trần väƒn toă n)
Giao trinh logic dc(trần väƒn toă n)hieusy
 
Giao trinh logic (bui thanh quat)
Giao trinh logic (bui thanh quat)Giao trinh logic (bui thanh quat)
Giao trinh logic (bui thanh quat)hieusy
 
Giai thuat va lap trinh
Giai thuat va lap trinhGiai thuat va lap trinh
Giai thuat va lap trinhhieusy
 
De cuong on tap (form)
De cuong on tap (form)De cuong on tap (form)
De cuong on tap (form)hieusy
 
Thảo luận logic học
Thảo luận logic họcThảo luận logic học
Thảo luận logic họchieusy
 
Ngan hang de thi (du thao)
Ngan hang de thi (du thao)Ngan hang de thi (du thao)
Ngan hang de thi (du thao)hieusy
 
Logic tl(01 k5)
Logic tl(01 k5)Logic tl(01 k5)
Logic tl(01 k5)hieusy
 

Plus de hieusy (20)

Thảo luận logic học
Thảo luận logic họcThảo luận logic học
Thảo luận logic học
 
Tcs p2
Tcs p2Tcs p2
Tcs p2
 
Tcs p1
Tcs p1Tcs p1
Tcs p1
 
Ngan hang de thi (du thao)
Ngan hang de thi (du thao)Ngan hang de thi (du thao)
Ngan hang de thi (du thao)
 
Logic tl(01 k5)
Logic tl(01 k5)Logic tl(01 k5)
Logic tl(01 k5)
 
Logic chuong5
Logic chuong5Logic chuong5
Logic chuong5
 
Logic chuong4
Logic chuong4Logic chuong4
Logic chuong4
 
Logic chuong3
Logic chuong3Logic chuong3
Logic chuong3
 
Logic chuong2
Logic chuong2Logic chuong2
Logic chuong2
 
Logic chuong1
Logic chuong1Logic chuong1
Logic chuong1
 
Logic hoc dai cuong (vuong tat dat)
Logic hoc dai cuong (vuong tat dat)Logic hoc dai cuong (vuong tat dat)
Logic hoc dai cuong (vuong tat dat)
 
Giao trinh logic dc(trần văn toàn)
Giao trinh logic dc(trần văn toàn)Giao trinh logic dc(trần văn toàn)
Giao trinh logic dc(trần văn toàn)
 
Giao trinh logic dc(trần väƒn toă n)
Giao trinh logic dc(trần väƒn toă n)Giao trinh logic dc(trần väƒn toă n)
Giao trinh logic dc(trần väƒn toă n)
 
Giao trinh logic (bui thanh quat)
Giao trinh logic (bui thanh quat)Giao trinh logic (bui thanh quat)
Giao trinh logic (bui thanh quat)
 
Giai thuat va lap trinh
Giai thuat va lap trinhGiai thuat va lap trinh
Giai thuat va lap trinh
 
De cuong on tap (form)
De cuong on tap (form)De cuong on tap (form)
De cuong on tap (form)
 
Ctdl1
Ctdl1Ctdl1
Ctdl1
 
Thảo luận logic học
Thảo luận logic họcThảo luận logic học
Thảo luận logic học
 
Ngan hang de thi (du thao)
Ngan hang de thi (du thao)Ngan hang de thi (du thao)
Ngan hang de thi (du thao)
 
Logic tl(01 k5)
Logic tl(01 k5)Logic tl(01 k5)
Logic tl(01 k5)
 

Dernier

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Dernier (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Giao trinh php 2009 vo duy tuan - final

  • 1.
  • 2. Enjoy PHPing! PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 2
  • 3. TABLE OF CONTENTS Chapter 1. Web Design Basic ..........................................................................................7 Web Design Toolbox..................................................................................................... 9 HTML Editor – Dreamweaver CS3 .............................................................................. 16 HTML Basics................................................................................................................ 22 HTML Form ................................................................................................................. 23 CSS .............................................................................................................................. 27 Javascript .................................................................................................................... 28 Chapter 2. PHP Workspace ...........................................................................................31 PHP Introduction ........................................................................................................ 33 AppServ Installation ................................................................................................... 35 Using AppServ ............................................................................................................ 37 PHP IDE - PhpEd.......................................................................................................... 38 Using PHP Interactive ................................................................................................. 42 Chapter 3. PHP Basics ...................................................................................................45 PHP Syntax.................................................................................................................. 47 Data Types .................................................................................................................. 48 Variable & Constant ................................................................................................... 49 Operators ................................................................................................................... 50 Control Structure ........................................................................................................ 51 Chapter 4. Function ......................................................................................................55 Introduction................................................................................................................ 57 Syntax ......................................................................................................................... 57 Parameter & Argument .............................................................................................. 58 Useful Functions ......................................................................................................... 61 Chapter 5. Array ...........................................................................................................63 Declaration ................................................................................................................. 65 Array Operation .......................................................................................................... 65 Iteration (Looping)...................................................................................................... 67 Sorting ........................................................................................................................ 68 More Functions .......................................................................................................... 70 Chapter 6. String Manipulation ....................................................................................73 Declaration ................................................................................................................. 75 Comparision ............................................................................................................... 75 Searching .................................................................................................................... 76 Replacement............................................................................................................... 76 Splitting....................................................................................................................... 77 Formatting .................................................................................................................. 78 Regular Expression – RegEx ........................................................................................ 79 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 3
  • 4. Chapter 7. HTTP Basic...................................................................................................83 HTTP Fundamentals.................................................................................................... 85 File Upload.................................................................................................................. 88 Cookie ......................................................................................................................... 90 Session ........................................................................................................................ 91 Chapter 8. OOP – Object Oriented Programming .........................................................93 OOP Fundamentals..................................................................................................... 95 Properties ................................................................................................................... 96 Methods ..................................................................................................................... 97 Inheritance & Overriding .......................................................................................... 101 Chapter 9. File Handling ............................................................................................. 107 File Handle ................................................................................................................ 109 File Manipulation...................................................................................................... 110 Directory ................................................................................................................... 112 File & Directory Constants........................................................................................ 113 Chapter 10. MySQL..................................................................................................... 115 DBMS Fundamentals ................................................................................................ 117 MySQL Fundamentals............................................................................................... 118 MySQL Basics ............................................................................................................ 122 Using phpMyAdmin .................................................................................................. 125 MySQL in PHP ........................................................................................................... 138 Chapter 11. Logging & Debugging .............................................................................. 141 Log Configuration ..................................................................................................... 143 PhpEd Debugger Installation .................................................................................... 143 Debugging................................................................................................................. 145 Chapter 12. OOP Advanced ........................................................................................ 149 Interface ................................................................................................................... 151 Abstract Class, Method ............................................................................................ 152 Final Class, Method .................................................................................................. 153 Lazy Loading ............................................................................................................. 154 Magic Methods......................................................................................................... 154 Chapter 13. MySQL Advanced .................................................................................... 159 Table Joining ............................................................................................................. 161 PHP Data Object (PDO) ............................................................................................. 164 Chapter 14. Software Engineering Basic ..................................................................... 167 Requirement Gathering............................................................................................ 169 Use-Case Diagram .................................................................................................... 171 Class Diagram ........................................................................................................... 177 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 4
  • 5. Chapter 15. XML & Web Service ................................................................................. 181 XML Basics ................................................................................................................ 183 SimpleXML Class ....................................................................................................... 184 Web Services Basics.................................................................................................. 185 SOAP ......................................................................................................................... 186 JSON Overview ......................................................................................................... 189 Chapter 16. Security ................................................................................................... 191 Security Basics .......................................................................................................... 193 Database Security ..................................................................................................... 193 Website Security....................................................................................................... 194 Session Security ........................................................................................................ 199 File System Security.................................................................................................. 201 Chapter 17. Advanced PHP Topics .............................................................................. 203 PHP.INI File Overview ............................................................................................... 205 Date & Time.............................................................................................................. 206 Email Sending ........................................................................................................... 208 Image Processing ...................................................................................................... 209 cURL library .............................................................................................................. 210 Smarty ...................................................................................................................... 211 Different between PHP5 & PHP4 ............................................................................. 212 Chapter 18. Design Pattern ........................................................................................ 215 Fundamentals ........................................................................................................... 217 Singleton Pattern ...................................................................................................... 217 Factory Pattern ......................................................................................................... 218 Strategy Pattern ....................................................................................................... 220 Model-View-Controller (MVC) Pattern .................................................................... 221 Chapter 19. E-Commerce Website .............................................................................. 225 E-Commerce Fundamentals ..................................................................................... 227 Website Optimization............................................................................................... 228 SEO Basics ................................................................................................................. 228 Website Analytic – Google Analytic Setup ............................................................... 230 Chapter 20. Zend PHP 5 Certification – ZCE (Zend Certified Engineer)........................ 243 Zend Certification Introduction ................................................................................ 245 Zend PHP 5 Certification Exam ................................................................................. 246 Further Reading.......................................................................................................... 249 UseFul Websites ......................................................................................................... 250 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 5
  • 6. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 6
  • 7. Chapter 1 Web Design Basics Keywords: Web design, editor, tool, photo, form, html, tag, style, javascript. Subjects: 1.1. Web Design Toolbox 1.2. HTML Editor – Dreamweaver CS3 1.3. HTML Basics 1.4. HTML Form 1.5. CSS 1.6. Javascript PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 7
  • 8. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 8
  • 9. 1.1. Web Design Toolbox: 1.1.1. Image Manipulating: Photoshop, GIMP, Illustrator… PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 9
  • 10. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 10
  • 11. 1.1.2. Animation Creator: Photoshop, Flash, Flex, Maya, 3DS Max… PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 11
  • 12. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 12
  • 13. 1.1.3. HTML Editor: Dreamweaver, Notepad++… PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 13
  • 14. 1.1.4. CSS Editor: Dreamweaver, Rapid CSS, Notepad++… PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 14
  • 15. 1.1.5. Javascript Editor: Dreamweaver, 1st Javascript Editor, Notepad++… PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 15
  • 16. 1.2. HTML Editor – Dreamweaver CS3: - Main Dreamweaver CS3 interface - Auto-complete function - Collapse selected script: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 16
  • 17. - Property Inspector Panel: - Create a Local Site: Or: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 17
  • 18. Or: - After creating site, the FILES panel will become: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 18
  • 19. - Open an Local Site: - Manage Site Files: In the Files Panel, right click the root (top level) and select your function (New File, New Folder…) PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 19
  • 20. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 20
  • 21. - Create new file PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 21
  • 22. 1.3. HTML Basics: 1.3.1. HTML Structure: <html> <head> <title>Four Square Cafe</title> </head> <body> Four Square Café is located at the intersection of Melrose and Sunset Avenues in Los Angeles. We are a cafe with our own bakery, and also have a charcuterie for your favorite meats and cheeses. We offer breakfasts and made to order sandwiches. You can buy fresh, hot from the oven bread for your home twice a day, at 8 am and 5 am daily. In our Café, we are also famous for fresh organic coffee and tea made with mountain water. Each cup is in its own single cone and paper filter and dripped right into your cup. We then start over for the next customer. Today's Specials ....................content deleted .............................. </body> </html> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 22
  • 23. 1.3.2. Popular HTML Tag: - Break line: br - Heading: h1, h2, h3, h4, h5, h6. - Paragraph: p - Link: a - Image: img - Text formatting: b, i, strong - Tables: table, tr, th, td - List: ul, ol, dl, li - Form: form, input, textarea, select - DIV, SPAN Tag: div, span 1.3.3. HTML Meta Tag: <meta name="description" content="Free Web tutorials" /> <meta name="keywords" content="HTML,CSS,XML,JavaScript" /> <meta name="author" content="Duy Tuan" /> <meta http-equiv="refresh" content="4;URL=http://example.com/"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 1.4. HTML Form: 1.4.1. Using Dreamweaver to insert Form element: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 23
  • 24. 1.4.2. Form Elements: 1.4.2.1. Text Field: <form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> </form> 1.4.2.2. Button: <form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"><br /> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 24
  • 25. <input type="submit" value="Send"> </form> 1.4.2.3. Radio button: <form method="post" action="mailto:youremail@email.com"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input type="radio" name="size" value="small">Small <input type="radio" name="size" value="medium">Medium <input type="radio" name="size" value="large">Large <br /> <input type="submit" value="Email Myself"> </form> 1.4.2.4. Check box: <form method="post" action="mailto:youremail@email.com"> Select your favorite cartoon characters. <input type="checkbox" name="toon" value="Goofy">Goofy <input type="checkbox" name="toon" value="Donald">Donald <input type="checkbox" name="toon" value="Bugs">Bugs Bunny <input type="checkbox" name="toon" value="Scoob">Scooby Doo <input type="submit" value="Email Myself"> </form> 1.4.2.5. Dropdown list: <form method="post" action="mailto:youremail@email.com"> College Degree? <select name="degree"> <option>Choose One</option> <option>Some High School</option> <option>High School Degree</option> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 25
  • 26. <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> </select> <input type="submit" value="Email Yourself"> </form> 1.4.2.6. Selection form: <form method="post" action="mailto:youremail@email.com"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option> <option value="ska" >Ska</option> <option value="jazz" >Jazz</option> <option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form> 1.4.2.7. Upload form: <input type="hidden" name="MAX_FILE_SIZE" value="100" /> <input name="file" type="file" /> 1.4.2.8. Text Area: <form method="post" action="mailto:youremail@email.com"> <textarea rows="5" cols="20" name="comments"> Enter Comments Here </textarea> <input type="submit" value="Email Yourself"> </form> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 26
  • 27. 1.5. CSS: 1.5.1. CSS Selector: - The selector name creates a direct relationship with the HTML tag you want to edit. - Many types of selector: type, class, id, child, universal… - Ex: <div id="container" class="bluebox largebox">…</div> 1.5.2. CSS Syntax: SELECTOR { PROPERTY: VALUE } 1.5.3. Embed CSS to HTML page: - Internal CSS: <style type="text/css"> p {color: white; } body {background-color: black; } </style> - External CSS: <link rel="stylesheet" type="text/css" href="test.css" /> - Inline CSS: <p style="background: blue; color: white;"> Text </p> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 27
  • 28. 1.6. Javascript: 1.6.1. Embed Javascript to HTML page: - Internal: <script type="text/javascript"> //script here </script> - External: <script type="text/javascript" src="file.js"></script> - Inline: <img src="button.gif" onclick="alert('test');" /> 1.6.2. Javascript Basics: 1.6.2.1. Comments: // this is a comment /* so is this */ 1.6.2.2. Function: function anExample(param1,param2) { alert(param1+param2); } <a href="javascript:void(0)" onClick="anExample("Ec","Lios") > Example </a> 1.6.2.3. IF Statement: function anIfExample(param) { if (param==1) {alert("Hello Philip");} else if (param==2) {alert("Hello Terrance");} else {alert("Hello everyone");} } <a href="javascript:void(0)" onClick="anIfExample(1)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="anIfExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="anIfExample(2)" > Example 3</a> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 28
  • 29. 1.6.2.4. SWITCH Statement: function aSwitchExample(param) { switch(param) { case 1: alert("Hello John"); break; case 2: alert("Hello Peter"); case 3: alert("Hello Moose"); break; default: alert("ahhh no moosi"); break; } } <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aSwitchExample(2)" > Example 3</a> 1.6.2.5. WHILE Statement: function aWhileExample(param) { counter=0; while(counter<param) { alert("round we go " + counter); counter++; // this adds one to the counter, could have typed // counter=counter+1; } } <a href="javascript:void(0)" onClick="aWhileExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aWhileExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aWhileExample(3)" > Example 3</a> 1.6.2.6. DO Statement: function aDoExample(param) { counter=0; do { alert("round we go " + counter); counter++; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 29
  • 30. // this adds one to the counter, could have typed // counter=counter+1; } while (counter<param) } <a href="javascript:void(0)" onClick="aDoExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aDoExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aDoExample(3)" > Example 3</a> 1.6.2.7. FOR Statement: function aForExample(param) { for(counter=0; counter<param; counter++) { alert("round we go " + counter); } } <a href="javascript:void(0)" onClick="aForExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aForExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aForExample(3)" > Example 3</a> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 30
  • 31. Chapter 2 PHP Workspace Keywords: installation, IDE, server-side, scripting, interpreter, opensource, CLI, service, GUI, code navigator, DB Client, php interactive, request, response. Subjects: 2.1. PHP Introduction 2.2. AppServ Installation 2.3. Using AppServ 2.4. PHP IDE - PhpEd 2.5. Using PHP Interactive PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 31
  • 32. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 32
  • 33. 2.1. PHP Introduction: - How PHP Works: - PHP stands for "PHP Hypertext Preprocessor" - PHP is a widely used open source. Stable version is PHP 5.3.0 (PHP6 beta) - Runs on Server -> Server-Side Scripting language - It's fast, free, easy to use, run on many Operating Systems(OS), secure, customizable, support community. - PHP supports many database (MySQL, Oracle, Sybase, PostgreSQL…) - File extension: ".php", ".php3", ".php5" or ".phtml" PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 33
  • 34. interacting via browser Working via CLI (command-line interface) Working via GUI(Graphical User Interface) – Desktop Application PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 34
  • 35. Working via web services (no need interface) 2.2. AppServ Installation: - It will install Apache, PHP, MySQL in one window executive file (.exe) - Best solution for creating an environment to learning, developing and testing website. - Download AppServ at: http://www.appservnetwork.com/ - Install like a normal window application. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 35
  • 36. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 36
  • 37. 2.3. Using AppServ: 2.3.1. AppServ 2.10 Directory Structure: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 37
  • 38. 2.3.2. Edit Server config using start menu: 2.3.3. Restart/ Stop / Start Apache / MySQL Services using start menu: 2.4. PHP IDE - PhpEd - Main Software interface: + Menu Bar + Toolbar (File, navigator, HTML element, Debugger…) + Code Explorer Panel (Left) + Source code editor (Center) + Code navigator Panel (Rignt) PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 38
  • 39. - Some main features: + Autocomplete code: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 39
  • 40. + Full screen support + Database Client + Support HTML, CSS, JS language PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 40
  • 41. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 41
  • 42. + Debuging & Profiling tool + Collapse / Expand Selected code. 2.5. Using PHP Interactive 2.5.1. Introduction: PHP Interactive is a simple PHP program that lets the user to write code in a text area (actually multiple text areas, with tabs to switch), and see the output of the code just pressing the update button. The scripts are persistent, and the program supports a raw and html output mode, in order to see the raw script output or to interpret it as html. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 42
  • 43. 2.5.2. Installation: - Download at: http://www.hping.org/phpinteractive/ - Unzip and copy to www folder and rename to "phpa". PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 43
  • 44. - Access php interactive using URL: http://localhost/phpa/ PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 44
  • 45. Chapter 3 PHP Basics Keywords: syntax, data type, variable, constant, type casting, operator, control structure, condition, loop, precidence, priority, expression. Subjects: 3.1. PHP Syntax 3.2. Data Types 3.3. Variable & Constant 3.4. Operators 3.5. Control Structure PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 45
  • 46. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 46
  • 47. 3.1. PHP Syntax: 3.1.1. PHP Tags: - PHP code can be inserted directly into a text file (.php…). The interpreter will output any text outside the tags, and execute the code that is between the tags 3.1.2. PHP Source code: - Every PHP script is made up of statements: function calls, variable assignments, data output…Most of the time, these statements must be terminatd with a semicolon(;). PHP is whitespace-intensitive. 3.1.3. Comments: - PHP has many types of comment //Single line comment #Single line comment /* Multi-line comment */ /** * API Documentation Example * * @param string $bar */ Function foo($bar){} <?php //this is the end tag "?>" of PHP ?> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 47
  • 48. 3.1.4. Code Block: is a series of statements enclosed between two braces { //Some comments f(); //a function call } 3.2. Data Types: 3.2.1. Numeric Value: - Integer numbers: . Decimal: normally used numbers. Ex: 10; -100… (invalid: 1 000) . Octal: begin with zero. Ex: 0666; 0777… . Hexadecimal: Begin with "0x" or "0X". Ex: 0x12; 0xAF; 0XFF… - Floating-point numbers: have a fractional component. . Decimal: 0.12; 3.45… . Exponential: 4E6; 1e2… 3.2.2. String: A series of single characters, such as Vietnam. 3.2.3. Boolean: A TRUE or FALSE value. 3.2.4. Array: can store any other data type. 3.2.5. Object: containers of both data and code. 3.2.6. Other types: - NULL : indicates that a variable has no value. - resource: used to indicate external resources. Such as handing files, manipulating images 3.2.7.Type casting: can be done automatically or manually. Ex: $a = 1.5; $b = (int)$a; // $b will be assigned 1 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 48
  • 49. 3.3. Variable & Constant: 3.3.1. Variables: - Can contain any type of data, such as strings, integers, objects, arrays…PHP is loosely typed. - Identified by a dollar sign $ - Variable name must be using only letters (a-z, A-Z), numbers and the underscore character "_". - Variable name must start with a letter or an underscore - Case-sensitive. - Examples: $var = "ok"; // Valid name $_var = "ok"; // Valid name $4var = "not ok"; //Invalid name, starts with a number 3.3.2. Variable Variables: - Variable whose name is contained in another variable. Example: $var = 'name'; $$var = 'I love php'; echo $name; // Displays 'I love php' 3.3.3. Constants: - Can be accessed for any scope within a script - They can only contain numeric values, strings and booleans. - Naming like rule of variable name, but not start with dollar sign $ - It's usually defined constants using only upper-case names. - Examples: define('EMAIL', 'myemail@example.com'); echo EMAIL; // Displays 'myemail@example.com' define('5CLASS, 'some value); // Invalid name PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 49
  • 50. 3.4. Operators: 3.4.1. Assignment Operator: assigning data to variables. Ex: $a = 1; // Assign the integer 1 to $a 3.4.2. Arithmetic Operators: performing basic math functions. Ex: $a = 5 + 6; $b = $a – 1; 3.4.3. String Operators: joining two or more strings. Ex: $myString = 'hello' . '-' . 'world'; // $myString will be string 'hello-world' 3.4.4. Comparison Operators: comparing two pieces of data. Ex: $a = 10; echo $a == 10; // outputs 1 3.4.5. Logical Operators: performing logical operations on Boolean values. $a = false; echo !$a; //outputs 1 3.4.6. Bitwise Operators: manipulating bits using boolean math. Ex: $x = 1; echo $x << 1; // Outputs 2; echo $x << 2; // Outputs 4; 3.4.7. Error Control Operators: Suppressing errors. Prepending @ to an expression, this operator causes PHP to ignore almost all error messages that occur that expression is being evaluated. Ex: $x = @mysql_connect(); 3.4.8. Execution Operators: executing system commands. Backtick operator (`) makes it possible to execute a shell command and retrieve its output. Ex: echo `dir c:`; // outputs info like open command window, type "dir c:" 3.4.9. Incrementing/Decrementing Operators: incrementing and decrementing numerical values. Ex: $a = 1; echo $a++; // Outputs 1, $a is now equal to 2 echo ++$a; //Outputs 3, $a is now equal to 3 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 50
  • 51. 3.4.10. Type Operators: instanceof operator is used to determine whether a PHP variable is an instantiated object of a certain class. Ex: echo $a instanceof MyClass; 3.4.11. Operator Precedence and Associativity: 3.5. Control Structure: 3.5.1. Conditional Structures: 3.5.1.1. If…Else Statement: if (condition_1) { statement_1 } [elseif (condition_2) { statement_2 }] ... [elseif (condition_n_1) { statement_n_1 PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 51
  • 52. }] [else { statement_n }] 3.5.1.2. Switch Statement: switch (expression) { case label_1: statements_1 [break;] case label_2: statements_2 [break;] ... default: statements_n [break;] } 3.5.2. Loop Structures: 3.5.2.1. While Loop: while (condition) { code to be executed; } 3.5.2.2. Do…While Loop: do { code to be exected; } while (condition); 3.5.2.3. For Loop: for (initialization; condition; increment) { code to be executed; } PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 52
  • 53. 3.5.2.4. Foreach Loop: foreach (array as value) { code to be executed; } foreach (array as key => value) { code to be executed; } 3.5.3. Break & Continue Statements 3.5.3.1. break: used to immediately exit a loop. It takes an optional parameter, which allows you to exit from multiple nested loops. Ex: $i = 0; $j = 0; while ($i < 10) { while ($j < 10) { if ($j == 5) {break 2;} // breaks out of two while loops $j++; } $i++; } 3.5.3.2. continue: want to skip over the remainder of an iteration and immediately skip over to the next. Like with break, you can provide it an integer parameter to specify the level of nesting to which the it applies. Ex: for ($i=0; $i<=10; $i++) { if (i==3){continue;} echo "The number is ".$i; echo "<br />"; } Chapter Exercise: A> Research typing casting on resource data type. B> What is the function used to check a declared variable? Is it always true in all situations? PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 53
  • 54. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 54
  • 55. Chapter 4 Functions Keywords: function, parameter, argument, reference, value, global, static, scope, return, null, empty, language construct. Subjects: 4.1. Introduction 4.2. Syntax 4.3. Parameter & Argument 4.4. Useful Functions PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 55
  • 56. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 56
  • 57. 4.1. Introduction: - Function is the heart of PHP programming. - Encapsulate any piece of code in a way that it can be called again and again. - Classify between Language constructs and Functions. • Fastest things in PHP are the language constructs. • They are highly optimized in the interpreter • Don’t require calling external libraries • Don’t call a function if there is a language construct. As an example, using a casting operator like (int) $total is much more efficient than using the function intval($foo) • Function calling generate considerably amount of overhead. Using a language construct avoid • isset() and unset() are both language constructs, even though they mostly act like functions. However calling them does not generate the function overhead. • Common language construct: echo() empty() isset() unset() eval() exit() die() include() include_once() require() require_once() return 4.2. Syntax: 4.2.1. Create function: function name is case-intensitive. function name() { //your code here } Ex: function hello() { echo 'Hello World'; } hello(); // Displays "Hello World"; HeLLo(); // Displays "Hello World"; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 57
  • 58. 4.2.2. Return values: - All functions in PHP return a value (event if you don't using return keyword, it will return NULL) - return keyword allows you to interrupt the execution of a function and exit it. - Ex: function hello() { return 'Hello World'; } $str = hello(); // Assigns return value "Hello World" to $str echo hello(); // Displays "Hello World" - Functions can be declared so that they return by reference, usually resource type. Ex: function &query() { $result = mysql_query('SELECT email FROM users'); return $result; } 4.3. Parameter & Argument: 4.3.1. Different between Parameter and Argument: - The term parameter refers to any declaration within the parentheses following the function name in a function declaration or definition; the term argument refers to any expression within the parentheses of a function call. - This example demonstrates the difference between a parameter and an argument: // $var is a parameter function test($var) { foo(5, 'a'); //5 and 'a' are arguments return 0; } 4.3.2. Passing by value: by default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). Ex: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 58
  • 59. function myFunc($str) { $str = 'bob'; echo $str; } $str = 'jack'; myFunc($str); // Displays "bob" echo $str; // Displays 'jack' 4.3.3. Passing by reference: to allow function to modify its arguments, they must be passed by reference.Ex: function myFunc(&$str) { $str = 'bob'; echo $str; } $str = 'jack'; myFunc($str); // Displays "bob" echo $str; // Displays 'bob 4.3.4. Default argument values: Set default value for an argument if it's not passed to function. Ex: function myFunc($str = 'mother') { echo $str; } $str = 'jack'; myFunc($str); // Displays "jack" myFunc(); // Displays "mother" Question: What will output when running this script? function myFunc(&$str = 'mother') { // } $str = 'jack'; myFunc($str); echo $str; 4.3.5. Variable Scope: is the context within which it is defined. Most part all PHP variables only have a single scope. View this script: $a = 1; /* global scope */ function test() { PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 59
  • 60. echo $a; /* reference to local scope variable */ } test(); // Not display "1" 4.3.5.1. Using global scope variables: - Using global keyword. Ex: $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; // Display "3" - Using $GLOBALS variable. Ex: $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; // Display "3" 4.3.6. Static variables: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. - Ex1: function test() { $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "0"; - Ex2: function test() { PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 60
  • 61. static $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "1"; - Note: static variable must not be declared as the result of an expression, it will cause a parse error. Ex: static $var = 1+2; // wrong (as it is an expression) static $var = sqrt(2); //wrong (as it is an expression) 4.4. Useful Functions: 4.4.1. func_num_args(): returns the number of arguments passed to the function. 4.4.2. func_get_arg(int $index): returns an item from the argument list. 4.4.3. func_get_args(): returns an array comprising a function's argument list. 4.4.4. function_exists(string $function_name): return TRUE if the given function has been defined. Chapter Exercise: A> Write a script to calculate and return the sum of all arguments (the number of argument is unknown) of a function. Example: $a = calculate(1,2,3,4,6,2); // $a = 18 B> List 3 global scope variables beside $GLOBALS PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 61
  • 62. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 62
  • 63. Chapter 5 Array Keywords: array, element, index, key, value, associate, sort, shuffle, random, iteration, loop, stack, queue, pop, push, shift. Subjects: 5.1. Declaration 5.2. Array Operation 5.3. Iteration (Looping) 5.4. Sorting 5.5. More Functions PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 63
  • 64. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 64
  • 65. 5.1. Declaration: 5.1.1. Declare an array variable: $a = array(10, 20, 30); $a = array('a' => 10, 'b' => 20, 'key' => 30); $a = array(5 => 1, 3=> 2, 1=>3, ); $a = array(); 5.1.2. Array operator []: $a[] = 10; $a['key'] = 'value'; echo $a['key']; // Displays "value" 5.1.3. Multi-dimension Arrays: element of an array is an array too. Ex: $a = array( array('red', 'green', 'blue'), array('small', 'medium', 'large') ); 5.2. Array Operation: 5.2.1. Printing array: - Using print_r() to print only one array. Ex: $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r($a); // Outputs: Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) - Using var_dump() can print more than one array. $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); $b = array('x', 'y'); PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 65
  • 66. var_dump($a, $b); // Outputs: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> array(3) { [0]=> string(1) "x" [1]=> string(1) "y" [2]=> string(1) "z" } } array(2) { [0]=> string(1) "x" [1]=> string(1) "y" } 5.2.2. Counting array elements: using count() function. Ex: $a = array(5,6,7); $element = count($a); // $element will be 3 5.2.3. Checking a variable is an array: using is_array() function. Ex: $a = array(5,6,7); $result = is_array($a); var_dump($result); // Displays "bool(true)" 5.2.4. Checking an element exists: using isset() function. - Note: if element value equal NULL, isset() still return FALSE. Ex: $a = array('a' => NULL, 'b' => 2); $test = isset($a['a']); // $test will be assigned FALSE In this case, using array_key_exists() function. Ex: $a = array('a' => NULL, 'b' => 2); $test = array_key_exists('a', $a); // $test will be TRUE PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 66
  • 67. 5.2.5. Deleting an element: using unset() function. Ex: $a = array('a', 'b', 'c'); unset($a[1]); print_r($a); // Outputs: Array ( [0] => a [2] => c ) 5.3. Iteration (Looping): 5.3.1. Array Pointer: using key(), current(), next(), prev(), reset(), end() function. Ex: $a = array('a', 'b', 'c'); while(key($a) !== null) { echo key($a) . ': ' . current($a) . PHP_EOL; // Move pointer to next element next($a); } // Outputs: 0: a 1: b 2: c It's not a common way for iteration array. 5.3.2. Using for() and foreach() function: - Ex 1: $a = array(3, 5, 7); $iCount = count($a); for($i = 0; $i < $iCount; $i++) { echo $a[$i] . '.'; } // Displays "3, 5, 7, " PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 67
  • 68. - Ex 2: $a = array('blue' => 'small', 'green' => 'large'); foreach($a as $key => $value) { echo $key. ' : ' . $value . ','; } //Displays "blue : small, green : large, " 5.4. Sorting: Function name Sorts by Maintains key Order of sort Related functions association sort() Value No Low to high rsort() rsort() Value No High to low sort() asort() Value Yes Low to high arsort() arsort() Value Yes High to low asort() natsort() Value Yes Natural natcasesort() natcasesort() Value Yes Natural, case natsort() insensitive ksort() Key Yes Low to high asort() krsort() Key Yes High to low ksort() usort() Value No User defined uasort() uasort() Value Yes User defined uksort() uksort() Key Yes User defined uasort() shuffle() Value No Random array_rand() array_multisort() Value Associative First array or array_walk() yes, numeric sort options no Example of using sort() function: $fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "n"; } PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 68
  • 69. // Outputs: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Example of using asort(): $fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); asort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "n"; } // Outputs: fruits[b] = apple fruits[d] = banana fruits[a] = lemon fruits[c] = orange Example of using ksort(): $fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); ksort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "n"; } // Outputs: fruits[a] = lemon fruits[b] = apple fruits[c] = orange fruits[d] = banana PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 69
  • 70. 5.5. More Functions: 5.5.1. list() : assign variables as if they were an array. 5.5.2. array_merge(): merge one or more arrays. 5.5.3. array_slice(): extract a slice of the array. 5.5.4. array_diff_*() group: computes the difference of arrays 5.5.5. array_intersect_*() group: computes the intersection of arrays. 5.5.6. array_push(), array_pop(), array_shift(), array_unshift(): insert/ remove an element from array using queue and stack operation. STACK OPERATION PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 70
  • 71. QUEUE OPERATION Chapter Exercise: A> Can we use arithmetic operator (+, -, *, /) between 2 arrays. If yes, what is the result? B> Simulate the game " ánh bài Ti n lên" of Vietnamese, there are 4 people in game, each has 13 cards. Using functions from beginning to this chapter to write the action of shuffle cards and give each one 13 random cards. ***** difficult : write the function to find the number of "3 ôi thông" in 13 cards of each person. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 71
  • 72. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 72
  • 73. Chapter 6 String Manipulation Keywords: string, haystack, needle, text, character, case-sensitive, case- insensitive, HEREDOC, escape character, compare, search, extract, replace, position, format, regular expression, expression, match, pattern, delimiter, PCRE, overhead. Subjects: 6.1. Declaration 6.2. Comparision 6.3. Searching 6.4. Replacement 6.5. Splitting 6.6. Formatting 6.7. Regular Expression – RegEx PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 73
  • 74. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 74
  • 75. 6.1. Declaration: 6.1.1. Normal Assignment: 1. $a = "Using double quote"; 2. $b = 'Using single quote'; 3. $c = "control characters in n double quote only"; 4. $c2 = "052"; 5. $c3 = "x2a"; 6. $num = 1; 7. $d = "$num is parsed"; // $d equals "1 is parsed" 8. $e = "$numx is not parsed"; // $e equals " is not parsed" 9. $f = "{$num}x is parsed"; // $f equals "1x is parsed" 6.1.2. HEREDOC: $who = "World"; $str = <<<TEXT Hello $who TEXT; // Displays "Hello World" 6.2. Comparision: 6.2.1. Comparison Operator : using operators == , !=, ===, !== . Ex: $a = '123abc'; $b = '123Abc'; $c = 123; $test1 = ($a == $b); // $test1 equals FALSE $test2 = ($a == $c); // $test2 equals TRUE $test3 = ($a === $c); // $test3 equals FALSE 6.2.2. Using strcmp() : compare two string, it's case-sensitive. Using strcasecmp() to compare two string, it's case-insensitive. Ex: $str = 'Hello world'; $test1 = strcmp($str, 'hello world'); // $test1 equals -1 $test2 = strcasecmp($str, 'hello world'); // $test2 equals 0 $test3 = strcmp('a', 'A'); // $test3 equals 1; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 75
  • 76. 6.3. Searching: 6.3.1. strpos(): Find position of first occurrence of a string. It's case-sensitive. - Ex: $pos = strpos('mystring', 'str'); // $pos equals 2 $pos = strpos('mystring', 'hi'); // $pos === FALSE 6.3.2. strrpos(): Find position of last occurrence of a char in a string. It's case-sensitive. Ex: $pos = strrpos('mystringmy', 'my'); // $pos equals 8 6.3.3. strstr(): Find first occurrence of a string. It's case-sensitive. Ex: $pos = strstr('mystring', 'str'); // $pos equals "string" $pos = strstr('mystring', 'hi'); // $pos === FALSE 6.3.4. stripos() is the case-insensitive version of strpos(). 6.3.5. strripos() is the case-insensitive version of strrpos(). 6.3.6. stristr() is the case-insensitive version of strstr(). 6.4. Replacement: 6.4.1. str_replace(): replace all occurrences of the search string with the replacement string, it's case-sensitive. str_ireplace() is the case-insensitive of str_replace(). Ex: echo str_replace('abc', 'z', 'abcdef' ); //Displays "zdef" echo str_replace('ABC', 'z', 'abcdef'); // Displays "abcdef" echo str_ireplace('ABC', 'z', 'abcdef'); // Display "zdef" 6.4.2. substr_replace(): replace text within a portion of a string. Ex: echo substr_replace('012345abcdef', 'zzz', 5); // Displays "01234zzz" PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 76
  • 77. 6.5. Splitting: 6.5.1. Retun part of string: using substr(). Ex: echo substr('abcdef', 1); // bcdef echo substr('abcdef', 1, 3); // bcd echo substr('abcdef', 0, 4); // abcd echo substr('abcdef', 0, 8); // abcdef echo substr('abcdef', -1, 1); // f 6.5.2. Split string to array: using explode() and split() function. Ex: $s1 = 'a,b,c,d'; $a1 = explode(',', $s1); print_r($a1); $s2 = '1,2,3,4'; $a2 = split(',', $s2, 2); print_r($a2); //Displays: Array ( [0] => a [1] => b [2] => c [3] => d ) Array ( [0] => 1 [1] => 2,3,4 ) Question: what displays when running this script: echo count(split('/', '///')); 6.5.3. Join array elements to a string: using implode() and join() function. Ex: $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // displays "lastname,email,phone" PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 77
  • 78. 6.6. Formatting: 6.6.1. Number formatting: using number_format() to formatting numerical value. Ex: echo number_format("100000.123", 2, '.', ','); // Displays "100,000.12" 6.6.2. Output formatting: using printf() to print a string in a specified format. Ex: - %s, %d, %f: Specifiers. Specifier Format b The argument is treated as an integer and is presented as an integer in binary form. c The argument is treated as an integer and is presented as the ASCII character for that value. d The argument is treated as an integer and presented as a signed integer. u The argument is treated as an integer and presented as an unsigned integer. f The argument is treated as a floating-point number and presented as a floating-point number. o The argument is treated as an integer and presented as its octal representation. x The argument is treated as an integer and presented as a hexadecimal number (using lowercase letters). X The argument is treated as an integer and presented as a hexadecimal number (using uppercase letters). - Formatting functions: Function Arguments Result printf Format, args Writes output sprintf Format, args Return result vprintf Format, array of args Writes output vsprintf Format, array of args Returns result fprintf Stream resource, format, args Writes output to stream PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 78
  • 79. 6.7. Regular Expression – RegEx: - The most powerful tools in the string manipulation toolbox are regular expressions 6.7.1. Introduction: 6.7.2. Character Class: allow a pattern to match multiple characters simultaneously Metacharacter Characters Matched d Digits 0-9 D Anything not a digit w Any alphanumeric character or an underscore (_) W Anything not an alphanumeric character or an underscore s Any whitespace (spaces, tabs, newlines) S Any non-whitespace character . Any character except for a newline ^ Match the start of the string $ Match the end of the string Ex 1: the expression /ab[cd]e/ matches abce and abde. Ex 2: the expression /ab[c-ed]/ will match abc, abd, abe and any combination of ab followed by a digit. 6.7.3. Quantifiers: allows you to specify the number of times a particular character or metacharacter can appear in a matched string. 4 types of quantifiers: PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 79
  • 80. * The character can appear zero or more times + The character can appear one or more times ? The character can appear zero or one times {n,m} The character can appear at least n times, and no more than m. Either parameter can be omitted to indicated a minimum limit with no maximum, or a maximum limit without a minimum, but not both Ex: the expression /ab?c/ matches both ac and abc, while ab{1,3}c matches abc, abbc, abbbc. 6.7.4. Match & Extract strings: preg_match() and preg_match_all(). Ex: $str = 'foobar: 2008 - hello: 2009'; preg_match('/(?<name>w+): (?<digit>d+)/', $str, $matches); print_r($matches); //Displays: Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 ) Ex 2: $str = 'foobar: 2008 - hello: 2009'; preg_match_all('/(w+): (d+)/', $str, $matches); print_r($matches); //Displays: Array ( [0] => Array ( [0] => foobar: 2008 [1] => hello: 2009 ) [1] => Array ( [0] => foobar [1] => hello ) [2] => Array ( [0] => 2008 [1] => 2009 ) ) PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 80
  • 81. 6.7.5. Replace string with Regex: preg_replace(). Ex: $string = 'April 15, 2003'; $pattern = '/(w+) (d+), (d+)/i'; $replacement = '${1}x,$3'; echo preg_replace($pattern, $replacement, $string); // Displays "Aprilx,2003" 6.7.6. Split string by a regular expression: using preg_split(). Ex: $keywords = preg_split("/[ds,]+/", "hyper1 lang2, prog"); print_r($keywords); // Displays Array ( [0] => hyper [1] => lang [2] => prog ) Chapter Exercise: A> Write the function to check the file is the image or not. Input: filename, return TRUE/FALSE. Valid image type: jpg, jpeg, png, gif, bmp. B> Write the regular expression pattern to match an URI of an image. Example: http://www.example.com/photo/some-directory/imagename.gif C> Write the regular expression pattern to match an email address. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 81
  • 82. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 82
  • 83. Chapter 7 HTTP Basic Keywords: http, html, header, form, request, response, get, post, cookie, session, authentication, domain, timeout, expire, redirect, caching, file upload, apache, rewrite rule, htaccess. Subjects: 7.1. HTTP Fundamentals 7.2. File Upload 7.3. Cookie 7.4. Session PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 83
  • 84. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 84
  • 85. 7.1. HTTP Fundamentals: 7.1.1. How HTTP works: (RFC 2616) 7.1.2. GET Method: - Change URL after submit form - using global variable $_GET or $_REQUEST to access data in form. Ex: $firstName = $_GET['FirstName']; $salary = $_GET['Salary']; $contractor = $_GET['Contractor']; 7.1.3. POST Method: - Not change URL after submit form - using global variable $_POST or $_REQUEST to access data in form. Ex: $firstName = $_POST['FirstName']; $salary = $_POST['Salary']; $contractor = $_POST['Contractor']; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 85
  • 86. 7.1.4. HTTP Request: - Sample of request: -------------------------------------------------------------------------------------------------------- GET Header Request: GET /dumprequest HTTP/1.1 Host: djce.org.uk User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://www.google.com.vn/search?hl=vi&client=firefox-a&rls=org.mozilla:en- US:official&um=1&q=http%20request&ndsp=21&ie=UTF-8&sa=N&tab=iw POST Header Request: POST /path/script.cgi HTTP/1.0 From: frog@jmarshall.com User-Agent: HTTPTool/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 32 home=Mosby&favorite+flavor=flies PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 86
  • 87. 7.1.5. HTTP Response: HTTP/1.1 200 OK Date: Sun, 08 Oct 2000 18:46:12 GMT Server: Apache/1.3.6 (Unix) Keep-Alive: timeout=5, max=120 Connection: Keep-Alive Content-Type: text/html <html>... Some HTTP 1.1 status code: Status Reason Description Code Phrase 200 OK Generic successful request message response. This is the code sent most often when a request is filled normally. 201 Created The request was successful and resulted in a resource being created. This would be a typical response to a PUT method. 301 Moved The resource requested has been moved to a new URL Permanently permanently. Any future requests for this resource should use the new URL. This is the proper method of handling situations where a file on a server is renamed or moved to a new directory. Most people don't bother setting this up, which is why URLs “break” so often, resulting in 404 errors as discussed below. 302 Found The resource requested is temporarily using a different URL. The client should continue to use the original URL. 304 Not Modified The client sent a conditional GET request, but the resource has not been modified since the specified date/time, so the server has not sent it. 400 Bad request Server says, “huh?” Generic response when the request cannot be understood or carried out due to a problem on the client's end. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 87
  • 88. 401 Unauthorized The client is not authorized to access the resource. Often returned if an attempt is made to access a resource protected by a password or some other means without the appropriate credentials. 404 Not Found The most common HTTP error message, returned when the server cannot locate the requested resource. Usually occurs due to either the server having moved/removed the resource, or the client giving an invalid URL (misspellings being the most common cause.) 500 Internal Generic error message indicating that the request could not be Server Error fulfilled due to a server problem. 502 Bad Gateway The server, while acting as a gateway or proxy, received an invalid response from another server it tried to access on the client's behalf. 503 Service The server is temporarily unable to fulfill the request for internal Unavailable reasons. This is often returned when a server is overloaded or down for maintenance. 504 Gateway The server, while acting as a gateway or proxy, timed out while Timeout waiting for a response from another server it tried to access on the client's behalf. 7.1.6. Header: - Using function header() to send a HTTP header. Ex: header('Location: http://www.php.net/'); header("HTTP/1.0 404 Not Found"); 7.2. File Upload: 7.2.1. Prepare form: <form method="post" enctype="multipart/form-data" action="upload.php"> File to upload: <input type="file" name="myfile"><BR> <input type="submit" value="Submit"> </FORM> PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 88
  • 89. 7.2.2. Upload a file: - Get uploaded file's data using $_FILES. Ex: $name = $_FILES[myfile]['name']; $type = $_FILES[myfile][type]; $size = $_FILES[myfile][size]; $tmpname = $_FILES[myfile][tmp_name]; $error = $_FILES[myfile][error]; $uploadPath = 'uploads/photos/'.$name; // Begin to upload fileif (move_uploaded_file($tmpname, $uploadPath)) { echo 'Upload successfully!'; } 7.2.3. Upload multiple files: - HTML form: … File to upload: <input type="file" name="myfile[]"><BR> File to upload: <input type="file" name="myfile[]"><BR> … - PHP script: $nameA = $_FILES[myfile]['name'][0]; $tmpnameA = $_FILES[myfile][tmp_name][0]; $uploadPathA = 'uploads/photos/'.$nameA; $nameB = $_FILES[myfile]['name'][1]; $tmpnameA = $_FILES[myfile][tmp_name][1]; $uploadPathB = 'uploads/photos/'.$nameB; // Begin to upload files … PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 89
  • 90. 7.3. Cookie: 7.3.1. How cookies work: 7.3.2. Create cookies: using setcookie() function. Ex: $value = 'something from somewhere'; setcookie("test", $value); setcookie("test", $value, time()+3600); /* expire in 1 hour */ setcookie("test", $value, time()+3600, "/~test/", ".example.com", 1); 7.3.3. Get cookies data: using global variables $_COOKIES or $_REQUEST. Ex: echo $_COOKIE["test"]; 7.3.4. Delete a cookie: setcookie ("test", "", time() - 3600); PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 90
  • 91. 7.4. Session: 7.4.1. How sessions work: 7.4.2. Create sessions: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser. session_start(); $_SESSION['username'] = 'testing'; 7.4.3. Session ID processing: 7.4.3.1. Get the current Session ID: - session_id() : used to get or set the session id for the current session. Ex: $currentSessID = session_id(); 7.4.3.2. Re-generate Session ID: - session_regenerate_id() : Update the current session id with a newly generated one. 7.4.3.3. Example: session_start(); $old_sessionid = session_id(); PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 91
  • 92. session_regenerate_id(); $new_sessionid = session_id(); echo "Old Session: $old_sessionid<br />"; echo "New Session: $new_sessionid<br />"; 7.4.4. Delete a session: session_destroy(); Chapter Exercise: A> Design a webpage to display form for user login. The username is an email, and the password must be at least 6 characters. Password must be alphanumerical characters (a-z, A-Z, 0-9). If login success, displays the name of the user (extract from email) and the number of page which is refreshed by user. Ex: enter email: rasmus@myemail.com, password: abc3456ad5, website will display: Hello rasmus ! You refreshed 3 times. B> Write photo album function for the user (after login) from question A. a. Upload images (png,gif,jpeg) – 5 images in a submit form b. Store images in directory "uploads/images/". c. Max file size: 300KB d. File name: USERNAME_imagename e. If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be renamed to rasmus_image1i.gif PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 92
  • 93. Chapter 8 OOP Object-Oriented Programming Keywords: object, class, instance, inheritance, encapsulation, access, constructor, destructor, property, method, visibility, parent, self, this, override, public, protected, private. Subjects: 8.1. OOP Fundamentals 8.2. Properties 8.3. Methods 8.4. Inheritance & Overriding PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 93
  • 94. PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 94
  • 95. 8.1. OOP Fundamentals: 8.1.1. What is OOP ? - As we mentioned previously, the basic element of OOP is the class. A class contains the definition of data elements (or properties) and functions (or methods) that share some common trait and can be encapsulated in a single structure. 8.1.2. Declaring Class: Class name is case-insensitive class ClassName { // Some Properties // Some Methods } 8.1.3. Instantiating an Object: To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation. - In the class context, it is possible to create a new object by new self and new parent. Ex: $myClassInstance = new MyClass(); $copyInstance = $myClassInstance; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 95
  • 96. 8.2. Properties: 8.2.1. Declaration & Visibility: The default value must be a constant expression, not (for example) a variable, a class member or a function call. Ex: class foo { //valid declaration public $name; protected $age; private $type; public $var1 = "Test"; // String public $var2 = 1.23; // Numeric value public $var3 = array(1, 2, 3); // Array //invalid declaration $var4 = TRUE; public $var1 = 'hello '.'world'; public $var2 = <<<EOD hello world EOD; public $var3 = 1+2; public $var4 = self::myStaticMethod(); public $var5 = $myVar; } 8.2.2. Constant: Ex: class foo { const BAR = 'Hello World'; } echo foo::BAR; PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 96
  • 97. 8.3. Methods: 8.3.1. Declaration: - A class method/functions is the behavior/functionality of a class i.e. they provide the necessary code for the class in which it is defined. - A class method is exactly similar to PHP functions, it’s just that class functions are declared inside classes and accessed using the -> (arrow operator / dereferencing operator). - Methods can also be declared as either public, protected or private. - Example: class MyClass { public function myFunction() { echo 'You called MyClass::myFunction'; //call the private function $this->myPrivate(); } private function myPrivate() { echo "nThis is a private function."; } } $obj = new MyClass(); $obj->myFunction(); //Displays: You called MyClass::myFunction This is a private function. - A pseudo-variable, $this is available when a method is called from within an object context. Ex: class Shirt { public $color; private function getColor() { echo $this->color; } public function say() PHP Beginner & Intermediate ATHENA TRAINING & EDUCATION CENTER 97