SlideShare une entreprise Scribd logo
1  sur  61
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
Ch5(ms access with php)
Ch5(ms access with php)Ch5(ms access with php)
Ch5(ms access with php)Chhom Karath
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan 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 TalkMichael Peacock
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Kris Wallsmith
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
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 PHPYogesh singh
 
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, MoscowRobert Nyman
 

Tendances (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
 

En vedette

Beginning Css
Beginning CssBeginning Css
Beginning Css8ran
 
Responsive UI using CSS Media Query
Responsive UI using CSS Media QueryResponsive UI using CSS Media Query
Responsive UI using CSS Media QueryNeev Technologies
 
Authoring Stylesheets with Compass & Sass
Authoring Stylesheets with Compass & SassAuthoring Stylesheets with Compass & Sass
Authoring Stylesheets with Compass & Sasschriseppstein
 
Mobile Web App Development
Mobile Web App DevelopmentMobile Web App Development
Mobile Web App DevelopmentBrian 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 mobileRoland Tanglao
 
ApacheCon 2011
ApacheCon 2011ApacheCon 2011
ApacheCon 2011mwbrooks
 
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 Chris Love
 
HT16 - DA156A - CSS, layout
HT16 - DA156A - CSS, layoutHT16 - DA156A - CSS, layout
HT16 - DA156A - CSS, layoutAnton Tibblin
 
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 LayoutsSvitlana Ivanytska
 
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 DevelopmentSimon Guest
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGapChristian Rokitta
 

En vedette (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
 

Similaire à 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 SystemAzharul Haque Shohan
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
 
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.pdfAppweb Coders
 
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-KjaerCOMMON Europe
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebRobert Nyman
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operationsyeda zoya mehdi
 
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 Symfony2Hugo Hamon
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 
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 DatabaseChristopher Singleton
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxCynthiaKendi1
 

Similaire à 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
 

Plus de Dan Phiffer

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
Static layouts with css
Static layouts with cssStatic layouts with css
Static layouts with cssDan Phiffer
 
Word press templates
Word press templatesWord press templates
Word press templatesDan Phiffer
 
Intro to word press
Intro to word pressIntro to word press
Intro to word pressDan Phiffer
 

Plus 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
 

Dernier

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Dernier (20)

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

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