wee

413 views
293 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
413
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

wee

  1. 1. PHP WEBDEVELOPMENT
  2. 2. The ProjectA simple registration website
  3. 3. Download...github.com/gapczar/Regi/archive/master.zip
  4. 4. WorkshopSetting Up a Local ProjectConnecting to the DatabaseUsing $_GET and $_POSTImage Upload and Form Validation
  5. 5. View this on...www.slideshare.net/gapczar/test-16614129
  6. 6. SETTING UP LOCAL PROJECT
  7. 7. RequirementsApache2Php 5.3 or aboveMySqlPhpMyAdminor MAMP, WAMP, and XAMPP
  8. 8. StepsInstallation of requirements (MAMP,XAMPP or WAMP)Structure of the projectAdding hostname to /etc/hostsEdit the httpd.conf in ApacheStart Apache and test it
  9. 9. Project StructureProject Directory web directory index.php
  10. 10. Hosts in MAC/UnixMac/Linux in terminalsudo vi /etc/hostsand insert this127.0.0.1 www.webcamp.com.local
  11. 11. 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.
  12. 12. Location of conf fileMAC OS (MAMP)/Applications/MAMP/conf/apache/httpd.confWINDOWS OS (WAMP)c:wampbinapacheApache2.2.11confhttpd.confUNIX OS (XAMPP)xamppapacheconfextraxamppliteapacheconfextra
  13. 13. 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.
  14. 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. 15. RESTART YOUR APACHE and its done!
  16. 16. CONNECTING TO THE DATABASE
  17. 17. Old Way of Connecting to a MySQL Database$conn = mysql_connect(127.0.0.1, root, );$db = mysql_select_db(database, $conn);
  18. 18. New Ways of Connectingto a MySQL Database PDO MySQLi
  19. 19. PDO (PHP Data Objects)a database access layer providinguniform access to multiple databases
  20. 20. MySQLian improved mysql extension developedto take advantage of MySQL’s newfeatures
  21. 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 NOPositional Parameters YES YESPrepared Statements YES YES
  22. 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 NOPositional Parameters YES YESPrepared Statements YES YES
  23. 23. API (Application Programming Interface)defines classes, methods, functions andvariables needed to call in order to carry out a certain task
  24. 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 NOPositional Parameters YES YESPrepared Statements YES YES
  25. 25. Named Parameters arguments specified by nameSELECT * FROM users WHERE name LIKE :name
  26. 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 NOPositional Parameters YES YESPrepared Statements YES YES
  27. 27. Positional Parameters arguments specified by positionSELECT * FROM users WHERE name LIKE ?
  28. 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 NOPositional Parameters YES YESPrepared Statements YES YES
  29. 29. Prepared Statementsa compiled template for the SQL that anapplication wants to run and is customizableusing variable parameters
  30. 30. Using PDO
  31. 31. Connecting via PDO$conn = new PDO( mysql:host=127.0.0.1;dbname=database, username, password);
  32. 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. 33. 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());}
  34. 34. Error Handling StrategiesPDO::ERRMODE_SILENTPDO::ERRMODE_WARNINGPDO::ERRMODE_EXCEPTION
  35. 35. Closing Connection via PDO $conn = null;
  36. 36. Using MySQLi
  37. 37. Connecting via MySQLi (Procedural Way)$conn = mysqli_connect(127.0.0.1, root, , dbname);
  38. 38. Connecting via MySQLi (Object-Oriented Way)$conn = new mysqli(127.0.0.1,root,,dbname);
  39. 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. 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. 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. 42. Closing Connection via MySQLi // procedural way mysqli_close($conn); // object-oriented way if ($conn->connect_errno) { die($conn->connect_error); }
  43. 43. Using $_POST & $_GET
  44. 44. Things to TackleRequest Methods of Form Submission method=”POST” method=”GET”Superglobals$_GET and $_POST
  45. 45. Request Methods of Form Submission
  46. 46. Create an HTML Form<form ... method=”POST”> ... input elements ... submit button</form><form ... method=”GET”>...input elements...submit button</form>
  47. 47. GET vs. POST GET POST Technical body of HTTP URL difference RequestRecommended viewing something changing something Usage without changing it
  48. 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 pageDisadvantages not suitable to use for search engines cannot sensitive information index the page
  49. 49. SUPERGLOBALS
  50. 50. SUPERGLOBALSaccessible all scope available
  51. 51. SUPERGLOBALS$GLOBALS $_COOKIE $_GET$_SERVER $_SESSION $_ENV $_POST $_REQUEST$_FILES
  52. 52. $_GETrepresents data sent to the PHP script in a URL
  53. 53. $_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>
  54. 54. $_POSTrepresents data sent to the PHP script via HTTP POST
  55. 55. $_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>
  56. 56. IMAGE UPLOAD
  57. 57. In 2 steps...Client submits fileServer processes submitted file
  58. 58. To submit a file...Specify content type<form ... enctype=”multipart/form-data”> ...</form>
  59. 59. And...Include a file input<form ... enctype=”multipart/form-data”> ... <input name=”photo” type=”file”> ...</form>
  60. 60. To process a file...HandleValidateSave
  61. 61. 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                    )            )    )
  62. 62. $_FILESname - original file nametype - file mime typetmp_name - temporary file locationerror - error codesize - file size (in bytes)
  63. 63. ValidatingThe file must be an image
  64. 64. Validation by...ExtensionMime TypeAttribute
  65. 65. 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)
  66. 66. 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)
  67. 67. FORM VALIDATION
  68. 68. Before validating... Sanitize
  69. 69. SanitizeRemove, replace, escape unwanted characters
  70. 70. ValidateEnsure that data is acceptable
  71. 71. 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)
  72. 72. 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)
  73. 73. 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)
  74. 74. 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)
  75. 75. PHP WEBDEVELOPMENT
  76. 76. See a full working example...github.com/gapczar/Regi-dev
  77. 77. THANK YOU

×