SlideShare a Scribd company logo
1 of 72
Download to read offline
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

What's hot

PHP an intro -1
PHP an intro -1PHP an intro -1
PHP an intro -1
Kanchilug
 
R57shell
R57shellR57shell
R57shell
ady36
 

What's hot (20)

PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbia
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Top 10 php classic traps confoo
Top 10 php classic traps confooTop 10 php classic traps confoo
Top 10 php classic traps confoo
 
Semantic Web & TYPO3
Semantic Web & TYPO3Semantic Web & TYPO3
Semantic Web & TYPO3
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in Berlin
 
Synapseindia php development tutorial
Synapseindia php development tutorialSynapseindia php development tutorial
Synapseindia php development tutorial
 
OWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmers
 
PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
PHP an intro -1
PHP an intro -1PHP an intro -1
PHP an intro -1
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQUA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
 
Php Security
Php SecurityPhp Security
Php Security
 
Using Phing for Fun and Profit
Using Phing for Fun and ProfitUsing Phing for Fun and Profit
Using Phing for Fun and Profit
 
Php mysq
Php mysqPhp mysq
Php mysq
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
R57shell
R57shellR57shell
R57shell
 

Similar to Php101

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )
Joseph Scott
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
Nat Weerawan
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
ShaimaaMohamedGalal
 

Similar to Php101 (20)

Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
PHP and MySQL.ppt
PHP and MySQL.pptPHP and MySQL.ppt
PHP and MySQL.ppt
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )Anatomy of a PHP Request ( UTOSC 2010 )
Anatomy of a PHP Request ( UTOSC 2010 )
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Intro to php
Intro to phpIntro to php
Intro to php
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Php hacku
Php hackuPhp hacku
Php hacku
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect Partners
 

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

Unit testing and junit
Unit testing and junitUnit testing and junit
Unit testing and junit
 
GraphDB
GraphDBGraphDB
GraphDB
 
No sql and mongodb
No sql and mongodbNo sql and mongodb
No sql and mongodb
 
Dependency management
Dependency managementDependency management
Dependency management
 
Orm
OrmOrm
Orm
 
Soa
SoaSoa
Soa
 
Oop basics
Oop basicsOop basics
Oop basics
 
Web Programming - Git basics
Web Programming - Git basicsWeb Programming - Git basics
Web Programming - Git basics
 
XXLWEB
XXLWEBXXLWEB
XXLWEB
 

Recently uploaded

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
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
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

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