SlideShare a Scribd company logo
PHP 101
Seda Yalçın & Ömer Taşkın
ABOUT US
PHP 101 2
Software
Engineer@GG
Seda Yalçın
Software
Engineer@GG
Ömer Taşkın
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
INTERNET
PHP 101 4
WEB
PHP 101 5
BASIC WEB ARCHITECTURE
PHP 101 6
SERVICE – CLIENT
PHP 101 7
HTTP
PHP 101 8
HTTP
PHP 101 9
HTTP
PHP 101 10
STATIC PAGES
PHP 101 11
DYNAMIC PAGES
PHP 101 12
HTML
JUST
VİEW
PAGE
SOURCE
PHP 101 13
CSS
PHP 101 14
JAVASCRIPT
PHP 101 15
LAB #1 Static Page Example
PHP 101 16
PHP
PHP 101 | 17
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 – Operators
PHP 101 25
Arithmetic Operators
PHP – Operators
PHP 101 26
Assignment Operators
PHP – Operators
PHP 101 27
Comparison Operators
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
LAB #2 Dynamic Page Example with PHP Fundamentals
PHP 101 43
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 – What is XSS?
PHP 101 53
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"]);
LAB #3 Session & Cookie Usages, XSS Example
PHP 101 58
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 62
Closing MySQL connection
<?php
mysql_close();
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;
LAB #4 Simple Comment Form Example
PHP 101 67
What can you do with PHP?
PHP 101 68
Server-side scripting
Command line scripting
API Services
Most known PHP applications / websites
PHP 101 69
QUESTIONS
PHP 101 70
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
REFERANCES
• http://www.php.net
• http://www.w3schools.com
• http://www.tuxradar.com/practicalphp/10/1/0
• http://www.acunetix.com/websitesecurity/cross-site-scripting/
• http://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/
Note: All images, from google images J
PHP 101 72

More Related Content

PDF
Php web backdoor obfuscation
PDF
PHP Backdoor: The rise of the vuln
PDF
Code obfuscation, php shells & more
PDF
Review unknown code with static analysis Zend con 2017
PDF
Review unknown code with static analysis
TXT
PDF
Testing TYPO3 Applications
PDF
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
Php web backdoor obfuscation
PHP Backdoor: The rise of the vuln
Code obfuscation, php shells & more
Review unknown code with static analysis Zend con 2017
Review unknown code with static analysis
Testing TYPO3 Applications
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013

What's hot (20)

PDF
PHP7 - Scalar Type Hints & Return Types
PDF
Top 10 php classic traps php serbia
KEY
PHP security audits
PDF
Top 10 php classic traps confoo
PDF
Semantic Web & TYPO3
PDF
Introdução ao Perl 6
PPT
SQL Injection in PHP
PDF
Perl6 grammars
PDF
OWASP Top 10 at International PHP Conference 2014 in Berlin
PPT
Synapseindia php development tutorial
PDF
OWASP TOP 10 for PHP Programmers
PDF
PHP Secure Programming
PDF
PHP an intro -1
PDF
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
PDF
Php Security
PDF
Using Phing for Fun and Profit
PPTX
Php mysq
PPT
Php with my sql
PDF
Melhorando sua API com DSLs
PDF
R57shell
PHP7 - Scalar Type Hints & Return Types
Top 10 php classic traps php serbia
PHP security audits
Top 10 php classic traps confoo
Semantic Web & TYPO3
Introdução ao Perl 6
SQL Injection in PHP
Perl6 grammars
OWASP Top 10 at International PHP Conference 2014 in Berlin
Synapseindia php development tutorial
OWASP TOP 10 for PHP Programmers
PHP Secure Programming
PHP an intro -1
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
Php Security
Using Phing for Fun and Profit
Php mysq
Php with my sql
Melhorando sua API com DSLs
R57shell
Ad

Similar to Php101 (20)

PPTX
php is the most important programming language
PPT
Php mysql
PPT
slidesharenew1
PPT
My cool new Slideshow!
PPT
Php Tutorial
PDF
basic concept of php(Gunikhan sonowal)
PPTX
An introduction to PHP : PHP and Using PHP, Variables Program control and Bui...
PPTX
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
PPTX
Unit 4-6 sem 7 Web Technologies.pptx
PPT
Introducation to php for beginners
PPT
Php mysql
PPT
PPT
Php mysql
PPT
Php basic for vit university
PDF
Introduction of PHP.pdf
PPT
PHP MySQL Workshop - facehook
PDF
PHP Unit-1 Introduction to PHP
PPTX
Day1
php is the most important programming language
Php mysql
slidesharenew1
My cool new Slideshow!
Php Tutorial
basic concept of php(Gunikhan sonowal)
An introduction to PHP : PHP and Using PHP, Variables Program control and Bui...
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Unit 4-6 sem 7 Web Technologies.pptx
Introducation to php for beginners
Php mysql
Php mysql
Php basic for vit university
Introduction of PHP.pdf
PHP MySQL Workshop - facehook
PHP Unit-1 Introduction to PHP
Day1
Ad

More from Ömer Taşkın (9)

PPTX
Unit testing and junit
PPTX
PPTX
No sql and mongodb
PDF
Dependency management
PPTX
Oop basics
PPTX
Web Programming - Git basics
PDF
Unit testing and junit
No sql and mongodb
Dependency management
Oop basics
Web Programming - Git basics

Recently uploaded (20)

PDF
Complications of Minimal Access Surgery at WLH
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Cell Structure & Organelles in detailed.
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Classroom Observation Tools for Teachers
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
Lesson notes of climatology university.
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
2.FourierTransform-ShortQuestionswithAnswers.pdf
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Yogi Goddess Pres Conference Studio Updates
Cell Structure & Organelles in detailed.
Weekly quiz Compilation Jan -July 25.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Chinmaya Tiranga quiz Grand Finale.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Classroom Observation Tools for Teachers
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Orientation - ARALprogram of Deped to the Parents.pptx
Lesson notes of climatology university.
STATICS OF THE RIGID BODIES Hibbelers.pdf

Php101

  • 1. PHP 101 Seda Yalçın & Ömer Taşkın
  • 2. ABOUT US PHP 101 2 Software Engineer@GG Seda Yalçın Software Engineer@GG Ömer Taşkın
  • 3. 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
  • 16. LAB #1 Static Page Example PHP 101 16
  • 18. PHP – Basic Syntax PHP 101 18 <?php echo "Hi there!”; ?> <?php include “another.php”; ?> <?php require “another.php”; ?>
  • 19. PHP – Types PHP 101 19 Integer $x = 1; Boolean $y = false; float $pi = 3.14; String $text = “YTU”; Array $arr = array(‘a’, ‘b’);
  • 20. 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; ?>
  • 21. PHP – Variables PHP 101 21 Does not need type of variable! <?php $testIntVar = 5; $testTexttVar = “a”; $testBooleanVar= true; $testArrayVar= array(); ?>
  • 22. 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
  • 23. PHP – Constants PHP 101 23 //Valid define("__FOO__", "something");  //Valid define ('echo', 'My constant value'); //Invalid define("2FOO",    "something"); echo __FOO__; echo constant('echo');
  • 24. 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; …
  • 25. PHP – Operators PHP 101 25 Arithmetic Operators
  • 26. PHP – Operators PHP 101 26 Assignment Operators
  • 27. PHP – Operators PHP 101 27 Comparison Operators
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. PHP – Loops PHP 101 33 <?php $numbers = array( 1, 2, 3, 4, 5); foreach($numbers as $number) { echo $number; } PHP foreach loop
  • 34. PHP – Functions PHP 101 34 <?php function functionName() { // code to be executed; } // function call functionName(); User defined functions:
  • 35. PHP – Functions PHP 101 35 <?php function loremIpsum() { echo “lorem ipsum”; } Does not contain return type! <?php function loremIpsum() { return “lorem ipsum”; }
  • 36. 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(); }
  • 37. 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
  • 38. PHP – Functions PHP 101 38 <?php int strlen(string string); $text = “Yildiz Technical University”; // returns 27 $str = strlen($text); Most used String functions
  • 39. 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
  • 40. 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
  • 41. 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
  • 42. 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
  • 43. LAB #2 Dynamic Page Example with PHP Fundamentals PHP 101 43
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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. “
  • 48. 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.”;
  • 49. 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();
  • 50. 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
  • 51. 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
  • 52. PHP – Sessions & Cookies PHP 101 52 <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); Cookies – Deleting a cookie
  • 53. PHP – What is XSS? PHP 101 53
  • 54. PHP – External & Internal Scripts PHP 101 54 <script src=http://hacker-site.com/xss.js></script> <script> alert(“XSS”); </script> External Script: Internal Script:
  • 55. 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."; }
  • 56. PHP – How to avoid xss with PHP? PHP 101 56 Data Sanitization <?php // sanitize HTML from the comment $comment = strip_tags($_POST["comment"]);
  • 57. 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"]);
  • 58. LAB #3 Session & Cookie Usages, XSS Example PHP 101 58
  • 59. 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);
  • 60. 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!
  • 61. 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; }
  • 62. PHP + MYSQL PHP 101 62 Closing MySQL connection <?php mysql_close();
  • 63. PHP + MYSQL PHP 101 63 Other useful MySQL specific functions <?php mysql_error(); mysql_errno(); mysql_info(); mysql_num_rows(); mysql_escape_string();
  • 64. 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;
  • 65. 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;
  • 66. 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;
  • 67. LAB #4 Simple Comment Form Example PHP 101 67
  • 68. What can you do with PHP? PHP 101 68 Server-side scripting Command line scripting API Services
  • 69. Most known PHP applications / websites PHP 101 69