SlideShare uma empresa Scribd logo
1 de 61
Baixar para ler offline
Diving into PHP
Fast, Easy, Complicated, and Powerful Web
   ITP, Spring 2011, section 1, session 1
         Dan Phiffer dan@phiffer.org
Diving into PHP
A simple content
management system


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
Basic form
<form action="basic-form.php">
  <input type="text" name="query" />
  <input type="submit" name="button" value="Kablooey" />
</form>
Feedback
<?php

echo $_REQUEST["query"];

?>
<form action="basic-form.php">
   <input type="text" name="query" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Feedback
<?php

echo $_REQUEST["query"];

?>
<form action="basic-form.php">
   <input type="text" name="query" />
   <input type="submit" name="button" value="Kablooey" />
</form>
What’s that ‘notice’ about?
<?php

echo $_REQUEST["query"];

?>
<form action="basic-form.php">
   <input type="text" name="query" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Solution: check if it’s set
<?php
if (isset($_REQUEST["query"])) {
   echo $_REQUEST["query"];
}
?>
<form action="basic-form.php">
   <input type="text" name="query" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Dynamic strings
<?php
if (isset($_REQUEST['query'])) {
   echo "<h1>You wrote: '{$_REQUEST['query']}'</h1>";
}
?>
<form action="basic-form.php">
   <input type="text" name="query" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Try it out
Defining a new variable

<?php
$query = "";
if (isset($_REQUEST["query"])) {
   $query = $_REQUEST["query"];
   echo "<h1>You wrote: '$query'</h1>";
}
?>
<form action="basic-form.php" >
   <input type="text" name="query"
          value="<?php echo $query; ?>" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Step 1 complete!
Wait, this is bad
User types input...
Clicks away... arbitrary
JavaScript execution!
We’ve been tricked into
adding an ‘onblur’
attribute!
Cross-site scripting (XSS)


• A common security vulnerability
• When content is unintentionally
  executed as code

• We must handle user-submitted
  content very carefully
Dangers of XSS


• Users’ sessions could be hijacked
• Passwords could be stolen
• Your site could get spammed up
• Puppies murdered, etc.
Escaping user input

<?php
$query = "";
if (isset($_REQUEST["query"])) {
   // htmlentities() turns " into &quot;
   $query = htmlentities($_REQUEST["query"]);
   echo "<h1>You wrote: '$query'</h1>";
}
?>
<form action="basic-form.php" >
   <input type="text" name="query"
          value="<?php echo $query; ?>" />
   <input type="submit" name="button" value="Kablooey" />
</form>
Before & after escaping
Now we’re really finished
with step 1


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
Adding a database
Relational databases

• Tables with columns and rows of
  individual data cells

• SQL is the language for working with
  relational databases

• MySQL is the database platform used
  by WordPress
The four operations

• Create new rows with INSERT
• Read rows with SELECT
• Update rows with UPDATE
• Delete rows with DELETE
• MySQL documentation
MySQL clients


• Sequel Pro (Mac OS X)
• SQLWave, SQLMaestro (Windows)
• phpMyAdmin (web-based)
• Or from the command-line: ‘mysql’
$ mysql -u root
mysql> CREATE DATABASE
-> tinydb CHARACTER SET utf8;
mysql> USE tinydb;
mysql> CREATE TABLE tinytable
-> (id INTEGER PRIMARY KEY AUTO_INCREMENT);
mysql> ALTER TABLE tinytable ADD COLUMN
-> content TEXT;
mysql> INSERT INTO tinytable
-> (id, content)
-> VALUES (1, 'Hello, world!');
mysql> SELECT * FROM tinytable;
Let’s build a tiny wiki!
A simple content
management system


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
A simple content
management system


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
Basic form
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type"
           content="text/html; charset=utf-8" />
    <title>Tiny wiki</title>
  </head>
  <body>
    <?php
    $content = ""; // We need to load the content!
    ?>
    <form action="tiny-wiki.php" method="post">
       <input type="text" name="content"
              value="<?php echo $content; ?>" />
       <input type="submit" value="Update" />
    </form>
  </body>
</html>
Add a load function

<?php

$content = load_content();

function load_content() {
  // Load content from the database
  return "";
}

?>
Add a database function
<?php

$db = connect_to_database();
$content = load_content($db);

function load_content($db) {
  // Load content from the database
  return "";
}

function connect_to_database() {
  // Connect to the database
}

?>
Connecting to the
database

function connect_to_database() {
  $host = "127.0.0.1";
  $port = 8889;
  $user = "root";
  $pass = "root";
  $name = "tinydb";
  $dsn = "mysql:host=$host;port=$port;dbname=$name";
  return new PDO($dsn, $user, $pass);
}
Querying the database


function load_content($db) {
  $sql = "SELECT * FROM tinytable ORDER BY id DESC";
  $query = $db->query($sql);
  $results = $query->fetchAll();
  $row = $results[0];
  return $row["content"];
}
tiny-wiki.php
    <?php

    $db = connect_to_database();
    $content = load_content($db);

    function load_content($db) {
      $sql = "SELECT * FROM tinytable ORDER BY id DESC";
      $query = $db->query($sql);
      $results = $query->fetchAll();
      $row = $results[0];
      return $row['content'];
    }

    function connect_to_database() {
      $host = "127.0.0.1";
      $port = 8889;
      $user = "root";
      $pass = "root";
      $name = "tinydb";
      $dsn = "mysql:host=$host;port=$port;dbname=$name";
      return new PDO($dsn, $user, $pass);
    }

    ?>
    <form action="tiny-wiki.php" method="post">
       <input type="text" name="content" value="<?php echo $content; ?>" />
       <input type="submit" value="Update" />
    </form>
Result
A simple content
management system


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
Core logic

<?php

$db = connect_to_database();
$content = load_content($db);

if (!empty($_REQUEST["content"])) {
  save_content($db, $_REQUEST["content"]);
  $content = htmlentities($_REQUEST["content"]);
}

?>
Saving the content


function save_content($content) {
  $sql = "INSERT INTO tinytable (content)
          VALUES ('$content')";
  $db->query($sql);
}
Save the content
A simple content
management system


1. Build a form for user input
2. Store submissions in a database
3. Retrieve submission data
Wait, this is bad
How does it work?




$content = "'); drop table tinytable; --";
$sql = "INSERT INTO tinytable (content)
        VALUES ('$content')";
How does it work?




$content = "'); drop table tinytable; --";
$sql = "INSERT INTO tinytable (content)
        VALUES ('$content')";

//     Result: (-- is a comment in SQL)
//     "INSERT INTO tinytable (content)
//      VALUES (''); drop table tinytable; --')
SQL injection

• Another security vulnerability, similar
  to cross site scripting

• When user data is unintentionally
  executed as SQL

• Escaping works here also (also,
  prepared statements)
Escape the user input


function save_content($db, $content) {
  $content = $db->quote($content);
  $sql = "INSERT INTO tinytable (content)
          VALUES ($content)"; // no more single quotes
  $db->query($sql, array($content));
}
Done!


• Download the files
• Try running the tiny wiki on your
  own local Apache/MySQL/PHP

• Get familiar with the PHP manual

Mais conteúdo relacionado

Mais procurados

Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
Jonathan Wage
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 

Mais procurados (18)

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Ch5(ms access with php)
Ch5(ms access with php)Ch5(ms access with php)
Ch5(ms access with php)
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
REST API with CakePHP
REST API with CakePHPREST API with CakePHP
REST API with CakePHP
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
 
Assetic (OSCON)
Assetic (OSCON)Assetic (OSCON)
Assetic (OSCON)
 
What's Parse
What's ParseWhat's Parse
What's Parse
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
Presentation
PresentationPresentation
Presentation
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHP
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
 
Add loop shortcode
Add loop shortcodeAdd loop shortcode
Add loop shortcode
 
25437 pertemuan25(hitcounter)
25437 pertemuan25(hitcounter)25437 pertemuan25(hitcounter)
25437 pertemuan25(hitcounter)
 
Tax management-system
Tax management-systemTax management-system
Tax management-system
 

Destaque

Beginning Css
Beginning CssBeginning Css
Beginning Css
8ran
 
Mobile Web App Development
Mobile Web App DevelopmentMobile Web App Development
Mobile Web App Development
Brian LeRoux
 
7 things you should know about mobile
7 things you should know about mobile7 things you should know about mobile
7 things you should know about mobile
Roland Tanglao
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap
Christian Rokitta
 

Destaque (12)

Web API Design
Web API DesignWeb API Design
Web API Design
 
Beginning Css
Beginning CssBeginning Css
Beginning Css
 
Responsive UI using CSS Media Query
Responsive UI using CSS Media QueryResponsive UI using CSS Media Query
Responsive UI using CSS Media Query
 
Authoring Stylesheets with Compass & Sass
Authoring Stylesheets with Compass & SassAuthoring Stylesheets with Compass & Sass
Authoring Stylesheets with Compass & Sass
 
Mobile Web App Development
Mobile Web App DevelopmentMobile Web App Development
Mobile Web App Development
 
7 things you should know about mobile
7 things you should know about mobile7 things you should know about mobile
7 things you should know about mobile
 
ApacheCon 2011
ApacheCon 2011ApacheCon 2011
ApacheCon 2011
 
Using Responsive Web Design To Make Your Web Work Everywhere
Using Responsive Web Design To Make Your Web Work Everywhere Using Responsive Web Design To Make Your Web Work Everywhere
Using Responsive Web Design To Make Your Web Work Everywhere
 
HT16 - DA156A - CSS, layout
HT16 - DA156A - CSS, layoutHT16 - DA156A - CSS, layout
HT16 - DA156A - CSS, layout
 
CSS3 Media Queries And Creating Adaptive Layouts
CSS3 Media Queries And Creating Adaptive LayoutsCSS3 Media Queries And Creating Adaptive Layouts
CSS3 Media Queries And Creating Adaptive Layouts
 
Top Ten Tips for HTML5/Mobile Web Development
Top Ten Tips for HTML5/Mobile Web DevelopmentTop Ten Tips for HTML5/Mobile Web Development
Top Ten Tips for HTML5/Mobile Web Development
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap
 

Semelhante a Diving into php

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
Appweb Coders
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the Web
Robert Nyman
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 

Semelhante a Diving into php (20)

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
 
Php (1)
Php (1)Php (1)
Php (1)
 
Practical PHP by example Jan Leth-Kjaer
Practical PHP by example   Jan Leth-KjaerPractical PHP by example   Jan Leth-Kjaer
Practical PHP by example Jan Leth-Kjaer
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the Web
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
JSP
JSPJSP
JSP
 
Php summary
Php summaryPhp summary
Php summary
 
PHP || [Student Result Management System]
PHP || [Student Result Management System]PHP || [Student Result Management System]
PHP || [Student Result Management System]
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operation
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
 

Mais de Dan Phiffer (7)

Occupy.here
Occupy.hereOccupy.here
Occupy.here
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Static layouts with css
Static layouts with cssStatic layouts with css
Static layouts with css
 
Word press templates
Word press templatesWord press templates
Word press templates
 
Intro to word press
Intro to word pressIntro to word press
Intro to word press
 
The web context
The web contextThe web context
The web context
 
Web tech 101
Web tech 101Web tech 101
Web tech 101
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

Diving into php

  • 1. Diving into PHP Fast, Easy, Complicated, and Powerful Web ITP, Spring 2011, section 1, session 1 Dan Phiffer dan@phiffer.org
  • 3. A simple content management system 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 4. Basic form <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 5. Feedback <?php echo $_REQUEST["query"]; ?> <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 6. Feedback <?php echo $_REQUEST["query"]; ?> <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 7. What’s that ‘notice’ about? <?php echo $_REQUEST["query"]; ?> <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 8. Solution: check if it’s set <?php if (isset($_REQUEST["query"])) { echo $_REQUEST["query"]; } ?> <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 9. Dynamic strings <?php if (isset($_REQUEST['query'])) { echo "<h1>You wrote: '{$_REQUEST['query']}'</h1>"; } ?> <form action="basic-form.php"> <input type="text" name="query" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 11. Defining a new variable <?php $query = ""; if (isset($_REQUEST["query"])) { $query = $_REQUEST["query"]; echo "<h1>You wrote: '$query'</h1>"; } ?> <form action="basic-form.php" > <input type="text" name="query" value="<?php echo $query; ?>" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 16. We’ve been tricked into adding an ‘onblur’ attribute!
  • 17. Cross-site scripting (XSS) • A common security vulnerability • When content is unintentionally executed as code • We must handle user-submitted content very carefully
  • 18. Dangers of XSS • Users’ sessions could be hijacked • Passwords could be stolen • Your site could get spammed up • Puppies murdered, etc.
  • 19. Escaping user input <?php $query = ""; if (isset($_REQUEST["query"])) { // htmlentities() turns " into &quot; $query = htmlentities($_REQUEST["query"]); echo "<h1>You wrote: '$query'</h1>"; } ?> <form action="basic-form.php" > <input type="text" name="query" value="<?php echo $query; ?>" /> <input type="submit" name="button" value="Kablooey" /> </form>
  • 20. Before & after escaping
  • 21. Now we’re really finished with step 1 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 23. Relational databases • Tables with columns and rows of individual data cells • SQL is the language for working with relational databases • MySQL is the database platform used by WordPress
  • 24. The four operations • Create new rows with INSERT • Read rows with SELECT • Update rows with UPDATE • Delete rows with DELETE • MySQL documentation
  • 25. MySQL clients • Sequel Pro (Mac OS X) • SQLWave, SQLMaestro (Windows) • phpMyAdmin (web-based) • Or from the command-line: ‘mysql’
  • 26. $ mysql -u root
  • 28. -> tinydb CHARACTER SET utf8;
  • 30. mysql> CREATE TABLE tinytable
  • 31. -> (id INTEGER PRIMARY KEY AUTO_INCREMENT);
  • 32.
  • 33. mysql> ALTER TABLE tinytable ADD COLUMN
  • 35.
  • 36.
  • 37. mysql> INSERT INTO tinytable
  • 39. -> VALUES (1, 'Hello, world!');
  • 40. mysql> SELECT * FROM tinytable;
  • 41. Let’s build a tiny wiki!
  • 42. A simple content management system 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 43. A simple content management system 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 44. Basic form <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Tiny wiki</title> </head> <body> <?php $content = ""; // We need to load the content! ?> <form action="tiny-wiki.php" method="post"> <input type="text" name="content" value="<?php echo $content; ?>" /> <input type="submit" value="Update" /> </form> </body> </html>
  • 45. Add a load function <?php $content = load_content(); function load_content() { // Load content from the database return ""; } ?>
  • 46. Add a database function <?php $db = connect_to_database(); $content = load_content($db); function load_content($db) { // Load content from the database return ""; } function connect_to_database() { // Connect to the database } ?>
  • 47. Connecting to the database function connect_to_database() { $host = "127.0.0.1"; $port = 8889; $user = "root"; $pass = "root"; $name = "tinydb"; $dsn = "mysql:host=$host;port=$port;dbname=$name"; return new PDO($dsn, $user, $pass); }
  • 48. Querying the database function load_content($db) { $sql = "SELECT * FROM tinytable ORDER BY id DESC"; $query = $db->query($sql); $results = $query->fetchAll(); $row = $results[0]; return $row["content"]; }
  • 49. tiny-wiki.php <?php $db = connect_to_database(); $content = load_content($db); function load_content($db) { $sql = "SELECT * FROM tinytable ORDER BY id DESC"; $query = $db->query($sql); $results = $query->fetchAll(); $row = $results[0]; return $row['content']; } function connect_to_database() { $host = "127.0.0.1"; $port = 8889; $user = "root"; $pass = "root"; $name = "tinydb"; $dsn = "mysql:host=$host;port=$port;dbname=$name"; return new PDO($dsn, $user, $pass); } ?> <form action="tiny-wiki.php" method="post"> <input type="text" name="content" value="<?php echo $content; ?>" /> <input type="submit" value="Update" /> </form>
  • 51. A simple content management system 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 52. Core logic <?php $db = connect_to_database(); $content = load_content($db); if (!empty($_REQUEST["content"])) { save_content($db, $_REQUEST["content"]); $content = htmlentities($_REQUEST["content"]); } ?>
  • 53. Saving the content function save_content($content) { $sql = "INSERT INTO tinytable (content) VALUES ('$content')"; $db->query($sql); }
  • 55. A simple content management system 1. Build a form for user input 2. Store submissions in a database 3. Retrieve submission data
  • 57. How does it work? $content = "'); drop table tinytable; --"; $sql = "INSERT INTO tinytable (content) VALUES ('$content')";
  • 58. How does it work? $content = "'); drop table tinytable; --"; $sql = "INSERT INTO tinytable (content) VALUES ('$content')"; // Result: (-- is a comment in SQL) // "INSERT INTO tinytable (content) // VALUES (''); drop table tinytable; --')
  • 59. SQL injection • Another security vulnerability, similar to cross site scripting • When user data is unintentionally executed as SQL • Escaping works here also (also, prepared statements)
  • 60. Escape the user input function save_content($db, $content) { $content = $db->quote($content); $sql = "INSERT INTO tinytable (content) VALUES ($content)"; // no more single quotes $db->query($sql, array($content)); }
  • 61. Done! • Download the files • Try running the tiny wiki on your own local Apache/MySQL/PHP • Get familiar with the PHP manual