SlideShare a Scribd company logo
1 of 79
Download to read offline
PHP WEB
DEVELOPMENT
The Project



A simple registration website
Download...



github.com/gapczar/Regi/archive/master.zip
Workshop
Setting Up a Local Project
Connecting to the Database
Using $_GET and $_POST
Image Upload and Form Validation
View this on...



www.slideshare.net/gapczar/test-16614129
SETTING UP LOCAL PROJECT
Requirements

Apache2
Php 5.3 or above
MySql
PhpMyAdmin
or MAMP, WAMP, and XAMPP
Steps

Installation of requirements (MAMP,
XAMPP or WAMP)
Structure of the project
Adding hostname to /etc/hosts
Edit the httpd.conf in Apache
Start Apache and test it
Project Structure


Project Directory
        web directory
                    index.php
Hosts in MAC/Unix


Mac/Linux in terminal
sudo vi /etc/hosts

and insert this
127.0.0.1         www.webcamp.com.local
Hosts in Windows
  Open file in notepad
c:windowssystem32driversetchosts
insert
127.0.0.1             www.webcamp.com.local

The number to the right is your computers default ip
address. In most cases the number should be the same
as have listed here. The words are the virtual host name.
www.webcamp.com.local for my the Project directory
Save the file. Make sure notepad doesn’t append .txt to
the file.
Location of conf file


MAC OS (MAMP)
/Applications/MAMP/conf/apache/httpd.conf

WINDOWS OS (WAMP)
c:wampbinapacheApache2.2.11confhttpd.conf

UNIX OS (XAMPP)
xamppapacheconfextra
xamppliteapacheconfextra
Relocation of conf file

MAC
Open /Applications/MAMP/conf/apache/httpd.conf

Change
Listen 8888 -> Listen 80
ServerName localhost:8888 -> ServerName localhost

Insert
NameVirtualHost *:80
Include /Users/computer_name/Sites/vhost/*.conf           //sample

Create a new file with an extension .conf and save it to the folder /
Users/computer_name/Sites/vhost and insert the code (next page) in
this file.
Virtual Host
  <VirtualHost *:80>
    ServerName www.webcamp.com.local
    DocumentRoot "/folder/path"
    DocumentIndex index.php
    <Directory "/folder/path">
        Allow from All
    </Directory>
</VirtualHost>
RESTART YOUR APACHE

  and its done!
CONNECTING TO THE
   DATABASE
Old Way of Connecting to
   a MySQL Database


$conn = mysql_connect('127.0.0.1', 'root', '');
$db = mysql_select_db('database', $conn);
New Ways of Connecting
to a MySQL Database


  PDO
  MySQLi
PDO (PHP Data Objects)


a database access layer providing
uniform access to multiple databases
MySQLi


an improved mysql extension developed
to take advantage of MySQL’s new
features
PDO vs. MySQLi

                                   PDO                    MySQLi
                        12 Drivers (CUBRID,
                        Microsoft SQL Server and
                        Sybase, Firebird/Interbase,
 Database Support       IBM, Informix, MySQL,           MySQL only
                        Microsoft SQL Server,
                        Oracle, ODBC and DB2,
                        PostgreSQL, SQLite, 4D)

        API                        OOP                OOP + procedural

 Named Parameters                  YES                      NO

Positional Parameters              YES                      YES

Prepared Statements                YES                      YES
PDO vs. MySQLi

                                   PDO                    MySQLi
                        12 Drivers (CUBRID,
                        Microsoft SQL Server and
                        Sybase, Firebird/Interbase,
 Database Support       IBM, Informix, MySQL,           MySQL only
                        Microsoft SQL Server,
                        Oracle, ODBC and DB2,
                        PostgreSQL, SQLite, 4D)

        API                        OOP                OOP + procedural

 Named Parameters                  YES                      NO

Positional Parameters              YES                      YES

Prepared Statements                YES                      YES
API (Application
 Programming Interface)


defines classes, methods, functions and
variables needed to call in order to carry
            out a certain task
PDO vs. MySQLi

                                   PDO                    MySQLi
                        12 Drivers (CUBRID,
                        Microsoft SQL Server and
                        Sybase, Firebird/Interbase,
 Database Support       IBM, Informix, MySQL,           MySQL only
                        Microsoft SQL Server,
                        Oracle, ODBC and DB2,
                        PostgreSQL, SQLite, 4D)

        API                        OOP                OOP + procedural

 Named Parameters                  YES                      NO

Positional Parameters              YES                      YES

Prepared Statements                YES                      YES
Named Parameters


   arguments specified by name


'SELECT * FROM users WHERE name LIKE :name'
PDO vs. MySQLi

                                   PDO                    MySQLi
                        12 Drivers (CUBRID,
                        Microsoft SQL Server and
                        Sybase, Firebird/Interbase,
 Database Support       IBM, Informix, MySQL,           MySQL only
                        Microsoft SQL Server,
                        Oracle, ODBC and DB2,
                        PostgreSQL, SQLite, 4D)

        API                        OOP                OOP + procedural

 Named Parameters                  YES                      NO

Positional Parameters              YES                      YES

Prepared Statements                YES                      YES
Positional Parameters


 arguments specified by position


'SELECT * FROM users WHERE name LIKE ?'
PDO vs. MySQLi

                                   PDO                    MySQLi
                        12 Drivers (CUBRID,
                        Microsoft SQL Server and
                        Sybase, Firebird/Interbase,
 Database Support       IBM, Informix, MySQL,           MySQL only
                        Microsoft SQL Server,
                        Oracle, ODBC and DB2,
                        PostgreSQL, SQLite, 4D)

        API                        OOP                OOP + procedural

 Named Parameters                  YES                      NO

Positional Parameters              YES                      YES

Prepared Statements                YES                      YES
Prepared Statements


a compiled template for the SQL that an
application wants to run and is customizable
using variable parameters
Using PDO
Connecting via PDO


$conn = new PDO(
    'mysql:host=127.0.0.1;dbname=database',
    'username',
    'password'
);
Querying via PDO

$sql = 'SELECT * FROM users ' .
       'WHERE first_name LIKE :first_name ' .
       'AND last_name LIKE :last_name';

$stmt = $db->prepare($sql);
$stmt->execute(array(
    ':last_name' => 'Doe',
    ':first_name' => 'Jane'
));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Error Handling via PDO
try {
   $conn = new PDO(
      'mysql:host=127.0.0.1;dbname=database',
      'root',
      ''
   );
   $conn->setAttribute(
       PDO::ATTR_ERRMODE,
       PDO::ERRMODE_EXCEPTION
   );
} catch (PDOException $e) {
   die($e->getMessage());
}
Error Handling Strategies

PDO::ERRMODE_SILENT
PDO::ERRMODE_WARNING
PDO::ERRMODE_EXCEPTION
Closing Connection via PDO


         $conn = null;
Using MySQLi
Connecting via MySQLi
        (Procedural Way)


$conn = mysqli_connect('127.0.0.1', 'root', '', 'dbname');
Connecting via MySQLi
  (Object-Oriented Way)


$conn = new mysqli('127.0.0.1','root','','dbname');
Querying via MySQLi
         (Procedural Way)
$firstName = 'Jane';
$sql = 'SELECT * FROM users WHERE first_name LIKE ?';

if ($stmt = mysqli_prepare($db, $sql)) {
    mysqli_stmt_bind_param($stmt, 's', $firstName);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $col1, $col2, $col3);

    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s %s n", $col1, $col2, $col3);
    }

    mysqli_stmt_close($stmt);
}
Querying via MySQLi
         (Object-Oriented Way)
$firstName = 'Jane';
$sql = 'SELECT * FROM users WHERE first_name LIKE ?';

if ($stmt = $conn->prepare($sql)) {
  $stmt->bind_param('s', $firstName);
  $stmt->execute();
  $stmt->bind_result($col1, $col2, $col3, $col4, $col5);

    while ($stmt->fetch()) {
       printf("%s %s %s n", $col1, $col2, $col3);
    }
    $stmt->close();
}
Error Handling via MySQLi

   // procedural way
   if (mysqli_connect_errno()) {
       die(mysqli_connect_error());	
   }

   // object-oriented way
   if ($conn->connect_errno) {
       die($conn->connect_error);
   }
Closing Connection via
       MySQLi

  // procedural way
  mysqli_close($conn);

  // object-oriented way
  if ($conn->connect_errno) {
      die($conn->connect_error);
  }
Using $_POST & $_GET
Things to Tackle

Request Methods of Form Submission
   method=”POST”
   method=”GET”
Superglobals
$_GET and $_POST
Request Methods of Form
      Submission
Create an HTML Form
<form ... method=”POST”>
  ...
  input elements
  ...
  submit button
</form>




<form ... method=”GET”>
...
input elements
...
submit button
</form>
GET vs. POST
                     GET                  POST


 Technical                             body of HTTP
                      URL
 difference                              Request



Recommended    viewing something
                                     changing something
   Usage       without changing it
GET vs. POST
                          GET                       POST

                 bookmark page              sensitive information
                  search engines can        multi-part binary (file
 Advantages
                index the page with        upload)
                passed data                 large quantities of data


                                             cannot bookmark or
                 size limitation
                                           direct access to the page
Disadvantages    not suitable to use for
                                             search engines cannot
                sensitive information
                                           index the page
SUPERGLOBALS
SUPERGLOBALS

accessible
             all scope

 available
SUPERGLOBALS
$GLOBALS
             $_COOKIE
                         $_GET
$_SERVER
            $_SESSION
 $_ENV                   $_POST
             $_REQUEST
$_FILES
$_GET


represents data sent to the PHP
        script in a URL
$_GET example
For method=‘GET’:
       ...
       <form action=”search.php”>
           Keyword: <input type="text" name="keyword"><br>
           <input type="submit" value="Search">
       </form>
       ...

in search.php:
       <html>
       <body>

       Keyword: <?php echo $_GET["keyword"]; ?><br>

       </body>
       </html>
$_POST


represents data sent to the PHP script
           via HTTP POST
$_POST Example
For method=‘POST’:
          ...
          <form action=”login.php” method=”POST”>
              Name: <input type="text" name="name"><br>
              Age: <input type="text" name="age"><br>
              <input type="submit" value="Login">
          </form>
          ...

in login.php:
          <html>
          <body>

          Hi <?php echo $_POST["name"]; ?>!<br>
          You are <?php echo $_POST["age"]; ?> years old.

          </body>
          </html>
IMAGE UPLOAD
In 2 steps...
Client submits file
Server processes submitted file
To submit a file...
Specify content type


<form ... enctype=”multipart/form-data”>
    ...
</form>
And...
Include a file input

<form ... enctype=”multipart/form-data”>
    ...
    <input name=”photo” type=”file”>
    ...
</form>
To process a file...
Handle
Validate
Save
Handling the $_FILES
Array
    (
        [user] => Array
            (
                [name] => Array
                    (
                        [photo] => image1.jpg
                    )                    
                [type] => Array
                    (
                        [photo] => image/jpeg
                    )
                [tmp_name] => Array
                    (
                        [photo] => /private/var/tmp/phpunJdED
                    )
                [error] => Array
                    (
                        [photo] => 0
                    )    
                [size] => Array
                    (
                        [photo] => 93521
                    )
            )
    )
$_FILES
name - original file name
type - file mime type
tmp_name - temporary file location
error - error code
size - file size (in bytes)
Validating



The file must be an image
Validation by...
Extension
Mime Type
Attribute
Validation by Attribute
  getimagesize($img)


      Get the size of an image. On failure, FALSE is
      returned.




From: getimagesize. http://php.net/manual/en/function.getimagesize.php (Accessed February 2013)
Saving

 move_uploaded_file($img, $destination)

        Moves an uploaded file to a new location.
              Returns TRUE on success.




From: move_uploaded_file. http://php.net/manual/en/function.move-uploaded-file.php
(Accessed February 2013)
FORM VALIDATION
Before validating...



      Sanitize
Sanitize



Remove, replace, escape unwanted characters
Validate



Ensure that data is acceptable
Sanitize with...
        filter_var($data, $filter)

      Filters a variable with a specified filter.
      Returns the filtered data, or FALSE if the filter
      fails.




From: filter_var. http://php.net/manual/en/function.filter-var.php (Accessed February 2013)
Using sanitize filters...
          FILTER_SANITIZE_EMAIL
          FILTER_SANITIZE_ENCODED
          FILTER_SANITIZE_MAGIC_QUOTES
          FILTER_SANITIZE_NUMBER_FLOAT
          FILTER_SANITIZE_NUMBER_INT
          FILTER_SANITIZE_SPECIAL_CHARS
          FILTER_SANITIZE_FULL_SPECIAL_CHARS
          FILTER_SANITIZE_STRING
          FILTER_SANITIZE_STRIPPED
          FILTER_SANITIZE_URL
          FILTER_UNSAFE_RAW

From: Sanitize filters. http://www.php.net/manual/en/filter.filters.sanitize.php (Accessed
February 2013)
Validate with...
        filter_var($data, $filter)

      Filters a variable with a specified filter.
      Returns the filtered data, or FALSE if the filter
      fails.




From: filter_var. http://php.net/manual/en/function.filter-var.php (Accessed February 2013)
Using validate filters...
          FILTER_VALIDATE_BOOLEAN

          FILTER_VALIDATE_EMAIL

          FILTER_VALIDATE_FLOAT

          FILTER_VALIDATE_INT

          FILTER_VALIDATE_IP

          FILTER_VALIDATE_REGEXP

          FILTER_VALIDATE_URL



From: Validate filters. http://www.php.net/manual/en/filter.filters.validate.php (Accessed
February 2013)
PHP WEB
DEVELOPMENT
See a full working
   example...


github.com/gapczar/Regi-dev
THANK YOU

More Related Content

What's hot

Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Arun Gupta
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudArun Gupta
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureArun Gupta
 
BASTA 2013: Custom OData Provider
BASTA 2013: Custom OData ProviderBASTA 2013: Custom OData Provider
BASTA 2013: Custom OData ProviderRainer Stropek
 
GlassFish & Java EE Business Update @ CEJUG
GlassFish & Java EE Business Update @ CEJUGGlassFish & Java EE Business Update @ CEJUG
GlassFish & Java EE Business Update @ CEJUGArun Gupta
 
Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009Brian Hogan
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudArun Gupta
 
Spring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingSpring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingThorsten Kamann
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012Arun Gupta
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012Arun Gupta
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration BackendArun Gupta
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nationArun Gupta
 
PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012Arun Gupta
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment WorkshopChuong Nguyen
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL Suraj Bang
 
Lesson06 使用子查询
Lesson06 使用子查询Lesson06 使用子查询
Lesson06 使用子查询renguzi
 
Configuration beyond Java EE 8
Configuration beyond Java EE 8Configuration beyond Java EE 8
Configuration beyond Java EE 8Anatole Tresch
 
Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaAnatole Tresch
 
Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0Arun Gupta
 

What's hot (20)

Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the Cloud
 
Java EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for futureJava EE 6 and GlassFish v3: Paving the path for future
Java EE 6 and GlassFish v3: Paving the path for future
 
BASTA 2013: Custom OData Provider
BASTA 2013: Custom OData ProviderBASTA 2013: Custom OData Provider
BASTA 2013: Custom OData Provider
 
GlassFish & Java EE Business Update @ CEJUG
GlassFish & Java EE Business Update @ CEJUGGlassFish & Java EE Business Update @ CEJUG
GlassFish & Java EE Business Update @ CEJUG
 
Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009
 
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the CloudTDC 2011: The Java EE 7 Platform: Developing for the Cloud
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
 
Spring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingSpring 3 - Der dritte Frühling
Spring 3 - Der dritte Frühling
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration Backend
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nation
 
PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
 
Lesson06 使用子查询
Lesson06 使用子查询Lesson06 使用子查询
Lesson06 使用子查询
 
Configuration beyond Java EE 8
Configuration beyond Java EE 8Configuration beyond Java EE 8
Configuration beyond Java EE 8
 
Java EE 7 overview
Java EE 7 overviewJava EE 7 overview
Java EE 7 overview
 
Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache Tamaya
 
Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0
 

Viewers also liked

Asignación búsquedas avanzadas módulo i
Asignación búsquedas avanzadas módulo iAsignación búsquedas avanzadas módulo i
Asignación búsquedas avanzadas módulo iKaki2501p
 
Plan Maker Overview
Plan Maker OverviewPlan Maker Overview
Plan Maker Overviewdphillippy
 
Safety QR Code - user guide-en
Safety QR Code - user guide-enSafety QR Code - user guide-en
Safety QR Code - user guide-enTrizero S.r.l.
 

Viewers also liked (7)

Asignación búsquedas avanzadas módulo i
Asignación búsquedas avanzadas módulo iAsignación búsquedas avanzadas módulo i
Asignación búsquedas avanzadas módulo i
 
Vestlig vekst
Vestlig vekstVestlig vekst
Vestlig vekst
 
Plan Maker Overview
Plan Maker OverviewPlan Maker Overview
Plan Maker Overview
 
Programme CAMPUS AFJE 2016
Programme CAMPUS AFJE 2016Programme CAMPUS AFJE 2016
Programme CAMPUS AFJE 2016
 
Araling panlipunan
Araling panlipunanAraling panlipunan
Araling panlipunan
 
Sayaw at liturhiya
Sayaw at liturhiyaSayaw at liturhiya
Sayaw at liturhiya
 
Safety QR Code - user guide-en
Safety QR Code - user guide-enSafety QR Code - user guide-en
Safety QR Code - user guide-en
 

Similar to PHP WEB DEVELOPMENT WORKSHOP

High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance JdbcSam Pattsin
 
Perl6 DBDI YAPC::EU 201008
Perl6 DBDI YAPC::EU 201008Perl6 DBDI YAPC::EU 201008
Perl6 DBDI YAPC::EU 201008Tim Bunce
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For HadoopCloudera, Inc.
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 
Php Site Optimization
Php Site OptimizationPhp Site Optimization
Php Site OptimizationAmit Kejriwal
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Vladimir Bacvanski, PhD
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...Sencha
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsRaimonds Simanovskis
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performanceMydbops
 

Similar to PHP WEB DEVELOPMENT WORKSHOP (20)

High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
 
11. jdbc
11. jdbc11. jdbc
11. jdbc
 
Perl6 DBDI YAPC::EU 201008
Perl6 DBDI YAPC::EU 201008Perl6 DBDI YAPC::EU 201008
Perl6 DBDI YAPC::EU 201008
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For Hadoop
 
Web 2.0 Development with IBM DB2
Web 2.0 Development with IBM DB2Web 2.0 Development with IBM DB2
Web 2.0 Development with IBM DB2
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Php Site Optimization
Php Site OptimizationPhp Site Optimization
Php Site Optimization
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Data access
Data accessData access
Data access
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
 
PI-RDBMS.ppt
PI-RDBMS.pptPI-RDBMS.ppt
PI-RDBMS.ppt
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Extending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on RailsExtending Oracle E-Business Suite with Ruby on Rails
Extending Oracle E-Business Suite with Ruby on Rails
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
 
harry presentation
harry presentationharry presentation
harry presentation
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 

PHP WEB DEVELOPMENT WORKSHOP

  • 2. The Project A simple registration website
  • 4. Workshop Setting Up a Local Project Connecting to the Database Using $_GET and $_POST Image Upload and Form Validation
  • 7. Requirements Apache2 Php 5.3 or above MySql PhpMyAdmin or MAMP, WAMP, and XAMPP
  • 8. Steps Installation of requirements (MAMP, XAMPP or WAMP) Structure of the project Adding hostname to /etc/hosts Edit the httpd.conf in Apache Start Apache and test it
  • 9. Project Structure Project Directory web directory index.php
  • 10. Hosts in MAC/Unix Mac/Linux in terminal sudo vi /etc/hosts and insert this 127.0.0.1 www.webcamp.com.local
  • 11. Hosts in Windows Open file in notepad c:windowssystem32driversetchosts insert 127.0.0.1 www.webcamp.com.local The number to the right is your computers default ip address. In most cases the number should be the same as have listed here. The words are the virtual host name. www.webcamp.com.local for my the Project directory Save the file. Make sure notepad doesn’t append .txt to the file.
  • 12. Location of conf file MAC OS (MAMP) /Applications/MAMP/conf/apache/httpd.conf WINDOWS OS (WAMP) c:wampbinapacheApache2.2.11confhttpd.conf UNIX OS (XAMPP) xamppapacheconfextra xamppliteapacheconfextra
  • 13. Relocation of conf file MAC Open /Applications/MAMP/conf/apache/httpd.conf Change Listen 8888 -> Listen 80 ServerName localhost:8888 -> ServerName localhost Insert NameVirtualHost *:80 Include /Users/computer_name/Sites/vhost/*.conf //sample Create a new file with an extension .conf and save it to the folder / Users/computer_name/Sites/vhost and insert the code (next page) in this file.
  • 14. Virtual Host <VirtualHost *:80>     ServerName www.webcamp.com.local     DocumentRoot "/folder/path"     DocumentIndex index.php     <Directory "/folder/path">         Allow from All     </Directory> </VirtualHost>
  • 15. RESTART YOUR APACHE and its done!
  • 16. CONNECTING TO THE DATABASE
  • 17. Old Way of Connecting to a MySQL Database $conn = mysql_connect('127.0.0.1', 'root', ''); $db = mysql_select_db('database', $conn);
  • 18. New Ways of Connecting to a MySQL Database PDO MySQLi
  • 19. PDO (PHP Data Objects) a database access layer providing uniform access to multiple databases
  • 20. MySQLi an improved mysql extension developed to take advantage of MySQL’s new features
  • 21. PDO vs. MySQLi PDO MySQLi 12 Drivers (CUBRID, Microsoft SQL Server and Sybase, Firebird/Interbase, Database Support IBM, Informix, MySQL, MySQL only Microsoft SQL Server, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D) API OOP OOP + procedural Named Parameters YES NO Positional Parameters YES YES Prepared Statements YES YES
  • 22. PDO vs. MySQLi PDO MySQLi 12 Drivers (CUBRID, Microsoft SQL Server and Sybase, Firebird/Interbase, Database Support IBM, Informix, MySQL, MySQL only Microsoft SQL Server, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D) API OOP OOP + procedural Named Parameters YES NO Positional Parameters YES YES Prepared Statements YES YES
  • 23. API (Application Programming Interface) defines classes, methods, functions and variables needed to call in order to carry out a certain task
  • 24. PDO vs. MySQLi PDO MySQLi 12 Drivers (CUBRID, Microsoft SQL Server and Sybase, Firebird/Interbase, Database Support IBM, Informix, MySQL, MySQL only Microsoft SQL Server, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D) API OOP OOP + procedural Named Parameters YES NO Positional Parameters YES YES Prepared Statements YES YES
  • 25. Named Parameters arguments specified by name 'SELECT * FROM users WHERE name LIKE :name'
  • 26. PDO vs. MySQLi PDO MySQLi 12 Drivers (CUBRID, Microsoft SQL Server and Sybase, Firebird/Interbase, Database Support IBM, Informix, MySQL, MySQL only Microsoft SQL Server, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D) API OOP OOP + procedural Named Parameters YES NO Positional Parameters YES YES Prepared Statements YES YES
  • 27. Positional Parameters arguments specified by position 'SELECT * FROM users WHERE name LIKE ?'
  • 28. PDO vs. MySQLi PDO MySQLi 12 Drivers (CUBRID, Microsoft SQL Server and Sybase, Firebird/Interbase, Database Support IBM, Informix, MySQL, MySQL only Microsoft SQL Server, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D) API OOP OOP + procedural Named Parameters YES NO Positional Parameters YES YES Prepared Statements YES YES
  • 29. Prepared Statements a compiled template for the SQL that an application wants to run and is customizable using variable parameters
  • 31. Connecting via PDO $conn = new PDO( 'mysql:host=127.0.0.1;dbname=database', 'username', 'password' );
  • 32. Querying via PDO $sql = 'SELECT * FROM users ' . 'WHERE first_name LIKE :first_name ' . 'AND last_name LIKE :last_name'; $stmt = $db->prepare($sql); $stmt->execute(array( ':last_name' => 'Doe', ':first_name' => 'Jane' )); $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
  • 33. Error Handling via PDO try { $conn = new PDO( 'mysql:host=127.0.0.1;dbname=database', 'root', '' ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch (PDOException $e) { die($e->getMessage()); }
  • 35. Closing Connection via PDO $conn = null;
  • 37. Connecting via MySQLi (Procedural Way) $conn = mysqli_connect('127.0.0.1', 'root', '', 'dbname');
  • 38. Connecting via MySQLi (Object-Oriented Way) $conn = new mysqli('127.0.0.1','root','','dbname');
  • 39. Querying via MySQLi (Procedural Way) $firstName = 'Jane'; $sql = 'SELECT * FROM users WHERE first_name LIKE ?'; if ($stmt = mysqli_prepare($db, $sql)) { mysqli_stmt_bind_param($stmt, 's', $firstName); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $col1, $col2, $col3); while (mysqli_stmt_fetch($stmt)) { printf("%s %s %s n", $col1, $col2, $col3); } mysqli_stmt_close($stmt); }
  • 40. Querying via MySQLi (Object-Oriented Way) $firstName = 'Jane'; $sql = 'SELECT * FROM users WHERE first_name LIKE ?'; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param('s', $firstName); $stmt->execute(); $stmt->bind_result($col1, $col2, $col3, $col4, $col5); while ($stmt->fetch()) { printf("%s %s %s n", $col1, $col2, $col3); } $stmt->close(); }
  • 41. Error Handling via MySQLi // procedural way if (mysqli_connect_errno()) { die(mysqli_connect_error()); } // object-oriented way if ($conn->connect_errno) { die($conn->connect_error); }
  • 42. Closing Connection via MySQLi // procedural way mysqli_close($conn); // object-oriented way if ($conn->connect_errno) { die($conn->connect_error); }
  • 43. Using $_POST & $_GET
  • 44. Things to Tackle Request Methods of Form Submission method=”POST” method=”GET” Superglobals $_GET and $_POST
  • 45. Request Methods of Form Submission
  • 46. Create an HTML Form <form ... method=”POST”> ... input elements ... submit button </form> <form ... method=”GET”> ... input elements ... submit button </form>
  • 47. GET vs. POST GET POST Technical body of HTTP URL difference Request Recommended viewing something changing something Usage without changing it
  • 48. GET vs. POST GET POST bookmark page sensitive information search engines can multi-part binary (file Advantages index the page with upload) passed data large quantities of data cannot bookmark or size limitation direct access to the page Disadvantages not suitable to use for search engines cannot sensitive information index the page
  • 50. SUPERGLOBALS accessible all scope available
  • 51. SUPERGLOBALS $GLOBALS $_COOKIE $_GET $_SERVER $_SESSION $_ENV $_POST $_REQUEST $_FILES
  • 52. $_GET represents data sent to the PHP script in a URL
  • 53. $_GET example For method=‘GET’: ... <form action=”search.php”> Keyword: <input type="text" name="keyword"><br> <input type="submit" value="Search"> </form> ... in search.php: <html> <body> Keyword: <?php echo $_GET["keyword"]; ?><br> </body> </html>
  • 54.
  • 55. $_POST represents data sent to the PHP script via HTTP POST
  • 56. $_POST Example For method=‘POST’: ... <form action=”login.php” method=”POST”> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> <input type="submit" value="Login"> </form> ... in login.php: <html> <body> Hi <?php echo $_POST["name"]; ?>!<br> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
  • 57.
  • 59. In 2 steps... Client submits file Server processes submitted file
  • 60. To submit a file... Specify content type <form ... enctype=”multipart/form-data”> ... </form>
  • 61. And... Include a file input <form ... enctype=”multipart/form-data”> ... <input name=”photo” type=”file”> ... </form>
  • 62. To process a file... Handle Validate Save
  • 63. Handling the $_FILES Array    (        [user] => Array            (                [name] => Array                    (                        [photo] => image1.jpg                    )                                    [type] => Array                    (                        [photo] => image/jpeg                    )                [tmp_name] => Array                    (                        [photo] => /private/var/tmp/phpunJdED                    )                [error] => Array                    (                        [photo] => 0                    )                    [size] => Array                    (                        [photo] => 93521                    )            )    )
  • 64. $_FILES name - original file name type - file mime type tmp_name - temporary file location error - error code size - file size (in bytes)
  • 67. Validation by Attribute getimagesize($img) Get the size of an image. On failure, FALSE is returned. From: getimagesize. http://php.net/manual/en/function.getimagesize.php (Accessed February 2013)
  • 68. Saving move_uploaded_file($img, $destination) Moves an uploaded file to a new location. Returns TRUE on success. From: move_uploaded_file. http://php.net/manual/en/function.move-uploaded-file.php (Accessed February 2013)
  • 71. Sanitize Remove, replace, escape unwanted characters
  • 72. Validate Ensure that data is acceptable
  • 73. Sanitize with... filter_var($data, $filter) Filters a variable with a specified filter. Returns the filtered data, or FALSE if the filter fails. From: filter_var. http://php.net/manual/en/function.filter-var.php (Accessed February 2013)
  • 74. Using sanitize filters... FILTER_SANITIZE_EMAIL FILTER_SANITIZE_ENCODED FILTER_SANITIZE_MAGIC_QUOTES FILTER_SANITIZE_NUMBER_FLOAT FILTER_SANITIZE_NUMBER_INT FILTER_SANITIZE_SPECIAL_CHARS FILTER_SANITIZE_FULL_SPECIAL_CHARS FILTER_SANITIZE_STRING FILTER_SANITIZE_STRIPPED FILTER_SANITIZE_URL FILTER_UNSAFE_RAW From: Sanitize filters. http://www.php.net/manual/en/filter.filters.sanitize.php (Accessed February 2013)
  • 75. Validate with... filter_var($data, $filter) Filters a variable with a specified filter. Returns the filtered data, or FALSE if the filter fails. From: filter_var. http://php.net/manual/en/function.filter-var.php (Accessed February 2013)
  • 76. Using validate filters... FILTER_VALIDATE_BOOLEAN FILTER_VALIDATE_EMAIL FILTER_VALIDATE_FLOAT FILTER_VALIDATE_INT FILTER_VALIDATE_IP FILTER_VALIDATE_REGEXP FILTER_VALIDATE_URL From: Validate filters. http://www.php.net/manual/en/filter.filters.validate.php (Accessed February 2013)
  • 78. See a full working example... github.com/gapczar/Regi-dev