0% found this document useful (0 votes)
52 views

To PHP: #Burningkeyboards

This document provides an introduction to PHP including PHP syntax, variables, data types, operators, conditional statements, loops, functions, arrays, strings and more. It explains PHP concepts like variables, constants, echo/print statements, variable scopes, and built-in functions. Code examples are provided throughout to demonstrate different PHP features. The document aims to give readers an overview of the core components of PHP.

Uploaded by

addssdfa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

To PHP: #Burningkeyboards

This document provides an introduction to PHP including PHP syntax, variables, data types, operators, conditional statements, loops, functions, arrays, strings and more. It explains PHP concepts like variables, constants, echo/print statements, variable scopes, and built-in functions. Code examples are provided throughout to demonstrate different PHP features. The document aims to give readers an overview of the core components of PHP.

Uploaded by

addssdfa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

#burningkeyboards

@denis_ristic

INTRODUCTION
TO PHP
INTRODUCTION TO PHP 2

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.


INTRODUCTION TO PHP 3

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 _ )
INTRODUCTION TO PHP 4

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
INTRODUCTION TO PHP 5

PHPECHO 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
INTRODUCTION TO PHP 6

PHP
E XA
<?php
MPLE
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;
INTRODUCTION TO PHP 7

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();
INTRODUCTION TO PHP 8

PHP DATA
TYPES
▸ PHP supports the following data types:

▸ String

▸ Integer

▸ Float (floating point numbers - also called double)

▸ Boolean

▸ Array

▸ Object
INTRODUCTION TO PHP 9

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);
INTRODUCTION TO PHP 1
0

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).
INTRODUCTION TO PHP 1
1

CONSTANTS
EXAMPLE
<?php

define("SOMECONTANT", "burning keyboards”);

echo SOMECONSTANT; // outputs "burning keyboards"


INTRODUCTION TO PHP 1
2

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
INTRODUCTION TO PHP 1
3

COMPARSI ON
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
INTRODUCTION TO PHP 1
4

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
INTRODUCTION TO PHP 1
5

STRING
OPERATORS
<?php

$str = $str1 . $str2; // concatenation


$str .= $str1; // concatenation assignment, appends $str2 to $str
INTRODUCTION TO PHP 1
6

CONDITIONAL
S
<?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;
INTRODUCTION TO PHP 1
7

LOOP
S
<?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>";
}
INTRODUCTION TO PHP 1
8

FUNCTION
S
<?php

function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function

function writeMsg($msq = "Default one") {


echo "My message: $msg";
}
writeMsg("New message");
INTRODUCTION TO PHP 1
9

ARRA
YS
<?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;
}
INTRODUCTION TO PHP 2
0

STRING
S
<?php

echo strlen("Hello world!"); // outputs 12


echo strrev("Hello world!");// outputs !dlrow olleH
echo strtoupper("Hello world!");// outputs HELLOWORLD!
echostrpos("Hello world!", "world"); //outputs6
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);
INTRODUCTION TO PHP 2
1

SUPERGLOBAL
S
▸ 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
INTRODUCTION TO PHP 2
2

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);
INTRODUCTION TO PHP 2
3

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 line\n");
fwrite($myfile, "Second line\n");
fclose($myfile);
INTRODUCTION TO PHP 2
4

COOKE
I
S
<?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);
INTRODUCTION TO PHP 2
5

SESSION
S
<?php
// Start the
session
session_start();

// Set session
variables
$_SESSION["username"
]

"Jon

Doe";

echo "Username is "


.
$_SESSION["username"
];

// modify session
$_SESSION["username"
]
INTRODUCTION TO PHP 2
6

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");


INTRODUCTION TO PHP 2
7

EXCEPTION
S
<?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(
);
}
INTRODUCTION TO PHP 2
8

INCLUDE
S
<?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 identicalto require exceptPHPwill check if the
file has already been included, and if so, not include(require)it again.
INTRODUCTION TO PHP 2
9

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/
INTRODUCTION TO PHP 3
0

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/

You might also like