SlideShare a Scribd company logo
1 of 30
Download to read offline
#BURNINGKEYBOARDS
DENIS.RISTIC@PERPETUUM.HR
INTRODUCTION TO
PHP
INTRODUCTION TO PHP
PHP SYNTAX
▸ A PHP script starts with <?php and ends with ?> (not always)
▸ PHP statements end with a semicolon (;)
▸ Comments in PHP
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple lines
*/
▸ In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are
NOT case-sensitive
▸ However; all variable names ARE case-sensitive.
3
INTRODUCTION TO PHP
PHP VARIABLES
▸ In PHP, a variable starts with the $ sign, followed by the name of the variable
▸ Rules for PHP variables:
▸ A variable starts with the $ sign, followed by the name of the variable
▸ A variable name must start with a letter or the underscore character
▸ A variable name cannot start with a number
▸ A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
▸ Variable names are case-sensitive ($age and $AGE are two different
variables)
4
INTRODUCTION TO PHP
PHP VARIABLES
▸ PHP is a Loosely Typed Language
▸ The scope of a variable is the part of the script where the variable can be
referenced/used.
▸ PHP has three different variable scopes: local, global, static
▸ A variable declared outside a function has a global scope and can only be
accessed outside a function
▸ A variable declared within a function has a local scope and can only be accessed
within that function
▸ The global keyword is used to access a global variable from within a function
▸ Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. To do this, use
the static keyword when you first declare the variable
5
INTRODUCTION TO PHP
PHP ECHO AND PRINT STATEMENTS
▸ In PHP there are two basic ways to get output: echo and
print
▸ echo and print are more or less the same, they are both
used to output data to the screen
▸ The differences are small: echo has no return value while
print has a return value of 1 so it can be used in
expressions. echo can take multiple parameters (although
such usage is rare) while print can take one argument.
echo is marginally faster than print
6
INTRODUCTION TO PHP
PHP EXAMPLE
<?php
echo "Hello World!";
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo "I love $txt!";
echo "I love " . $txt . "!";
echo "I love {$txt}!";
echo $x + $y;
7
INTRODUCTION TO PHP
PHP EXAMPLE
<?php
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
// using x outside the function will generate an error
echo "Variable x outside function is: $x";
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
8
INTRODUCTION TO PHP
PHP DATA TYPES
▸ PHP supports the following data types:
▸ String
▸ Integer
▸ Float (floating point numbers - also called double)
▸ Boolean
▸ Array
▸ Object
▸ NULL
▸ Resource
9
INTRODUCTION TO PHP
DATA TYPES EXAMPLE
<?php
$x = 'Hello world!';
echo $x;
$x = 5985;
var_dump($x);
$x = 10.365;
var_dump($x);
$x = true;
var_dump($x);
$cars = ["Volvo", "BMW", "Toyota"];
var_dump($cars);
class Car {
public $model;
function __construct($model) {
$this->model = $model;
}
}
$golf = new Car("WW");
echo $golf->model;
$x = null;
var_dump($x);
10
INTRODUCTION TO PHP
PHP CONSTANTS
▸ A constant is an identifier (name) for a simple value. The
value cannot be changed during the script.
▸ A valid constant name starts with a letter or underscore (no
$ sign before the constant name).
11
INTRODUCTION TO PHP
CONSTANTS EXAMPLE
<?php
define("SOMECONTANT", "burning keyboards”);
echo SOMECONSTANT; // outputs "burning keyboards"
12
INTRODUCTION TO PHP
ARITHMETIC & ASSIGNMENT OPERATORS
<?php
$x = 10;
$y = 5;
echo $x + $y; // outputs 15
echo $x - $y; // outputs 5
echo $x * $y; // outputs 50
echo $x / $y; // outputs 2
echo $x % $y; // outputs 5
echo $x ** $y; // outputs 100000
$x += $y; // equal to $x = $x + $y
$x -= $y; // equal to $x = $x - $y
$x *= $y; // equal to $x = $x * $y
$x /= $y; // equal to $x = $x / $y
$x %= $y; // equal to $x = $x % $y
$x **= $y; // equal to $x = $x ** $y
13
INTRODUCTION TO PHP
COMPARISON OPERATORS
<?php
$x = 10;
$y = 5;
$x == $y; // equal
$x === $y; // identical (equal + same type)
$x != $y; // not equal
$x !== $y; // not identical
$x <> $y; // not equal
$x > $y; // greater than
$x >= $y; // greater than or equal
$x < $y; // less than
$x <= $y; // less than or equal
14
INTRODUCTION TO PHP
INCREMENT / DECREMENT & LOGICAL OPERATORS
<?php
++$x; // Pre-increment - increments $x by one, then returns $x
$x++; // Post-increment - returns $x, then increments $x by one
--$x; // Pre-decrement - decrements $x by one, then returns $x
$x--; // Post-decrement - returns $x, then decrements $x by one
$x && $y; // AND, returns true if both $x and $y are true
$x || $y; // OR, returns true if either $x or $y are true
$x xor $y; // XOR, returns true if either $x or $y is true, but not both
!$x; // NOT, returns true if $x is not true
15
INTRODUCTION TO PHP
STRING OPERATORS
<?php
$str = $str1 . $str2; // concatenation
$str .= $str1; // concatenation assignment, appends $str2 to $str
16
INTRODUCTION TO PHP
CONDITIONALS
<?php
$i = 11;
if ($i < 10) {
echo "Number is smaller than 10!";
} else if ($i < 20) {
echo "Number is smaller than 20!";
} else {
echo "Number is greater or equal to 20!";
}
$favoritecolor = "red";
switch ($favoritecolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
$a = ($b > $c) ? $b : $c;
17
INTRODUCTION TO PHP
LOOPS
<?php
$x = 1;
while ($x <= 5) {
echo "The number is: $x";
$x++;
}
$x = 6;
do {
echo "The number is: $x";
$x++;
} while ($x <= 5); // this evaluates at the end, so it will always print once
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x";
}
$colors = ["red", "green", "blue", "yellow"];
foreach ($colors as $color) {
echo "$color <br>";
}
18
INTRODUCTION TO PHP
FUNCTIONS
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
function writeMsg($msq = "Default one") {
echo "My message: $msg";
}
writeMsg("New message");
19
INTRODUCTION TO PHP
ARRAYS
<?php
$cars = ["BMW", "Mercedes", "Audi"];
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
$cars_length = count($cars);
for ($x = 0; $x < $cars_length; $x++) {
echo $cars[$x];
}
$cars = [
"BMW" => "350d",
"Mercedes" => [
"E" => [220, 250, 300],
"S" => "500"
]
"Audi" => ["A8", "A6", "A4"]
];
echo "I like " . $cars['BMW'] . ".";
foreach ($cars as $key => $value) {
echo "Key: " . $key . ", Value: " . $value;
}
20
INTRODUCTION TO PHP
STRINGS
<?php
echo strlen("Hello world!"); // outputs 12
echo strrev("Hello world!"); // outputs !dlrow olleH
echo strtoupper("Hello world!"); // outputs HELLO WORLD!
echo strpos("Hello world!", "world"); // outputs 6
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
var_dump(str_split("Hello world!")); // outputs ["H", "e", "l", "l", "o", " ", "w",
"o", "r", "l", "d", “!"]
var_dump(explode(" ", "Hello world!")); // outputs ["Hello", "world!"]
echo implode(" ", ["Hello", "world!"]); // outputs Hello world!
$number = 123;
printf("With 2 decimals: %1$.2f, With no decimals: %1$u", $number);
21
INTRODUCTION TO PHP
SUPERGLOBALS
▸ Several predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file
without having to do anything special.
▸ The PHP superglobal variables are:
▸ $GLOBALS
▸ $_SERVER
▸ $_REQUEST
▸ $_POST
▸ $_GET
▸ $_FILES
▸ $_ENV
▸ $_COOKIE
▸ $_SESSION
22
INTRODUCTION TO PHP
DATE & TIME
<?php
echo "Today is " . date("d.m.Y H:i:s");
$d = mktime(11, 14, 54, 7, 5, 2017);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
$d = strtotime("10:30pm July 5 2017");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
$d = strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d);
$d = strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d);
$d = strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d);
$nextWeek = time() + (7 * 24 * 60 * 60); // + 7 days
echo 'Next Week: '. date('Y-m-d', $nextWeek);
23
INTRODUCTION TO PHP
FILE HANDLING
<?php
echo readfile("some.txt");
$file = file_get_contents('some.txt'); // returns string
$homepage = file_get_contents('http://www.google.com/'); // returns string
$lines = file('some.txt');
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . $line . "n";
}
$myfile = fopen("some.txt", "r") or die("Unable to open file!");
echo fread($myfile, filesize("some.txt"));
fclose($myfile);
$myfile = fopen("some.txt", "r") or die("Unable to open file!");
while (!feof($myfile)) {
echo fgets($myfile);
}
fclose($myfile);
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, "First linen");
fwrite($myfile, "Second linen");
fclose($myfile);
24
INTRODUCTION TO PHP
COOKIES
<?php
setcookie("username", "John Doe", time() + (86400 * 30), "/"); // 86400 = 1 day
if (!isset($_COOKIE["username"])) {
echo "Cookie named username is not set!";
} else {
echo "Cookie username is set and has value " . $_COOKIE["username"];
}
// modify cookie
setcookie("username", "Jane Doe", time() + (86400 * 30), "/");
// delete cookie
setcookie("username", "", time() - 3600);
25
INTRODUCTION TO PHP
SESSIONS
<?php
// Start the session
session_start();
// Set session variables
$_SESSION["username"] = "Jon Doe";
echo "Username is " . $_SESSION["username"];
// modify session
$_SESSION["username"] = "Jane Doe";
// delete single session variable
unset($_SESSION["username"]);
// remove all session variables
session_unset();
// destroy the session
session_destroy();
26
INTRODUCTION TO PHP
ERROR HANDLING
<?php
if (!file_exists("welcome.txt")) {
die("File not found");
} else {
$file = fopen(“welcome.txt", "r");
}
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr n";
}
set_error_handler("customError");
$test = 2;
if ($test >= 1) {
trigger_error("Value must be 1 or below");
}
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
27
INTRODUCTION TO PHP
EXCEPTIONS
<?php
function checkNum($number) {
if ($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
} catch (Exception $e) {
echo 'Message: ' .$e->getMessage();
}
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
28
INTRODUCTION TO PHP
INCLUDES
<?php
include 'header.php';
//include will only produce a warning (E_WARNING) and the script will continue
require 'body.php';
// require will produce a fatal error (E_COMPILE_ERROR) and stop the script
require_once 'footer.php';
// the require_once statement is identical to require except PHP will check if the file
has already been included, and if so, not include (require) it again.
29
INTRODUCTION TO PHP
PHP REFERENCES
▸ PHP Manual
▸ http://php.net/manual/en/
▸ Zend PHP 101
▸ https://devzone.zend.com/6/php-101-php-for-the-absolute-
beginner/
▸ PHP The Right Way
▸ http://www.phptherightway.com/
▸ Awesome PHP
▸ https://github.com/ziadoz/awesome-php
30

More Related Content

What's hot

What's hot (20)

PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
PHP
PHPPHP
PHP
 
Php basics
Php basicsPhp basics
Php basics
 
php basics
php basicsphp basics
php basics
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php
PhpPhp
Php
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 

Similar to 07 Introduction to PHP #burningkeyboards

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
Hung-yu Lin
 

Similar to 07 Introduction to PHP #burningkeyboards (20)

Php mysql
Php mysqlPhp mysql
Php mysql
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Php introduction
Php introductionPhp introduction
Php introduction
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 

More from Denis Ristic

18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboards
Denis Ristic
 

More from Denis Ristic (20)

Magento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRMagento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HR
 
Continuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzContinuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVz
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards
 
24 Scrum #burningkeyboards
24 Scrum #burningkeyboards24 Scrum #burningkeyboards
24 Scrum #burningkeyboards
 
23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards
 
19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards
 
18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboards
 
17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards
 
16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards
 
12 Composer #burningkeyboards
12 Composer #burningkeyboards12 Composer #burningkeyboards
12 Composer #burningkeyboards
 
11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

07 Introduction to PHP #burningkeyboards

  • 3. INTRODUCTION TO PHP PHP SYNTAX ▸ A PHP script starts with <?php and ends with ?> (not always) ▸ PHP statements end with a semicolon (;) ▸ Comments in PHP // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ ▸ In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive ▸ However; all variable names ARE case-sensitive. 3
  • 4. INTRODUCTION TO PHP PHP VARIABLES ▸ In PHP, a variable starts with the $ sign, followed by the name of the variable ▸ Rules for PHP variables: ▸ A variable starts with the $ sign, followed by the name of the variable ▸ A variable name must start with a letter or the underscore character ▸ A variable name cannot start with a number ▸ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) ▸ Variable names are case-sensitive ($age and $AGE are two different variables) 4
  • 5. INTRODUCTION TO PHP PHP VARIABLES ▸ PHP is a Loosely Typed Language ▸ The scope of a variable is the part of the script where the variable can be referenced/used. ▸ PHP has three different variable scopes: local, global, static ▸ A variable declared outside a function has a global scope and can only be accessed outside a function ▸ A variable declared within a function has a local scope and can only be accessed within that function ▸ The global keyword is used to access a global variable from within a function ▸ Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. To do this, use the static keyword when you first declare the variable 5
  • 6. INTRODUCTION TO PHP PHP ECHO AND PRINT STATEMENTS ▸ In PHP there are two basic ways to get output: echo and print ▸ echo and print are more or less the same, they are both used to output data to the screen ▸ The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print 6
  • 7. INTRODUCTION TO PHP PHP EXAMPLE <?php echo "Hello World!"; $txt = "Hello world!"; $x = 5; $y = 10.5; echo "I love $txt!"; echo "I love " . $txt . "!"; echo "I love {$txt}!"; echo $x + $y; 7
  • 8. INTRODUCTION TO PHP PHP EXAMPLE <?php function myTest() { $x = 5; // local scope echo "Variable x inside function is: $x"; } myTest(); // using x outside the function will generate an error echo "Variable x outside function is: $x"; $x = 5; $y = 10; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // outputs 15 function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); 8
  • 9. INTRODUCTION TO PHP PHP DATA TYPES ▸ PHP supports the following data types: ▸ String ▸ Integer ▸ Float (floating point numbers - also called double) ▸ Boolean ▸ Array ▸ Object ▸ NULL ▸ Resource 9
  • 10. INTRODUCTION TO PHP DATA TYPES EXAMPLE <?php $x = 'Hello world!'; echo $x; $x = 5985; var_dump($x); $x = 10.365; var_dump($x); $x = true; var_dump($x); $cars = ["Volvo", "BMW", "Toyota"]; var_dump($cars); class Car { public $model; function __construct($model) { $this->model = $model; } } $golf = new Car("WW"); echo $golf->model; $x = null; var_dump($x); 10
  • 11. INTRODUCTION TO PHP PHP CONSTANTS ▸ A constant is an identifier (name) for a simple value. The value cannot be changed during the script. ▸ A valid constant name starts with a letter or underscore (no $ sign before the constant name). 11
  • 12. INTRODUCTION TO PHP CONSTANTS EXAMPLE <?php define("SOMECONTANT", "burning keyboards”); echo SOMECONSTANT; // outputs "burning keyboards" 12
  • 13. INTRODUCTION TO PHP ARITHMETIC & ASSIGNMENT OPERATORS <?php $x = 10; $y = 5; echo $x + $y; // outputs 15 echo $x - $y; // outputs 5 echo $x * $y; // outputs 50 echo $x / $y; // outputs 2 echo $x % $y; // outputs 5 echo $x ** $y; // outputs 100000 $x += $y; // equal to $x = $x + $y $x -= $y; // equal to $x = $x - $y $x *= $y; // equal to $x = $x * $y $x /= $y; // equal to $x = $x / $y $x %= $y; // equal to $x = $x % $y $x **= $y; // equal to $x = $x ** $y 13
  • 14. INTRODUCTION TO PHP COMPARISON OPERATORS <?php $x = 10; $y = 5; $x == $y; // equal $x === $y; // identical (equal + same type) $x != $y; // not equal $x !== $y; // not identical $x <> $y; // not equal $x > $y; // greater than $x >= $y; // greater than or equal $x < $y; // less than $x <= $y; // less than or equal 14
  • 15. INTRODUCTION TO PHP INCREMENT / DECREMENT & LOGICAL OPERATORS <?php ++$x; // Pre-increment - increments $x by one, then returns $x $x++; // Post-increment - returns $x, then increments $x by one --$x; // Pre-decrement - decrements $x by one, then returns $x $x--; // Post-decrement - returns $x, then decrements $x by one $x && $y; // AND, returns true if both $x and $y are true $x || $y; // OR, returns true if either $x or $y are true $x xor $y; // XOR, returns true if either $x or $y is true, but not both !$x; // NOT, returns true if $x is not true 15
  • 16. INTRODUCTION TO PHP STRING OPERATORS <?php $str = $str1 . $str2; // concatenation $str .= $str1; // concatenation assignment, appends $str2 to $str 16
  • 17. INTRODUCTION TO PHP CONDITIONALS <?php $i = 11; if ($i < 10) { echo "Number is smaller than 10!"; } else if ($i < 20) { echo "Number is smaller than 20!"; } else { echo "Number is greater or equal to 20!"; } $favoritecolor = "red"; switch ($favoritecolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } $a = ($b > $c) ? $b : $c; 17
  • 18. INTRODUCTION TO PHP LOOPS <?php $x = 1; while ($x <= 5) { echo "The number is: $x"; $x++; } $x = 6; do { echo "The number is: $x"; $x++; } while ($x <= 5); // this evaluates at the end, so it will always print once for ($x = 0; $x <= 10; $x++) { echo "The number is: $x"; } $colors = ["red", "green", "blue", "yellow"]; foreach ($colors as $color) { echo "$color <br>"; } 18
  • 19. INTRODUCTION TO PHP FUNCTIONS <?php function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function function writeMsg($msq = "Default one") { echo "My message: $msg"; } writeMsg("New message"); 19
  • 20. INTRODUCTION TO PHP ARRAYS <?php $cars = ["BMW", "Mercedes", "Audi"]; echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; $cars_length = count($cars); for ($x = 0; $x < $cars_length; $x++) { echo $cars[$x]; } $cars = [ "BMW" => "350d", "Mercedes" => [ "E" => [220, 250, 300], "S" => "500" ] "Audi" => ["A8", "A6", "A4"] ]; echo "I like " . $cars['BMW'] . "."; foreach ($cars as $key => $value) { echo "Key: " . $key . ", Value: " . $value; } 20
  • 21. INTRODUCTION TO PHP STRINGS <?php echo strlen("Hello world!"); // outputs 12 echo strrev("Hello world!"); // outputs !dlrow olleH echo strtoupper("Hello world!"); // outputs HELLO WORLD! echo strpos("Hello world!", "world"); // outputs 6 echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! var_dump(str_split("Hello world!")); // outputs ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", “!"] var_dump(explode(" ", "Hello world!")); // outputs ["Hello", "world!"] echo implode(" ", ["Hello", "world!"]); // outputs Hello world! $number = 123; printf("With 2 decimals: %1$.2f, With no decimals: %1$u", $number); 21
  • 22. INTRODUCTION TO PHP SUPERGLOBALS ▸ Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. ▸ The PHP superglobal variables are: ▸ $GLOBALS ▸ $_SERVER ▸ $_REQUEST ▸ $_POST ▸ $_GET ▸ $_FILES ▸ $_ENV ▸ $_COOKIE ▸ $_SESSION 22
  • 23. INTRODUCTION TO PHP DATE & TIME <?php echo "Today is " . date("d.m.Y H:i:s"); $d = mktime(11, 14, 54, 7, 5, 2017); echo "Created date is " . date("Y-m-d h:i:sa", $d); $d = strtotime("10:30pm July 5 2017"); echo "Created date is " . date("Y-m-d h:i:sa", $d); $d = strtotime("tomorrow"); echo date("Y-m-d h:i:sa", $d); $d = strtotime("next Saturday"); echo date("Y-m-d h:i:sa", $d); $d = strtotime("+3 Months"); echo date("Y-m-d h:i:sa", $d); $nextWeek = time() + (7 * 24 * 60 * 60); // + 7 days echo 'Next Week: '. date('Y-m-d', $nextWeek); 23
  • 24. INTRODUCTION TO PHP FILE HANDLING <?php echo readfile("some.txt"); $file = file_get_contents('some.txt'); // returns string $homepage = file_get_contents('http://www.google.com/'); // returns string $lines = file('some.txt'); foreach ($lines as $line_num => $line) { echo "Line #{$line_num} : " . $line . "n"; } $myfile = fopen("some.txt", "r") or die("Unable to open file!"); echo fread($myfile, filesize("some.txt")); fclose($myfile); $myfile = fopen("some.txt", "r") or die("Unable to open file!"); while (!feof($myfile)) { echo fgets($myfile); } fclose($myfile); $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); fwrite($myfile, "First linen"); fwrite($myfile, "Second linen"); fclose($myfile); 24
  • 25. INTRODUCTION TO PHP COOKIES <?php setcookie("username", "John Doe", time() + (86400 * 30), "/"); // 86400 = 1 day if (!isset($_COOKIE["username"])) { echo "Cookie named username is not set!"; } else { echo "Cookie username is set and has value " . $_COOKIE["username"]; } // modify cookie setcookie("username", "Jane Doe", time() + (86400 * 30), "/"); // delete cookie setcookie("username", "", time() - 3600); 25
  • 26. INTRODUCTION TO PHP SESSIONS <?php // Start the session session_start(); // Set session variables $_SESSION["username"] = "Jon Doe"; echo "Username is " . $_SESSION["username"]; // modify session $_SESSION["username"] = "Jane Doe"; // delete single session variable unset($_SESSION["username"]); // remove all session variables session_unset(); // destroy the session session_destroy(); 26
  • 27. INTRODUCTION TO PHP ERROR HANDLING <?php if (!file_exists("welcome.txt")) { die("File not found"); } else { $file = fopen(“welcome.txt", "r"); } function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr n"; } set_error_handler("customError"); $test = 2; if ($test >= 1) { trigger_error("Value must be 1 or below"); } error_log("You messed up!", 3, "/var/tmp/my-errors.log"); 27
  • 28. INTRODUCTION TO PHP EXCEPTIONS <?php function checkNum($number) { if ($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } catch (Exception $e) { echo 'Message: ' .$e->getMessage(); } function myException($exception) { echo "<b>Exception:</b> " . $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); 28
  • 29. INTRODUCTION TO PHP INCLUDES <?php include 'header.php'; //include will only produce a warning (E_WARNING) and the script will continue require 'body.php'; // require will produce a fatal error (E_COMPILE_ERROR) and stop the script require_once 'footer.php'; // the require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again. 29
  • 30. INTRODUCTION TO PHP PHP REFERENCES ▸ PHP Manual ▸ http://php.net/manual/en/ ▸ Zend PHP 101 ▸ https://devzone.zend.com/6/php-101-php-for-the-absolute- beginner/ ▸ PHP The Right Way ▸ http://www.phptherightway.com/ ▸ Awesome PHP ▸ https://github.com/ziadoz/awesome-php 30
  • 31. INTRODUCTION TO PHP PHP REFERENCES ▸ PHP Best Practices ▸ https://phpbestpractices.org/ ▸ PHP FIG ▸ http://www.php-fig.org/ ▸ PHP Security ▸ http://phpsecurity.readthedocs.io/en/latest/index.html ▸ The PHP Benchmark ▸ http://phpbench.com/ ▸ PHP Sandbox (Online) ▸ http://sandbox.onlinephpfunctions.com/ 31