php101
TRANSCRIPT
OUTLINE • WEB FUNDAMENTALS
– Basic Web Architecture – Service Client – HTTP
• STATIC & DYNAMIC PAGES – HTML, CSS, JS – Finally PHP!
• PHP FUNDAMENTALS – Syntax, Types, Arrays, Constants,
Variables, Expressions, Operators, Control Structures, Loops
– Functions – Pre-defined Variables – Session & Cookies, XSS
• PHP + MYSQL
PHP 101 3
PHP – Basic Syntax
PHP 101 18
<?php
echo "Hi there!”; ?>
<?php
include “another.php”; ?>
<?php
require “another.php”; ?>
PHP – Types
PHP 101 19
Integer $x = 1;
Boolean $y = false;
float $pi = 3.14;
String $text = “YTU”;
Array $arr = array(‘a’, ‘b’);
PHP – Array
PHP 101 20
initializing array
<?php
$ytuArr = array(); $ytuArr [0] = ‘YTU’; $ytuArr[1] = 1911;
// or
$ytuArr = array(‘YTU’, 1911);
?>
<?php
$ytuArr[‘university’] = ‘YTU’; $ytuArr[‘year’] = 1991;
?>
PHP – Variables
PHP 101 21
Does not need type of variable!
<?php
$testIntVar = 5; $testTexttVar = “a”; $testBooleanVar= true; $testArrayVar= array();
?>
PHP – Constants
PHP 101 22
const $pi = 3.14; echo $pi;
define(‘PI’, 3.14); echo PI;
#define PI 3.14; printf(PI);
const float pi = 3.14; printf(pi);
PHP C
PHP – Constants
PHP 101 23
//Valid define("__FOO__", "something"); //Valid define ('echo', 'My constant value'); //Invalid define("2FOO", "something"); echo __FOO__; echo constant('echo');
PHP – Expressions
PHP 101 24
<?php
$a = 3.14; $b = $a
echo ‘values: ’.$a.’-’.$b;
<?php …
$first ? $second : $third …
<?php …
function foo () {
return 5; }
$a = foo();
echo $a;
…
PHP – Control Structures
PHP 101 28
<?php
$a = 5; $b = 4;
if($a >= $b) { echo “$a is big or equal”; } else { echo “$b is bigger”; }
void main() {
int a = 5; int b = 4;
if( a >= b) { printf (“%d big or equal”, a); } else { printf (“%d bigger”, b); }
}
PHP C
PHP – Control Structures
PHP 101 29
<?php
$dayIndex = 5; switch ($dayIndex) { case 1 : echo “Monday”; break; case 2 : echo “Tuesday”; break; …… case 5 : echo “Friday”; break; }
void main() {
int dayIndex = 1;
switch (dayIndex) { case 1 : printf("Monday"); break; case 2 : printf("Tuesday"); break;
….. } }
PHP C
PHP – Loops
PHP 101 30
<?php
for( $i = 0; $i <= 10; $i++) { echo $i; }
void main() { int i = 0; for( i = 0; i <= 10; i++) { printf(“%d”, i); }
}
PHP C
for loop
PHP – Loops
PHP 101 31
<?php $i = 0; while($i <= 10) { echo $i; $i++; }
void main() { int i = 0; while(i <= 10) { printf(“%d”, i); i++; }
}
PHP C
while loop
PHP – Loops
PHP 101 32
<?php $i = 0; do { echo $i; $i++; } while ($i <= 10);
void main() { int i = 0; do { printf(“%d”, i); i++; } while (i <= 10);
}
PHP C
do while loop
PHP – Loops
PHP 101 33
<?php $numbers = array( 1, 2, 3, 4, 5); foreach($numbers as $number) { echo $number; }
PHP
foreach loop
PHP – Functions
PHP 101 34
<?php function functionName() { // code to be executed; } // function call functionName();
User defined functions:
PHP – Functions
PHP 101 35
<?php
function loremIpsum() { echo “lorem ipsum”; }
Does not contain return type!
<?php
function loremIpsum() { return “lorem ipsum”; }
PHP – Functions
PHP 101 36
<?php
function returnSampleType() { return true; }
Functions are able to return many types. Boolean, String, Integer, Array …
<?php
function returnSampleType() { return 1; }
<?php
function returnSampleType() { return “YTU”; }
<?php
function returnSampleType() { return array(); }
PHP – Functions
PHP 101 37
<?php string substr(string string, int start[, int length] ); $text = “Yildiz Technical University”; // returns Yildiz $str = substr( $text, 0, 6);
Most used String functions
PHP – Functions
PHP 101 38
<?php int strlen(string string);
$text = “Yildiz Technical University”; // returns 27 $str = strlen($text);
Most used String functions
PHP – Functions
PHP 101 39
<?php mixed str_replace (mixed needle, mixed new_needle, mixed haystack[, int &count]));
$text = “Yildiz Technical University”; // returns Yildiz-Technical-University $str = str_replace($text, ‘ ’, ‘-’);
Most used String functions
PHP – Functions
PHP 101 40
<?php string strtoupper(string string); string strtolower(string string);
$text = “Yildiz Technical University”; // returns YILDIZ TECHNICAL UNIVERSITY $str = strtoupper ($text);
// returns yildiz technical university $str = strtolower ($text);
Most used String functions
PHP – Functions
PHP 101 41
<?php bool isset (mixed mixed); bool empty(mixed mixed); bool in_array(mixed needle, array haystack); $number = 5; $num = null;
var_dump(isset($number)); //true var_dump(empty($number)); //false
var_dump(isset($num)); //false var_dump(empty($num)); //true
var_dump(isset($n)); //false var_dump(empty($n)); //true
Most used control functions
PHP – Functions
PHP 101 42
<?php bool in_array(mixed needle, array haystack);
$array = array( ‘lab1’, ‘lab2’, ‘lab3’, ‘lab4’); // prints false var_dump(in_array(‘lab5’, $array));
// prints true var_dump(in_array(‘lab3’, $array));
Most used control functions
PHP – Predefined Variables
HTTP GET variables <?php $pageNumber = $_GET[‘pageNumber’]; ?>
HTTP POST variables <?php $password= $_POST[‘password’]; ?>
HTTP Request variables An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_GET
$_POST
$_REQUEST
PHP 101 44
PHP – Predefined Variables
Session variables <?php $paymentInfo = $_SESSION[‘paymentInfo ’]; ?>
HTTP Cookies <?php $userName = $_COOKIE[‘userName’]; ?>
$_SESSION
$_COOKIE
PHP 101 45
Server and execution environment information <?php $server = $_SERVER['SERVER_NAME'] ?>
$_SERVER
PHP – Sessions & Cookies
“HTTP is stateless - that is, any data you have stored is forgotten about when the page has been sent to the client and the connection is closed. “
PHP 101 46
QUESTION / Why we need sessions & cookies?
ANSWER / SOLUTION
Cookies… have a bad famous, but a client-side solution
Sessions… a server-side solution
PHP – Sessions & Cookies
“Do you want your data to work when you visitor comes back the next day? “
PHP 101 47
QUESTION / Which to use and when?
ANSWER / SOLUTION
“If so, then your only choice is cookies.“ “If you do not need semi-permanent data, then sessions are generally preferred, as they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes their web browser. “
PHP – Sessions & Cookies
PHP 101 48
Sessions – Starting a session, setting session variables <?php
// Start the session session_start(); // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set.”;
PHP – Sessions & Cookies
PHP 101 49
Sessions – Removing session variables, destroying session <?php
// Start the session session_start(); // remove all session variables session_unset(); // destroy the session session_destroy();
PHP – Sessions & Cookies
PHP 101 50
<?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
Cookies – Setting a cookie
PHP – Sessions & Cookies
PHP 101 51
<?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; }
Cookies – Checking cookie variables
PHP – Sessions & Cookies
PHP 101 52
<?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600);
Cookies – Deleting a cookie
PHP – External & Internal Scripts
PHP 101 54
<script src=http://hacker-site.com/xss.js></script>
<script> alert(“XSS”); </script>
External Script:
Internal Script:
PHP – How to avoid xss with PHP?
PHP 101 55
Data Validation
<?php // validate a US phone number if (preg_match('/^((1-)?d{3}-)d{3}-d{4}$/', $phone)) { echo $phone . " is valid format."; }
PHP – How to avoid xss with PHP?
PHP 101 56
Data Sanitization
<?php // sanitize HTML from the comment $comment = strip_tags($_POST["comment"]);
PHP – How to avoid xss with PHP?
PHP 101 57
Output Escaping
<?php // escape output sent to the browser echo "You searched for: " . htmlspecialchars($_GET["query"]);
PHP + MYSQL
PHP 101 59
Connecting MySQL database
<?php $host = ‘localhost’; $user = ‘root’; $pass = ‘********’;
$connection = mysql_connect($host, $user, $pass);
Selecting Schema
<?php $db = ‘test’; mysql_select_db($db, $connection);
PHP + MYSQL
PHP 101 60
Running Query
<?php $sampleQuery = “DELETE FROM comment LIMIT 1”; $query= mysql_query($sampleQuery);
Querying is not enough if you need to fetch result set!
PHP + MYSQL
PHP 101 61
Fetching Result
<?php $sampleQuery = “SELECT * FROM comment”; $query= mysql_query($sampleQuery);
$results = array();
while($row = mysql_fetch_assoc($query)) {
$results[] = $row; }
PHP + MYSQL
PHP 101 63
Other useful MySQL specific functions
<?php mysql_error(); mysql_errno(); mysql_info(); mysql_num_rows(); mysql_escape_string();
SQL INJECTION!
PHP 101 64
It’s possible to inject by http parameters
<?php $id = $_GET[‘id’];
$query = “SELECT * FROM comment WHERE COMMENT_ID = $id;
SQL INJECTION!
PHP 101 65
It’s ok if $id is integer. But!
<?php // assume that $id = “1 OR 1=1”; $id = $_GET[‘id’];
$query = “SELECT * FROM comment WHERE COMMENT_ID = $id;
SQL INJECTION!
PHP 101 66
Here is a nice solution:
<?php // assume that $id = “1 OR 1=1”; $id = intval($_GET[‘id’]);
$query = “SELECT * FROM comment WHERE COMMENT_ID = $id;
FURTHER READINGS
• http://scholar.lib.vt.edu/manuals/php3.0.6/intro-history.html • http://phpsecurity.readthedocs.org/en/latest/Cross-Site-Scripting-%28XSS%29.html
• https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
• http://en.wikipedia.org/wiki/PHP Note: And all referances are also further readings J
PRESENTATION TITLE GOES HERE 71