Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

PHP

Download progam
1 - Download xampp
2 – start Apache
3 – go to path ‘ C/xampp/htdocs’
4 – create folder ex (test)
5 – create file ex (test.php)
6 – open browser
7 – go to ‘ localhost/test/test.php
outline
• Data Types & variables .
• constants .
• echo .
• operators .
• if and else .
• switch .
• loops .
• functions .
• Arrays .
• super global .
• File read/write.
• File Download.
• File Upload.
• Include and Required.
• Sessions.
• Cookies.
• Filters.
• Exception Handling.
• Form Handling and Validation.
• Class / object.
• Constructor.
• Constant.
• Access modifier .
• Inheritance.
• Abstraction.
• Interface.
• Overloading.
• Final .
• Static .
• connect Data Base .
Data Types & Variables

Data Types Variables


• String • $string = “hollow world" ;
• Integer • $integer = 20 ;
• Float • $float = 1.5 ;
• Boolean • $checkBool = true ;
• Array • $numbers = [ 1 , 2 , 3 ]
• Object • $object=new object () ;
• NULL • $empty = NULL ;
Constants
define(name, value, case-insensitive)
• Example :
1 - define(CONSTANT, 15 , true)
Can use constant or CONSTANT
2 – define(CONSTANT , 15 , false)
Can use CONSTANT only
• Case-insensitive meaning :
• true : No care name in uppercase or lowercase
• false : Name must be same to Name
echo
• echo "<H1>Welcome</H1>" ;
• echo "Hollow world" ;
• echo 20 ;
• echo true ;
• echo $myName ;
• echo “hollow” , “ “ , “world”;
Operators
• Arithmetic operators
( + , - , * , / , % , ** )
• Assignment operators
( = , += , -= , *= , /= , %= )
• Comparison operators
( == , != , <> , === , !== , < , > , <= , >= )
• Increment / Decrement operators
( ++$var , $var++ , --$var , $var-- )
• Logical operators
( and , && , or ,|| , ! )
• String operators
( . , .=)
Arithmetic
• 15 + 10 = 25
• 15 – 10 = 5
• 3 * 2 =6
• 10 / 5 = 2
• 10 % 3 = 1
• 3 ** 2 = 9
Assignment

• $var = 5
• $var += 5 $var = $var + 5 $var
= 10
• $var -= 5 $var = $var - 5 $var
= 0
• $var *= 5 $var = $var * 5 $var
= 25
• $var /= 5 $var = $var / 5 $var
= 1
Comparison
5 == 5 5===“5”
true false
5 ==“5“ 5 >= 10
true false
5 != 10 10 > 5
true true
5 <> 5 “ali” < “moahmed”
false true
Inc and Dec
• $var = 5 ;
echo $var++ ;
echo $var ;
• $var = 8 ;
echo ++$var;
echo $var;
• $var =10 ;
echo $var --;
Logical
• and | &&
all conditions true
• or | ||
at least one true
• !
! (true)  false
! (false)  true
String
• .  concatenation
$string= “ali” . “ “ .”moahmed” ;
“ali mohamed”
• .=
$string= “hollow”;
$string .= “ ll “;
$string .=“world”;
or
$string .=“ ll “ . “world”;
“hollow ll world”
Let’s Try
if..else
if ($grade < 50){
echo "F" ;
} elseif ($grade <60){
echo "D" ;
} elseif ($grade <70){
echo "C" ;
} elseif ($grade <80){
echo "B" ;
} else {
echo "A" ;
}
if..else (cont.)
if ($grade < 70){
echo "C" ;
} elseif ($grade <60){
echo "D" ;
} elseif ($grade <50){
echo “D" ;
} elseif ($grade <80){
echo "B" ;
} else {
echo "A" ;
}
switch
switch ($character){
case "A" :
echo "The Character is A ";
break;
case "B" :
echo "The Character is B ";
break;
case "C" :
echo "The Character is C ";
break;
default :
echo "The Character is unknown " ;
break;
}
Loops
• for loop :
for(Initialize ; Condition ; Increment )
{
code ;
}
• Example :
for ($i=0 ; $i<10 ; $i++)
{
echo $i ;
}
Loops(Cont.)
• while loop :
Initialize;
while(Condition)
{
code ;
Increment;
}
Functions
• Function without arguments :
function functionName(){
code ;
}
Example
function printMessage ()
{
echo “message”;
}
Functions(Cont.)
• Function with arguments :
function functionName($arg1 , $arg2){
code ;
}
Example
function factorial($number)
{
$result=1;
for ( $i =1 ; $i <=$number ; $i++)
{
$result *= $i;
}
return $result ;
}
Arrays
• Indexed Arrays :
$arrayName = array(val1 ,val2 ,val3);
Or
$arrayName = [val1 ,val2 ,val3];
0 1 2
$arrayName [ index ];
Arrays(Cont.)
Arrays(Cont.)
• Associative Arrays :
$arrayName = array(key1 => val1,key2 => val2,key3 => val3);
foreach
superglopals
• $GLOBALS
$x = 75;
$y = 25;

function addGlobals() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
Superglopals (cont.)
• $_SERVER
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI) the
server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3schools.com)

$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as
HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as


1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request


$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request (such as
utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because
not all user-agents support it)
Superglopals (cont.)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the
current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the
current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script

$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in the


web server configuration file (if your script runs on a virtual host,
it will be the value defined for that virtual host) (such as
someone@w3schools.com)
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web
server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are
added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
Superglopals (cont.)
• $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML
form.
Superglopals (cont.)
• $_POST
PHP $_POST is widely used to collect form data after submitting an
HTML form with method="post“
Superglopals (cont.)
• $_GET
PHP $_GET can also be used to collect form data after submitting an
HTML form with method="get“
File open/close
fopen (file path , mode)
fclose(Resource) call after read and write
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist.
File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
File read
• fread(Resource , number of bytes).

• fgets (Resource) read single line.

• feof(Resource) return true if end of file has been


reached.
File write
• fwrite(Resource ,string).
File Download
• File_exists(filepath)
Check file exist or not.
• Mime_content_type(filepath)
Return type of file.
• Basename(filepath)
Return file name
Example :
File path is C/XAMPP/file.txt
Return file.txt
• Isset(var)
Check var exist or not.
File Download (cont.)

File Upload

Include and required
• include (file name) ;
• require (file name);
takes all the text/code/markup that exists in the specified
file and copies it into the file that uses the include
statement.
Include when a file is included with
the include statement and PHP cannot find it, the script
will continue to execute (warning) but Require
Product fatal error and stop the script.
• Include_once (file name) ;
• Require_once (file name);
Include file Once
Include and required (cont.)
In temp file (temp.php) output

In basis file (basis.php)


Include and required (cont.)
In temp file (temp.php) output

In basis file (basis.php)


Session
A session is a way to store information (in variables) to be used
across multiple pages.
session_start()
Session variables are set with the PHP global variable: $_SESSION.
In file (Basis.php) in file
(temp.php)

Note: The session_start() function must be the very first thing


in your document. Before any HTML tags.
Session (cont.)
To remove all global session variables and destroy the
session, use session_unset() and session_destroy():
• session_unset() : remove all session variables
• session_destroy(): destroy the session
Cookies
A cookies is used to identify a user .
• To set cookies use function setcookie()
setcookie(name, value, expire, path, domain, secure, httponly);
• To set cookies :

• To remove cookies :
Filters
• Filter id from 257 to 275 return Boolean.
• Filter id from 513 to 521 return value.

Result is not valid .

Result is 155 .
Exception handling
Try and Catch
Used to change the normal flow of the code execution
if a specified error condition occurs .
Form handling
trim — Strip whitespace (or other characters) from the
beginning and end of a string
Form handling
Form handling
class and object
class className
{
attributes .

functions .
}
class Foo
{
public $id = 15 ;
public $name = ‘Ayman‘ ;

function aMemberFunc()
{
print ‘my name is ‘ . $this -> name ;
}
}
$foo = new Foo();
$foo -> amemberFunc(); // prints my name is Ayman
constructor
class Foo
{
public $id ;
public $name ;

function __construct() // magic function


{
$this -> name = ‘Ayman’ ;
$this -> id = 15 ;
}
}
$foo = new Foo();
constant
class Myclass
{
const CONSTANT ;

function showConstant()
{
echo self::CONSTANT ;
}
}

$ob = new Myclass();


echo $ob -> showConstant() ;
or
echo Myclass :: CONSTANT ;
access modifier
• members declared public can be
accessed everywhere .
• Members declared protected can be
accessed only within the class itself and
by inheriting and parent classes.
• Members declared as private may only
be accessed by the class that defines
the member.
access modifier (cont.)
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj = new MyClass();


echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
access modifier and
inheritance (cont.)
class MyClass2 extends Myclass
{

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj = new MyClass();


echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Undefined
$obj->printHello(); // Shows Public, Protected and Undefined
Abstraction
Classes defined as abstract may not be instantiated
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}

class ConcreteClass1 extends AbstractClass


{
protected function getValue() {
return "ConcreteClass1";
}

public function prefixValue($prefix) {


return "{$prefix}ConcreteClass1";
}
}
interface
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
class Template implements iTemplate
{
private $vars = array();

public function setVariable ( $name, $var)


{
$this->vars[$name] = $var;
}

public function getHtml($template)


{
foreach($this->vars as $name => $value) {
$template = str_replace( '{' . $name . '}‘ , $value, $template);
}

return $template;
}
}
overloading
__call is triggered when invoking inaccessible methods in an object context.
__callStatic() is triggered when invoking inaccessible methods in a static context.
class MethodTest{
public function __call($name, $arguments){
if ($name== "sum“ ){
if (count($arguments)==2){
return $arguments[0]+$arguments[1];
}
else {
return $arguments[0]+$arguments[1]+$arguments[2];
}
}}
public function send() {
echo "string";
}}
$ob = new MethodTest();
echo $ob->sum(1,2,3);
echo $ob->sum(1,2);
$ob->send();
Final
Note for Java developers: the 'final' keyword is not used for class constants in PHP.
We use the keyword 'const'.

//Final methods example


class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called\n";
}
}

class ChildClass extends BaseClass {


public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
Final (cont.)
//Final class example
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called\n";
}
}

class ChildClass extends BaseClass {


}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
Static
class A {
protected static $a;

public static function init($value) { self:: $a = $value; }


public static function getA() { return self:: $a; }
}

class B extends A {
protected static $a; // redefine $a for own use

// inherit the init() method


public static function getA() { return self:: $a; }
}

B::init('lala');
echo 'A::$a = '. A::getA() .'; B::$a = '.B::getA();

This will output:


A::$a = lala; B::$a =
Connect MYSQLi
If don’t have Data Base .
Connect MYSQLi (cont.)
If have Data Base .
Create DB MYSQLi
I have object of mysqli called $conn .
Create Table MYSQLi
I have object of mysqli called $conn .
Insert Data MYSQLi
I have object of mysqli called $conn .
Insert Data MYSQLi (cont.)
I have object of mysqli called $conn .
Get id inserted .
Select Data MYSQLi
I have object of mysqli called $conn .
Update Data MYSQLi
I have object of mysqli called $conn .
Prepared Statements MYSQLi
• bind_param : Binds variables to a prepared statement as
parameters .
• prepare : Prepare an SQL statement for execution .
Prepared Statements MYSQLi
(cont.)
I have object of mysqli called $conn .
Prepared Statements MYSQLi
(cont.)
I have object of mysqli called $conn .
THANKS

You might also like