• Like

Thanks for flagging this SlideShare!

Oops! An error has occurred.

PHP for Web Designers

  • 14,908 views
Published

An introduction to PHP covering basic syntax, variables, arrays, looping, functions, includes, SuperGlobals, if/else statements, cookies, forms, and a quick overview of PDO. - Updated 6/6/13 for PSU …

An introduction to PHP covering basic syntax, variables, arrays, looping, functions, includes, SuperGlobals, if/else statements, cookies, forms, and a quick overview of PDO. - Updated 6/6/13 for PSU Web Conference

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
14,908
On SlideShare
0
From Embeds
0
Number of Embeds
3

Actions

Shares
Downloads
98
Comments
0
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. PHP forWeb DesignersJune 6, 2013michael stowe
  • 2. MIKESTOWE•  Open Source Contributor•  Author, Speaker, and Consultant•  10+ years experience hacking PHP•  Zend Certified PHP 5.3 Software Engineer•  Developer Advocate with Constant Contact.com@mikegstowe
  • 3. PURPOSE OF THIS PRESENTATIONThe goal of this presentation is not to showyou “cool snippets” but rather to give you afoundation in PHP to help you use those “coolsnippets” that are already out there, andcustomize them to meet your needs.
  • 4. CONFERENCE ATTENDEESWe’re going to go through A LOT ofinformation in a very short time (1 hour). Iwant to give you a start, but I don’t expectyou to remember EVERYTHING. So don’tworry, these slides will be posted online alongwith my contact information.MIKESTOWE.COM
  • 5. WHAT WE’RE GONNA TALK ABOUT•  What is PHP•  Getting Started•  Variables•  If/Else Logical Statements•  Including Files•  SuperGlobals•  Cookies•  Arrays•  Forms & Form Security•  Databases & Database Security•  Functions•  More Resources
  • 6. WHAT IS PHPPHP is a server-side programming languagedesigned by Rasmus Lerdorf in 1995. Thelanguage was originally designed as acollection of Perl scripts to handle basicfunctions (counters, forms, etc) for “PersonalHome Pages.”
  • 7. WHAT IS PHPThe PHP parser was rewritten by ZeevSuraski and Andi Gutmans and launchedas the Zend Engine in 1998. Since thenPHP has become the most popular weblanguage, being used on an estimated75% of all websites.
  • 8. WHAT IS PHPRecent developments in PHP have escalatedits status substantially. PHP 5 offered largesteps in Object Oriented Programming, withPHP 5.3 being a landmark release, and PHP5.4 incorporating horizontal architecturaldesign helping make PHP a truly enterpriselanguage.
  • 9. WHAT IS PHPAnd a recent survey of decision makers comparingPHP to other programming languages found:•  88% said PHP decreased development time•  81% said it was easier to work with in the cloud•  79% said it was easier for new developers•  76% said it was easier to administer•  65% saw an increase in performance•  60% found it easier to find resources (staff &frameworks)
  • 10. WHAT IS PHPToday PHP is used by companies includingGoogle, Facebook, Yahoo, Amazon, eBay,Wikimedia (Wikipedia), Digg, Flickr, Intel, BestBuy, CaringBrige, CNN, and more.PHP also powers WordPress and Drupal, twoof the most popular Blog/ CMS solutions.
  • 11. WHAT IS PHPWhat makes PHP unique from JavaScript,HTML, or CSS is that it is compiled on theServer, this means there is no interaction withthe user once the data has been sent. Wecan make more calls via Ajax, but once thedata has been sent it cannot be manipulatedwithout another call.
  • 12. WHAT IS PHPAnd unlike JavaScript, PHP is limited to theserver resources, not the browser resources.Every time a PHP script is run the server hasto do all of the work running through thelogic, functions, and commands.
  • 13. SO WHY USE PHP?The advantage PHP offers is that because it’sserver-side, it is more secure. You are able toaccess databases, files, and other resourceswithout providing the user your credentials,or making your code base available.
  • 14. SO WHY USE PHP?Server-side languages also help reduce theamount of code you need to transfer to thebrowser, making your page load faster,especially on older browsers and mobiledevices as compared to having to do a ton ofJavaScript to achieve the same effect.
  • 15. GETTING STARTEDTo get started using PHP you will need a basiceditor (Notepad anyone) and a server orcomputer with PHP installed. Fordevelopment on your personal machine youcan install a prepackaged virtual server suchas WAMP (for Windows) or MAMP (for Mac).
  • 16. GETTING STARTEDThere are also numerous IDE’s out there thatyou can use for development purposes. Theadvantage to an IDE is that it will highlightcode to make it easier to read and check forerrors as you are typing.
  • 17. GETTING STARTEDWhile there are many IDE’s out there, some of themost recommended include:•  Aptana Studio 3 (free)•  Notepad++ (free)•  Eclipse+PDT (free)•  Netbeans (free)•  Zend Studio•  PhpStorm•  PhpEdDreamweaver also offers code highlighting.
  • 18. GETTING STARTEDOnce you have PHP installed and something toedit PHP scripts with, you can start creatingPHP.To get started, simply create a script calledyourfile.php and open your code with <?php,closing it with ?>.
  • 19. GETTING STARTEDBecause PHP is a server-side language it doesnot provide any styling for the browser. Inorder to return a webpage we will still useHTML, JavaScript, and CSS to do things client(browser) side. This code can also be put inthe PHP file outside of PHP brackets.
  • 20. PHP AND HTML <?php<html>     <head>       <title>         <?php  echo  $title;  ?>       </title>     </head>     <body>       <?php         echo  hello  world;       ?>     </body>  </html>  
  • 21. PHP SYNTAXThere are other types of tags you can use todeclare PHP code, however, you shouldn’t.Stick with the long form <?php  method.
  • 22. PHP SYNTAX <?php<?php  //  Traditional  PHP  Tag  ?>    <script  language="php">     //  Non-­‐Traditional  -­‐  Dont  Do  This  </script>    <?     //  Short  Tag  -­‐  Dont  Do  This  Either  ?>    <%     //  ASP  Style...  Deprecated...  I  will  find  you.  %>  
  • 23. PHP SYNTAXBest practice is to use the full <?php  /*  …  */  ?>  tagswhen writing your code. Short style tags require aspecial INI setting to be turned on, so they will not workon all servers.ASP style tags also require a special INI directive to beset, and have been deprecated. They should be avoidedat all costs (no matter how cool they look).
  • 24. PHP SYNTAX – SHORT ECHOPHP 5.4 now allows the short echo by default. This lookslike <?=$title;  ?>.However, because PHP 5.4 is so new, and most serversdo not yet support it, you should avoid using the shortecho method in any scripts that may be distributed orhosted elsewhere.
  • 25. WAIT! WHAT IS ECHOBecause PHP is a server-side language it operateson a output buffer, meaning it will not echoanything out without you explicitly telling it to.PHP provides multiple methods for echoing orprinting out data. Two of the most popularstatements for this are echo and print (print canalso be used as a function).
  • 26. PRINT ECHO <?php<?php// Set a variable!!!$world = world;echo hello world;echo "hello world";echo hello . $world;echo "hello $world";print hello world;print "hello world";print hello . $world;print "hello $world";// All print hello world?>
  • 27. VARIABLESIn PHP, setting variables is incredibly easy.Simply use the dollar sign ($) to declare your textas a variable, and then use the equal sign (=) toset it.Beware using two dollar signs (or the inevitablevariable variable) as well as the double or tripleequal signs (which performs a logical check).
  • 28. VARIABLES <?php<?php// Set variables$myvariable = hello;$variable2 = world;// Change variable$myvariable = good-night;// Oops!$myvariable == hello; // (returns FALSE)?>
  • 29. IF/ ELSEIF/ ELSEPHP allows you to run logical checks to performdifferent actions based on specific conditions.The logical operators are:== Content is equal (ie 0 == false)=== Content and type are equal (ie int(1) != string(1))!= Content is Not Equal!== Content or Type is not Equal
  • 30. IF/ ELSEIF/ ELSEPHP allows you to run logical checks to performdifferent actions based on specific conditions.The logical operators are:< Less than<= Less than or equal> Greater than>= Greater than or equal
  • 31. IF/ ELSEIF/ ELSEThere are a few more (ie bit-wise operators), butwe’re not going into those. You can also addadditional conditions:&& And|| Or
  • 32. IF/ ELSE/ ELSEIF <?php<?php$text = Hello World;// This returns "text is Hello World"if ($text == Hello World) {echo text is Hello World;}?>
  • 33. IF/ ELSE/ ELSEIF <?php<?php$text = Hello World;// This returns "text is Hello World"if ($text == Hello World) {echo text is Hello World;} else {echo text is not Hello World;}?>
  • 34. IF/ ELSE/ ELSEIF <?php<?php$a = 1;if ($a == 1 || $a == 2) {echo $a is equal to 1 or 2;} elseif ($a !== 3) {echo $a is not equal to 3 or is not an int;} else {echo $a is equal to 3 and is an int;}?>
  • 35. INCLUDING FILESOne of the most convenient features of PHP is the abilityto include or require other files and execute them as PHPcode.PHP has four main functions for this: include(),include_once(), require(), require_once().Note: require() requires the file to exist and be calledin, otherwise it will throw a fatal error. include()throws a warning which can be suppressed.
  • 36. INCLUDING FILES <?php<?php// about_us.php// set menu for use in header.php$menu = thismenu.php;// get headerinclude(header.php); // get header template?><h1>About Us</h1><p>We are awesome</p><?php// get footerinclude(footer.php);?>
  • 37. INCLUDING FILESinclude()  and require()  will execute thefile each time they are called, whereasinclude_once()  and require_once()  willcheck to see if the file has already beenincluded and executed, and if it has, they willignore any future calls to the file.
  • 38. INCLUDING FILES <?php<?phpinclude(echo_one.php);include(echo_one.php);include(echo_one.php);// echo one included 3 timesinclude_once(echo_one.php);// echo one NOT includedinclude_once(echo_two.php);// echo two included?>
  • 39. SUPERGLOBALSSuperGlobals are globals defined by PHP based ondata either being sent to the browser or collectedfrom the server. These SuperGlobals are accessiblethroughout any part of the PHP script.SuperGlobals include the $_POST, $_GET,$_REQUEST, $_COOKIE, $_SESSION, $_SERVER, and$_ENV  arrays which each contain special sets ofdata.
  • 40. SUPERGLOBALS$_POST contains the POST data from form submissions$_GET contains the parameters from the QueryString$_REQUEST contains a combination of Post, Get, andCookie by default (controlled by INI)$_COOKIE contains all cookie data sent in the headers$_SESSION contains the session data (if started)$_SERVER contains server and client variables$_ENV contains environmental properties
  • 41. SUPERGLOBALS <?php<?php/** Display the value given for the form* field with a name attribute of* "field_name"*/echo $_POST[field_name];?>
  • 42. SUPERGLOBALSAs a general rule, you should never trust dataprovided in the SuperGlobals to be safe or secure.You should always assume it is tainted.Likewise, do not depend on $_REQUEST, but ratheruse the appropriate SuperGlobal for the source ofthe data expected (ie $_POST, $_GET, $_COOKIE).
  • 43. COOKIES - YUMCookies are strings stored on the user’s machineto help identify them or a specific preference.For example, you may use a cookie to identifytheir favorite theme for your website, to identifya session, or to remember their username.
  • 44. COOKIES - YUMCookies should NEVER be used to storepasswords, user roles, or informationused by the system to determine user type(other than a session ID which relies on data tiedto the server. Remember, cookies can bemodified by the user, and should be treated as“tainted data.”
  • 45. COOKIES - YUMWriting to and reading cookies in PHP is veryeasy. You can use the setcookie()  function towrite to cookies, but you must do it BEFORE theheaders are sent.Then to read cookies, just use the $_COOKIE  SuperGlobal.
  • 46. COOKIES- YUM <?php<?phpsetcookie(cookie_name, cookie_value, time()+6000);// expires after 60 hoursecho Hi world!;// But now this doesnt work :(setcookie(mycookie, myvalue);// But we can still edit the cookie// data for internal use:)$_COOKIE[cookie_name] = new_value;?>
  • 47. COOKIES - YUMTo delete a cookie in PHP you will create a cookieusing  setcookie()  with the exact same name/key, but with a expiration time in the past.
  • 48. COOKIES- YUM <?php<?phpsetcookie(cookie_name, cookie_value, time()+6000);// expires after 60 hourssetcookie(cookie_name, , time()-1);// cookie has been deleted?>
  • 49. ARRAYSOne powerful data-type we have in PHP isarrays. Unlike JavaScript, arrays are notobjects, but are their own entity type.To declare an array, simply call the array()  function. It’s super easy!
  • 50. ARRAYS <?php<?php// Create an array$myArray = array(one, two, three);// Append to the array$myArray[] = four;array_push($myArray, five);// Ooh what happens here?array_push($myArray, five);var_dump($myArray);// Echos array(one, two, three, four, five, five);?>
  • 51. ARRAY KEYSYou can also setup key value pairs with yourarray. By default, the array starts with a key ofzero (0) and increments by one for each value.If you’re used to working with JavaScript it’s veryeasy to forget this, as arrays in JavaScript startat 1. Remember PHP Arrays start with an indexof 0.
  • 52. ARRAY KEYS <?php<?php// Build Array$myArray = array(key => value);// Append$myArray[newKey] = $value;// Change$myArray[key] = bob;?>
  • 53. ARRAY FUNCTIONSThere are a lot of useful functions for managing yourarray, ranging from count()  to count the number ofvalues in an array, array_push(), array_pop(),array_shift(), array_unshift()  to add or removeitems from the array (either to the beginning or end),array_merge()  to merge two arrays, or sort(),ksort(), usort(), and others to sort your arrayseither by keys or by values.
  • 54. ARRAY FUNCTIONSYou can also use the explode() and implode()functions to “explode” strings into an array basedon a separating character, or “implode” arraysinto a string using a separating character. This isuseful for taking a list of items and turning it intoan array for processing, or to a string for display/storage purposes.
  • 55. EXPLODE/ IMPLODE <?php<?php$list = red,blue,green,yellow;$colors = explode(,, $list);// colors is now an array// [0] => red, [1] => blue,// [2] => green, [3] => yellow$pipe = implode(|, $colors);// pipe is now a string// red|blue|green|yellow$colors2 = explode(|, $pipe);// and a new array called colors2?>
  • 56. LOOPING ARRAYS/ ITERATORSThere are several functions to loop througharrays or iterated objects, including for(),foreach(), and while().
  • 57. LOOPING ARRAYS/ ITERATORS <?php<?php$array = array(1 => a, b, c, d);foreach ($array as $key => $value) {echo $value . is the . $key . letter in the abcs;}$count = count($array);$i = 0;// In this case $i is our key, has to be numericwhile ($i < $count) {echo $array[$i] . is the . $i . letter in the abcs;$i++; // increase $i by one, same as $i = $i + 1;}// Set $i in the loop!for ($i = 1; $i < $count; $i++) {echo $array[$i] . is the . $i . letter in the abcs;}?>
  • 58. LOOPING ARRAYS/ ITERATORS <?php<?php// Foreach is better for arrays, and faster! But...// While is good for database results!while ($item = mysql_fetch_array($result)) {echo $item[firstName] . $item[lastName] .is registered <br />;}?>
  • 59. FORMSOne of the primary uses of server-sidelanguages is form/ data collection. All incomingdata is stored in the $_REQUEST SuperGlobal,as well as the $_POST or $_GET SuperGlobaldepending on the source (Querystring or a formwith a method of Post).
  • 60. FORMSWhile the $_REQUEST SuperGlobalcontains data from POST, GET, andCookies, you should not rely on thisas you do not know WHERE the data is comingfrom and it can be used to manipulate your form.Also, the collection order $_REQUEST uses is setby each server and may be different than what youare expecting.
  • 61. FORMSUsing a form with a method of GET, or withoutsetting the method to POST is essentially thesame as doing it in the URL:doForm.php?name=Bob&age=30&submit=Submit
  • 62. FORMS VIA GET <?php<form action="doForm.php"><!-- This form sends data via GET -->Name: <input type="text" name="name" /><br />Age: <input type="text" name="age" /><br /><input type="submit" name="submit" value="Submit" /></form><?php// GET SuperGlobal Array// $_GET[name] => Bob;// $_GET[age] => 30;// $_GET[submit] => Submit;// POST SuperGlobal is Empty?>
  • 63. FORMS VIA POST <?php<form action="doForm.php" method="post"><!-- This form sends data via GET -->Name: <input type="text" name="name" /><br />Age: <input type="text" name="age" /><br /><input type="submit" name="submit" value="Submit" /></form><?php// GET SuperGlobal is Empty// POST SuperGlobal Array// $_POST[name] => Bob;// $_POST[age] => 30;// $_POST[submit] => Submit;?>
  • 64. HANDLING FORMSNow that we have incoming data we can handleit, first by validating, then by sanitizing thedata, and finally by sending the datasomewhere.First we will start by checking to make sure wehave data.
  • 65. HANDLING FORMS <?php<?phpif ($_POST) {// if there is nothing in the $_POST// SuperGlobal this will not be run/** ... ACTIONS HERE ... **/}?><!-- Form can go here -->
  • 66. HANDLING FORMSWe also want to check and validate that thedata is the data we want. We can do this usingthe isset() function, and making sure thedata fits the parameters that we want.In this case we’re going to use is_numeric()to check the age.
  • 67. HANDLING FORMS <?php<?php$error = ;if ($_POST) {if (!isset($_POST[name])) {$error .= You must enter a name<br />;}if (!isset($_POST[age]) || !is_numeric($_POST[age])) {$error .= You must enter a valid age<br />;}if (!$error) {/** SUBMIT **/} else {// Cut off last BR$error = substr($error, 0, -6);}}?><!-- Form can go here -->
  • 68. HANDLING FORMSIf the form is valid, then we want to sanitizethe data to make sure nothing malicious isbeing passed to us (ie XSS attack or attemptedSQL injection).We will sanitize the data and prepare it to beemailed to us in this next slide:
  • 69. HANDLING FORMSFor more on Form Security reviewIntro to PHP Security andPHP Security 101 slides found athttp://www.mikestowe.com/slides
  • 70. HANDLING FORMS <?php<?php$error = ;if ($_POST) {/** ... **/if (!$error) {$mail = "Form Request" . PHP_EOL . PHP_EOL;// PHP_EOL = end of line, start new line$name = htmlspecialchars(strip_tags($_POST[name]));$age = htmlspecialchars(strip_tags($_POST[age]));$mail .= "Name: " . $name . PHP_EOL;$mail .= "Age: " . $age . PHP_EOL;}/** ... **/}?>
  • 71. SENDING EMAILSending a text email is extremely easy in PHP.To send an email we will use the mail()function which takes 5 arguments:•  To•  Subject•  Message•  Headers (Optional)•  Additional Params (Optional)
  • 72. SENDING EMAIL <?php<?php/** ... **/if (!$error) {$mail = "Form Request" . PHP_EOL . PHP_EOL;// PHP_EOL = end of line, start new line$name = htmlspecialchars(strip_tags($_POST[name]));$age = htmlspecialchars(strip_tags($_POST[age]));$mail .= "Name: " . $name . PHP_EOL;$mail .= "Age: " . $age . PHP_EOL;mail(you@youremail.com, Form Request, $mail, FROM: bot@yoursite.com);}/** ... **/?>!
  • 73. ACCESSING THE DATABASEPHP allows you to connect to and run queries to awide range of databases, of which the most popular isMySQL.PHP comes with three different libraries for accessingMySQL including the deprecated mysql functions, theimproved MySQL extension (MySQLi), and PDO or PHPData Objects.
  • 74. MYSQL TUTORIALSThere are several great tools and resources to learnand use MySQL. Check out some of the sites below tolearn more:http://www.w3schools.com/sql/http://www.tizag.com/mysqlTutorial/
  • 75. PHP DATA OBJECTSIn order to make working with databases easier andSAFER, PHP Data Objects, or PDO was introduced as a wayof connecting to your database and writing queries.Queries can be run as raw queries as with the mysqlfunctions (ie mysql_query()), but PDO allows you tocreate a Query template that uses binded variables orparameters (which are automatically quoted) to preventSQL injection (adding security to your application).
  • 76. USING PHP DATA OBJECTS <?php<?php// Setup PDO Object and Connection Information$db = new PDO(mysql:host=localhost;dbname=testdb;charset=UTF-8,username, password);// Build Query Template$stmt = $db->prepare("SELECT * FROM myTable WHEREusername = :username AND password = :password");// Bind and Sanitize Values// You can bind PHP Variables using the bindParam() method instead$stmt->bindValue(:username, $_POST[username], PDO::PARAM_STR);$stmt->bindValue(:password, $_POST[password], PDO::PARAM_STR);// Execute and Fetch$stmt->execute();$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);Running a Select Query
  • 77. USING PHP DATA OBJECTS <?phpRunning an Insert<?php// Setup PDO Object and Connection Information$db = new PDO(mysql:host=localhost;dbname=testdb;charset=UTF-8,username, password);// Build Query Template$stmt = $db->prepare("INSERT INTO myTable (username, password)VALUES (:username, :password)");// Bind and Sanitize Values// You can bind PHP Variables using the bindParam() method instead$stmt->bindValue(:username, $_POST[username], PDO::PARAM_STR);$stmt->bindValue(:password, $_POST[password], PDO::PARAM_STR);// Execute and Fetch$stmt->execute();
  • 78. USING PHP DATA OBJECTS <?phpRunning an Update<?php// Setup PDO Object and Connection Information$db = new PDO(mysql:host=localhost;dbname=testdb;charset=UTF-8,username, password);// Build Query Template$stmt = $db->prepare("UPDATE myTable SET password = :passwordWHERE username = :username");// Bind and Sanitize Values// You can bind PHP Variables using the bindParam() method instead$stmt->bindValue(:username, $_POST[username], PDO::PARAM_STR);$stmt->bindValue(:password, $_POST[password], PDO::PARAM_STR);// Execute and Fetch$stmt->execute();
  • 79. FUNCTIONSFunctions are groups of code contained within a localscope… basically, what that means is that you canrun the same code time and time again, withouthaving to write it 60,000 times.The local scope allows us to create variables that willonly be used within the function, and will not beutilized anywhere else.
  • 80. FUNCTIONS <?php<?phpfunction echonum($num){echo $num;}for ($i = 1; $i < 4; $i++) {echonum($num);}// Echos out 1, 2, 3?>
  • 81. FUNCTIONS – MULTIPLE PARAMS <?php<?phpfunction add($a, $b){// result is only local$result = $a + $b;// return the resultreturn $result;}$number = add(1, 5);var_dump($number); // prints integer(6);var_dump(isset($result)); // prints bool(false);?>
  • 82. FUNCTIONS – GLOBAL VARIABLES <?php<?phpfunction add($a, $b){// Call in $result, use global scopeglobal $result;// result is only local$result = $a + $b;}$result = 0;add(1, 5);var_dump($result); // prints integer(6);?>
  • 83. CONFERENCE ATTENDEESQUESTIONS?
  • 84. Hopefully…This will give you a good place to start, but one of the bestways to learn is just to get out there and start playing withcode on a development environment. There are a lot of placesthat offer free or low cost hosting where you can build yourown site/ applications and learn more.Remember, the journey is just beginning…
  • 85. More Resourceshttp://www.php.net - PHP Manualhttp://www.mikestowe.com - More slideshttp://www.w3schools.com/php/ - PHP Tutorialhttp://www.tizag.com/phpT/ - PHP Tutorialhttp://www.stackoverflow.com - Great place to ask Questionshttp://www.phpclasses.org - Great collection of PHP scripts
  • 86. Find a PHPUser Grouphttp://www.meetup.comhttp://www.phpusergroups.org/groups.phtmlhttp://www.zend.com/en/company/community/local-php-groups
  • 87. THANK YOU.@mikegstowevisit mikestowe.com/slides for more on PHP and Web Development@ctct_apiA big thank you to Constant Contact formaking this presentation possible