wee
Upcoming SlideShare
Loading in...5
×
 

wee

on

  • 248 views

 

Statistics

Views

Total Views
248
Views on SlideShare
248
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    wee wee Presentation Transcript

    • PHP WEBDEVELOPMENT
    • The ProjectA simple registration website
    • Download...github.com/gapczar/Regi/archive/master.zip
    • WorkshopSetting Up a Local ProjectConnecting to the DatabaseUsing $_GET and $_POSTImage Upload and Form Validation
    • View this on...www.slideshare.net/gapczar/test-16614129
    • SETTING UP LOCAL PROJECT
    • RequirementsApache2Php 5.3 or aboveMySqlPhpMyAdminor MAMP, WAMP, and XAMPP
    • StepsInstallation of requirements (MAMP,XAMPP or WAMP)Structure of the projectAdding hostname to /etc/hostsEdit the httpd.conf in ApacheStart Apache and test it
    • Project StructureProject Directory web directory index.php
    • Hosts in MAC/UnixMac/Linux in terminalsudo vi /etc/hostsand insert this127.0.0.1 www.webcamp.com.local
    • Hosts in Windows Open file in notepadc:windowssystem32driversetchostsinsert127.0.0.1 www.webcamp.com.localThe number to the right is your computers default ipaddress. In most cases the number should be the sameas have listed here. The words are the virtual host name.www.webcamp.com.local for my the Project directorySave the file. Make sure notepad doesn’t append .txt tothe file.
    • Location of conf fileMAC OS (MAMP)/Applications/MAMP/conf/apache/httpd.confWINDOWS OS (WAMP)c:wampbinapacheApache2.2.11confhttpd.confUNIX OS (XAMPP)xamppapacheconfextraxamppliteapacheconfextra
    • Relocation of conf fileMACOpen /Applications/MAMP/conf/apache/httpd.confChangeListen 8888 -> Listen 80ServerName localhost:8888 -> ServerName localhostInsertNameVirtualHost *:80Include /Users/computer_name/Sites/vhost/*.conf //sampleCreate a new file with an extension .conf and save it to the folder /Users/computer_name/Sites/vhost and insert the code (next page) inthis 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 Connectingto a MySQL Database PDO MySQLi
    • PDO (PHP Data Objects)a database access layer providinguniform access to multiple databases
    • MySQLian improved mysql extension developedto take advantage of MySQL’s newfeatures
    • 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 NOPositional Parameters YES YESPrepared 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 NOPositional Parameters YES YESPrepared Statements YES YES
    • API (Application Programming Interface)defines classes, methods, functions andvariables 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 NOPositional Parameters YES YESPrepared Statements YES YES
    • Named Parameters arguments specified by nameSELECT * 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 NOPositional Parameters YES YESPrepared Statements YES YES
    • Positional Parameters arguments specified by positionSELECT * 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 NOPositional Parameters YES YESPrepared Statements YES YES
    • Prepared Statementsa compiled template for the SQL that anapplication wants to run and is customizableusing 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 PDOtry { $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 StrategiesPDO::ERRMODE_SILENTPDO::ERRMODE_WARNINGPDO::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 TackleRequest 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 RequestRecommended 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 pageDisadvantages not suitable to use for search engines cannot sensitive information index the page
    • SUPERGLOBALS
    • SUPERGLOBALSaccessible all scope available
    • SUPERGLOBALS$GLOBALS $_COOKIE $_GET$_SERVER $_SESSION $_ENV $_POST $_REQUEST$_FILES
    • $_GETrepresents data sent to the PHP script in a URL
    • $_GET exampleFor 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>
    • $_POSTrepresents data sent to the PHP script via HTTP POST
    • $_POST ExampleFor 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 fileServer 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...HandleValidateSave
    • Handling the $_FILESArray    (        [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                    )            )    )
    • $_FILESname - original file nametype - file mime typetmp_name - temporary file locationerror - error codesize - file size (in bytes)
    • ValidatingThe file must be an image
    • Validation by...ExtensionMime TypeAttribute
    • 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
    • SanitizeRemove, replace, escape unwanted characters
    • ValidateEnsure 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_RAWFrom: Sanitize filters. http://www.php.net/manual/en/filter.filters.sanitize.php (AccessedFebruary 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_URLFrom: Validate filters. http://www.php.net/manual/en/filter.filters.validate.php (AccessedFebruary 2013)
    • PHP WEBDEVELOPMENT
    • See a full working example...github.com/gapczar/Regi-dev
    • THANK YOU