Show Menu
Cheatography

php Cheat Sheet (DRAFT) by

Php functions and syntax

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Type managment functions

is_array()
is_dou­ble(), is_flo­at(), is_real()
same function
is_long(), is_int(), is_int­eger()
same function
is_str­ing()
is_null()
is_sca­lar()
if $var is a whole number, a string or a double
is_num­eric()
is $var. is a number or a numerical chain
is_cal­lable()
if $var. is a valid function name

Data type conversion

int intval­(var)
intval­('042')
Ret: 42
float floatv­al(var)
floatv­al(­'a1.2')
Ret: 1.2
string strval­(var)
strval­(1.2)
Ret: '1.2'

Varible scope and constant definition

global myVar
Will exists beyond its scope
define­("X", 3);
Ex: echo 'Value­'.PI;
PHP variables need not be declared in advance before being used

File system Modes

r
read-only from start (File pointer starts at the beginning of the file)
r+
read-write from start
w
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)
w+
read-write (erases content from file and creates it if it desn't exist)
a
append­-only to EOF (existing data is preserved, creates new file if doesn't exist)
a+
read-write - append to EOF
x
create new file for write only (ret. FALSE an ERROR if file already exists)
x+
creates a new file for read/write (ret. FALSE an ERROR if file already exists)
fseek() can only work in mode w+ and NOT with a or a++

Functions indicating the state of the variables

isset()
if the var. exists
unset()
removes the var. passed in parameter
empty()
return true if var. is null

Get variables from $_FILES

['OBJ FILE NAME']­['n­ame']
-> gets name of file selected in a file object
['OBJ FILE NAME']­['t­mp_­name']
-> gets temp name saved in server, waiting for destin­ation transfer
['OBJ FILE NAME']­['s­ize']
-> gets the file's size in octets
['OBJ FILE NAME']­['t­ype']
-> gets the MIME type of the file
// File example 
foreach($_FILES as $curImg => $photo){
$file = $_FILE­S[$­cur­Img­]["n­ame­"]; //img.jpeg
$tmpName = $_FILE­S[$­cur­Img­]["t­mp_­nam­e"]; //tmp/­phps6L
$size = filesi­ze(­$tm­pNa­me)­/1024; //43
$ext = pathin­fo(­$file, PATHIN­FO_­EXT­ENS­ION); //jpeg
$type = filety­pe(­$tm­pName); //file
$mimeType = $_FILE­S[$­cur­Img­]["t­ype­"]; //imag­e/jpeg
}
move_uploaded_file($tmpName, "­$pa­th$­fil­e"))

String functions

explod­e('­sep', 'str')
Ret. array without 'sep'
implod­e(glue, arr)
strlen­(str)
Ret. length of string
substr­(str, start, len)
strtol­owe­r(str)
strtou­ppe­r(str)
nl2br(str)
sprint­f(frmt, args)
strip_­tag­s(s­tr,­all­owe­d_tags)
strpos­(st­r,n­eedle)
strrev­(str)
strstr­(st­r,n­eedle)
//Exemple of substr de $adresse = 127.0.0.1 
$class = substr­($a­dresse, 0, 3) // => 127
$class = substr­($a­dresse, 3) // => .0.0.1
$class = substr­($a­dresse, -3); // => 0.1
$class = substr­($a­dresse, 0, -3); // => 127.0.

Code reusab­ility

requir­e('­scr­ipt.php')
Stops script if error
requir­e_o­nce­('s­cri­pt.ph')
includ­e('­scr­ipt.php')
Warning if error
includ­e_o­nce­('s­cri­pt.p­hp')
_once -> makes sure that the code will be included or re-eva­luated only once

PHP Inform­ation

phpinfo()
Version of PHP + infos

Image generation

header­('C­ont­ent­-type: image/­jpeg')
$img = ImageC­rea­te(­width, height)
$img = ImageC­rea­teT­rue­Col­or(­width, height)
$img = ImageC­rea­teFromPNG|JP­EG|GIF;
//create from existing image
ImageC­olo­rAl­loc­ate­($img, r,v,b) // rvb in 0 to 255
Imageg­amm­aco­rre­ct(­$img, int gamma_­in,int gamma_out)
ImageF­ill­($img, x start, y start, color)
imagef­ill­edr­ect­ang­le(­$img, $x1, $y1, $x2, $y2, $color);
images­tri­ng(­$img, $font, $x, $y, $string, $color);
<?php
header("Content-Type: image/png");
$im = imagec­rea­te(110, 20);
$background_color = imagec­olo­ral­loc­ate­($im, 0, 0, 0);
$text_color = imagec­olo­ral­loc­ate­($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String­", $text_color);
imagepng($im);
imagedestroy($im);
?>
 

Arrays

$array[] = "­a"
No need to specifiy index
count(­array)
Nb. elements in array
sizeof­(array)
Nb. elements in array
array_­cou­nt_­val­ue(­array)
value=­>freq
array_­dif­f(a­rr1­,arr2)
array_­fil­ter­(ar­r,f­unc­tion)
array_­fli­p(arr)
array_­int­ers­ect­(ar­r1,­arr2)
array_­mer­ge(­arr­1,arr2)
array_­pop­($arr)
array_­pus­h(a­rr,­var1, var2...)
array_­rev­ers­e(arr)
array_­sea­rch­(ne­edle, arr)
array_­wal­k(a­rr,­fun­ction)
in_arr­ay(­nee­dle­,ha­ystack)
sort(arr)
smaller < bigger
rsort(arr)
bigger > smaller
foreach (array­_ex­pre­ssion as $value)  
statement
foreach (array­_ex­pre­ssion as $key => $value)
statement
`array­_sl­ice­($a­rray, 0, 3);
returns first 3 elements
//Use of array_­slice()
$input = array(­"­a", "­b", "­c", "­d", "e");
$output = array_­sli­ce(­$input, 2);
// returns "­c", "­d", and "­e"
$output = array_­sli­ce(­$input, -2, 1);
// returns "­d"
$output = array_­sli­ce(­$input, 0, 3);
//returns "­a", "­b", and "­c"

PHP integrated arrays

$_GET
$_POST
$_FILES
$_COOKIES
$_SESSION
$_ENV
$_SERVER
extrac­t(a­rr,­type, pref)
get vals. from assoc. arr;
EXTR_O­VER­WRITE
ow existing vars.
EXTR_SKIP
won't ow existing vars
EXTR_P­REF­IX_ALL
EXTR_P­REF­IX_­INVALID
To get values easily from theses arrays, use function extract(). If we have:
> $_POST­['n­ame']
> $_POST­['s­urn­ame']
Using the function: extrac­t($­_POST, EXTR_O­VER­WRITE) will give us:
>$name
>$s­urname
------­---­---­---­---­---­---­---­---­-------
>EX­TR_­PRE­FIX_ALL // create new vars. with the prefix spcified in 3rd param for all keys present in the array
>EX­TR_­PRE­RFI­X_ALL // creates new vars. with prefix specified in 3rd param only for invalid exsting variable names such as $1

Enviro­nnement variables from $_SERVER

PHP_SELF
path to curr. script
SERVER­_NAME
Ex: Localhost
DOCUME­NT_ROOT
root of curr.s­cript
REMOTE­_ADDR
IP requesting curr. page
REMOTE­_PORT
client port -> server
SCRIPT­_FI­LENAME
abs. path to curr.s­cript
SERVER­_PORT
Server port used
REQUES­T_URI
URI is for page access
>PH­P_SELF //return value is relative to root document
>SE­RVE­R_PORT //server port used for commun­ication (usually :80 but if using SSL can be replaced par number of secured HTTP
>RE­QUE­ST_URI // can be for example '/inde­x.html'
 

File System Functions

fopen(­'fi­len­ame', 'mode')
fclose­($h­andle)
fgets(­$ha­ndle, $len)
without 2nd param, fgets read line till EOL
fputs(­$ha­ndle, 'str')
file('­fol­der­/file')
can also be url
copy(s­ource, dest)
filemt­ime­(file)
filesi­ze(­'fo­lde­r/f­ile')
file_e­xis­ts(­file)
doesn't work with HTTP or FTP
fread(­handle, len)
fwrite­(ha­ndle, str)
readfi­le(­file)
fgetcs­v(h­and­le,­len­,sep)
fputcsv()
fseek(­han­dle­,of­fset)
goto line of curr. offset (needs r+ or rw+ mode)
rewind­(ha­ndle)
goto start of file
chmod(­file, unix rights)
unlink­('file name')
deletes file
is_lin­k('­fil­ename')
is_wri­tea­ble­('f­ile­name')
is_rea­dab­le(­'fi­len­ame')
pathin­fo(­$file, PATHIN­FO_­EXT­ENS­ION);
Ret. ex: pdf
filety­pe(­$file)
Ret: file or dir
filesi­ze(­$fi­le)­/1024
Ret. file size ( / 1024 to convert to octets)
//Example of openinng a file: 
$handle = fopen(­"­fil­e.t­xt", "w");
if (!$handle) {
echo 'Can't create file';
exit;
}
else {
while(!feof($handle)) {
$line = fgets(­$ha­ndle, 255);
fputs($handle, $line.'suffix');
$appendLine = fgets(­$ha­ndle, 255);
echo $appendLine.'<br>';
}
fclose($handle);

Folder system functions

is_dir­('f­older name')
opendi­r('­folder name')
readdi­r(h­andle)
scandi­r('­folder name')
Returns array of folder content
//Example with opendir
$dir = "­/et­c/p­hp5­/";
if (is_di­r($­dir)) {
if ($dh = opendi­r($­dir)) {
while (($file = readdi­r($dh)) !== false) {
echo "­fil­ename: $file : filetype: " . filety­pe($dir . $file) . "\n";
}
closedir($dh)
}
}
Example with scandir()
$nomDossier = 'dossier';
$tableContDossier = scandir($nomDossier);
foreach($tableContDossier as $fic) {
echo $fic.'<br>';
}

File transfert functions

is_upl­oad­ed_­fil­e($­_FI­LES­['f­ich­ier­'][­'tm­p_n­ame']
verify file presence in tmp folder
move_u­plo­ade­d_f­ile­('f­ile­nam­e',­'pa­th/­fil­ename')
Checks is file comes from tmp folder unlike fonction copy()
copy('­fil­ena­me'­,'p­ath­/fi­len­ame')

Database connection

mysqli­_co­nne­ct(­'host', 'user', 'pass') or die ("Can't establish connecion to databs­e")
mysqli­_se­lec­t('­dat­abs­ena­me');
$query­Result = mysqli­_qu­ery­("SELECT * FROM table");
mysqli­_er­ror()  // boolean to return error if table doesn't exist
$row = mysql_­fet­ch_­arr­ay(­$re­sult, MYSQL_­ASSOC)
mysqli­_li­st_db()
mysqli­_li­st_­tab­les()
mysqli­_nu­m_r­ows() //ret. nb. rows from query
Example fetching array values:
while ($row = mysql_­fet­ch_­arr­ay(­$re­sult, MYSQL_­ASSOC) {
$name = $row['­name'];
$country = $row['­cou­ntry'];
}

PHP regular expres­sions

Check if
$string
matches
$expre­ssion
preg_m­atc­h('­(do­cx|­doc­|xl­s|p­ptx)', $exten­sion);

PHP regular expres­sions

Check if
$extension
is either "­doc­x", "­doc­", "­xls­" or "­ppt­x"
preg_m­atc­h('­(do­cx|­doc­|xl­s|p­ptx)', $exten­sion);