PHP tutorial

November 11th, 2019 - Vincent Luciani
The tables below will help you to rehearse PHP's most useful functionalities. Use the quick links below to jump directly to the type of information you are interested in.
Choose a chapter below:

Information about the request

Get parameter from a post call, input name inputname$_POST['inputname']
Get parameter from a get call, input name inputname$_GET['inputname']
Get the server accessed (for example localhost)$_SERVER['SERVER_NAME']
Get the part of the url after the server name$_SERVER['REQUEST_URI']
Get the port$_SERVER['SERVER_PORT']
Get information if https is used$_SERVER['HTTPS'];

Logic

Logical operator not!
Logical operator and&&
Logical operator or||
Get result from listing of a folder in a parameter$myparameter=`ls -la`
check if a parameter is a stringis_string($myparameter)
check if a parameter is nullis_null($myparameter)
check if a parameter is numericis_numeric($myparameter)
check if a parameter is setisset($myparameter)
check if a parameter is not set or emptyempty($myparameter)
Convert to integer$result=intval($inputparameter);
Convert to string$result=strval($inputparameter);
If elseif (condition)
{
...
}
else
{


}
Switchswitch($inputparameter){
case "a" :
...
break;
case "b" :
...
break;
default :
...
break;
}
whilewhile ( conditiontocontinue ){
...
}
for loopfor ( $i=0 ;$i <=$imax ;$i++)
{

}
get out of a loopexit

Deal with files

open a text file to add content at the end$filepointer=fopen("filepath","at");
when opening, symbol to modify from the beginningw
when opening, symbol delete file if existing, otherwise write from the beginningw+
when opening, symbol add content at the end, create file if not existinga+
Write in a fileint fwrite($filepointer,$inputstring,strlen($inputstring));
you get $filepointer from fopen
Close a fileclose($filepointer);
Prevent file lockingflock($filepointer,LOCK_NB);
Lock file for writingflock($filepointer,LOCK_EX);
Lock file for readingflock($filepointer,LOCK_SH);
Unlock fileflock($filepointer,LOCK_UN);
Read file line by line (but don't read more than 999 bytes)while (!feof($filepointer))
{

$line=fgets($filepointer,999);
Read a line but take off all php and html charactersfgetss($filepointer,999,$allowedspecialcharacters);
Read a line from a csv file with tab separatorfgetcsv($filepointer,100,"\t");
Test if file existsfile_exists($filepath)
Get the file sizefilesize($filepath)
Delete a fileunlink($filepath)

Deal with arrays

Initialize an array$myarray=array(value1,...);
Initialize an empty array$myarray=array();
Make an array containing numbers from 1 to 10$mylist=range(1,10);
Access first element of the array and put in a variable$myelement=$myarray[0];
Show the content of the arrayprint_r($myarray);
Use each element of the arrayforeach ( $myarray as $variable )
{
echo $variable;
}
Initialize an array with keys$myarray=array(key1=>value1,key2=>value2,...);
Use each element of the array, get keys and valuesforeach ( $myarray as $key=> $value )
{
echo $key." : ".$value;
}
Initialize an array of arrays$myarray=array ( array (a11,a12), array (a21,a22) );
Sort an arraysort($myarray);
Array with keys and values: sort per keysksort($myarray);
Array with keys and values: sort per valuesasort($myarray);
Inverted sortAdd an r before sort: rsort, krsort, arsort
Custom sort=indicate how I know an element is before anotherfunction mycomparison($x,$y)
{
.... algorithm returning 0, 1 or -1
}

usort($myarray,'mycomparison');
Put a random order in elements of the arrayshuffle($myarray);
Add an element at the end of an arrayarray_push($myarray,$myelement);
Take of the last element of an arrayarray_pop($myarray);
Get the last element of an array and stay on this position$myvalue=end($myarray);
Get the next element in an array and stay on this position$myvalue=next($myarray);
Get the previous element in an array and stay on this position$myvalue=prev($myarray);
Get the first element of an array and stay on this position$myvalue=reset($myarray);
Modify each element of an array using a function multiplying by 3 each element in the arrayfunction mymodificator(&$inputvalue,$mykey,$myvalue)
{
$inputvalue*=$myvalue;
}
array_walk($myarray,'my_modification',3);
Number of elements in an arraycount($myarray) or sizeof($myarray)
Get the list of values with the number of occurence per valuearray_count_values($myarray);

Deal with strings

Take off spaces from a string$result=trim($input);
Convert all returns to
$result=nl2br($input);
Print something in a certain format using a parameterprintf("This is a text : %s",$value);
format: float with 2 digits after decimal point%.2f
format: string of 4 characters, fill-in with x on right if less than 4 characters%'0-4s
format: string of 5 characters%5s
format: integer of 9 digits, fill-in with zeroes on the left%'.09d
format: take second parameter as an integer of 4 digits filled-in with 0 if less%1\$s
Change to upper casestrtoupper($input)
Change to lower casestrtolower($input)
Change first letter to upper caseucfirst($input)
Change first letter of each word to upper caseucwords($input)
Trim and escape special characters addslashes(trim($input))
Convert string to array, using ;as delimiterexplode(';',$input)
Convert back array to string (delimiter ;)implode(';',$myarray)
Take part of a stringsubstr($inputstring,start,[lenght])
From bibula, take bulsubstr("bibula",2,3)
From bibula, take ibulasubstr("bibula",1)
Compare two stringsstrcmp($firstinput,$secondinput)
0 if same
>0 if $firststring>$secondstring
(or if first string is higher in alphabet than second string)
Number returned when comparing a,b-1
Compare, NOT taking into account upper or lower casestrcasecmp()
Get the length of a stringstrlen($inputstring)
Look for string in string$test=strpos($inputstring,$searchedstring);
returns null if not found
Look for string in string, starting from position n$test=strpos($inputstring,$searchedstring,n);
Look for string in string, give last position$test=strrpos($inputstring,$searchedstring);
Replace string1 by string2 inside stringstr_replace($string1,$string2,$string)
Regular expression: 1 or more (not 0)+
Regular expression : 0, 1 or more*
Regular expression: dot\.
Regular expression: any lower case letter or dash[a-z\-]
Regular expression: tabulators and spaces[[:space]]
Regular expression: word\w
Regular expression: number\d
Regular expression: aa or ab or acaa|ab|ac
Regular expression: \\\
Give array of strings matching the expression$result=preg_match($expression,$inputstring,$arrayoffound);
Case insensitive search/i
Declare regular expression$expression='/regularexpression/'
Replacement pattern: second group${2}
Replacement pattern: form a group(group)
Make replacements $result=preg_replace($expression,$replacementpattern,$inputstring);
Separate string in array elements using regular expression
example: separator is @ or .
$array=split("\.|@",$inputstring);
get code from mycode.php without critical include('mycode.php');
get code from mycode.php making sure it is done only onceinclude_once('mycode.php');

Functions and objects

Function: get number of arguments$number=func_num_args();
Function : loop through all arguments$arguments=func_get_args();
foreach ( $arguments as $argument)
{...
Function returning a resultfunction myFunction(){
return $myresult;
}

$result=myFunction();
Class with constructorclass myClass
{
private $objectparam;
function __construct($myparam)
{
$this->$objectparam=$myparam;
}
}
Class with getter and setterclass myClass
{
private $objectparam;
function __construct($myparam)
{
$this->$objectparam=$myparam;
}
function __get($myparam)
{
return $this->$myparam;
}

function __set($myparam,$myvalue)
{
$this->$objectparam=$myvalue*2;
}

function printvalue()
{
echo "value of object param:".$this->$objectparam;
}

}
Get instance of class$myobject=new className();
Call function$myobject->functionName();
Get value of parameter (calling getter)$result=$classpointer->$parametername;
Set value of parameter ( calling setter)$classpointer->$parametername=$value;
Class B is child of Aclass B extends A
Interface definitioninterface myInterface
{
function myFunction();
}
Class implementing the function in interfaceclass myClass implements myInterface
{
function myFunction()
{
...
}
}

Error handling

Catch error try
{
...
}
catch (Throwable $t)
{
.....
}
Get all details about the errorgetMessage — Gets the message
getCode — Gets the exception code
getFile — Gets the file in which the object was created
getLine — Gets the line on which the object was instantiated
getTrace — Gets the stack trace
getTraceAsString — Gets the stack trace as a string
getPrevious — Returns the previous Throwable
__toString — Gets a string representation of the thrown object

PHP and SQL

Connect to an sql database (object oriented)$connectionobject=new mysqli($myhost, $myuser, $mypassword, $mydatabase);
...
$connectionobject->close();
Connection error$connectionobject->connect_errno
Execute a query$resultpointer=$mysqli->query("SELECT * from TEST"));

....
$resultpointer->free();
Get number of rows$resultpointer->num_rows
Get each row in a table in which column names are keysfor ($i=0;$i<$numberofrows;$i++)
{
$currentline=$resultpointer->fetch_assoc();
}
Get an element of the row$currentline['columnname'];
Get each row in a table (without keys)fetch_row()
Query with mask$myquery="insert into mytable values (?,?)";
$myinstruction=$connectionpointer->prepare($myquery);
$myinstruction->bind_param($param1,$param2);
$myinstruction->execute();
... $myinstruction->affected_rows ...
$myinstruction.close();
This website is non commercial and does not register any of your personal data (no cookie, no statistics). The site and its content are delivered on an "as-is" and "as-available basis".
image/svg+xml