PHP: Difference between revisions

From wiki
Jump to navigation Jump to search
 
(13 intermediate revisions by the same user not shown)
Line 4: Line 4:
Script language for dynamic web-pages. The syntax and concepts used are similar to [[Perl]]
Script language for dynamic web-pages. The syntax and concepts used are similar to [[Perl]]


<strong>Limited number of loops:</strong>
;Limited number of loops
<syntaxhighlight lang=php>  
<syntaxhighlight lang=php>  
for ($i = 0; $i <= 6; $i++) {
for ($i = 0; $i <= 6; $i++) {
Line 20: Line 20:


;<nowiki>date("Y-m-d h:i:s")</nowiki>
;<nowiki>date("Y-m-d h:i:s")</nowiki>
:Current timestamp (YYYY-mm-dd HH:MM:SS)
:Current timestamp (YYYY-mm-dd HH:MM:SS).
;sprintf("%7.2f",$float )
:Format "U" is [https://duckduckgo.com/?q=unixtime unixtime] (seconds since epoch)
:Format a number (7 digits, 2 decemals)
;sprintf("%7.2f", $float )
:Format a number (7 digits, 2 decimals)
;number_format($number, 2, '.', ',')
:Format $number with 2 decimals, . as decimal separator and , as thousand separator.


;strpos($string, $search,$start)
;strpos($string, $search,$start)
:Return position of $search exists in $string. When it is not in, return FALSE. Start searching at position $start (optional). Simple test on strpos - <code>if (strpos(x,y)) {}</code> - does not differ between position 0 and FALSE. Test on position 2 or count from the end by setting $start to a negative value (possible since PHP7.1).
:Return position of $search exists in $string. When it is not in, return FALSE. Start searching at position $start (optional). Simple test on strpos - <code>if (strpos(x,y)) {}</code> - does not differ between position 0 and FALSE. Test on position 2 or count from the end by setting $start to a negative value (possible since PHP7.1).
;str_replace($old,$new,$string)
;str_replace($old, $new, $string)
:Return $string with $old replaced by $new
:Return $string with $old replaced by $new
;trim($string, 'abc')
:Remove characters a, b and c from the start and the end of $string. If no characters are specified all whitespace will be removed.


;round($float,<precision>)
;round($float,<precision>)
Line 49: Line 54:
}
}
fclose($fh)
fclose($fh)
</syntaxhighlight>
Read directory
<syntaxhighlight lang=php>
$dir = "./";
// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh))){
      echo "filename:" . $file . "\n";
    }
    closedir($dh);
  }
}
</syntaxhighlight>
</syntaxhighlight>


=Functions=
=Functions=


All variables are local to the function. You have to pass everything it needs.
All variables are local to the function. You have to pass everything it needs, or declare variables as GLOBAL


<syntaxhighlight lang=php>
<syntaxhighlight lang=php>


<?php
function func1($arg1, $arg2)
function func1($arg1, $arg2)
{
{
    GLOBAL $vardeclaredoutside
     <codeblock>
     <codeblock>
     return $value;
     return $value;
}
}
?>
</syntaxhighlight>
 
Only one value can be returned but you can return arrays.
 
<syntaxhighlight lang=php>
 
function func1()
{
    <codeblock>
    return array ($value1, $value2);
}
 
list($val1,$val2) = func1();
</syntaxhighlight>
</syntaxhighlight>


=Arrays=
=Arrays=


;arr1 = ( val1, val2, val3 )
;arr = []
:(Create) empty array
 
;arr1 = [val1, val2, val3]
;arr1 = array(val1, val2, val3)
:Create an indexed array. The keys are the range 0..arraylength.
:Create an indexed array. The keys are the range 0..arraylength.
;array_push($arr1,val1,val2)
:Add elements val1 and val2 to the end of $arr1


;$arr1 = array(key1=>val1, key2=>val2, key3=>val3)
;$arr1 = array(key1=>val1, key2=>val2, key3=>val3)
;$arr2[key1] = val1
;$arr2[key1] = val1
:Create an associative array (like a hash in perl)
:Create an associative array (like a [[Perl#Hashes]] or a [[Python:DataTypes#Dictionary_or_dict|Python dictionay]])


;count(arr1)
;count($arr1)
:Return the number of elements (length) of an array
:Return the number of elements (length) of an array
;end($arr1)
:Return the value of the last element in $arr1 and set the pointer to it.
;join(',',$arr1)
:Join elements in arr1 with ',' as separator.


;foreach($arr1 as $value) { codeblock }
;foreach($arr1 as $value) { codeblock }
Line 83: Line 128:
;foreach($arr1 as $key => $value) { codeblock }
;foreach($arr1 as $key => $value) { codeblock }
:Loop over an associative array
:Loop over an associative array
;unset($arr1[key])
:Remove the key element from $array. Numerical keys will not be reindexed.


=Install=
=Install=
Line 91: Line 139:
:Uncomment line with cgi.fix_pathinfo and set it to 0
:Uncomment line with cgi.fix_pathinfo and set it to 0


==php7.4 not in repository==
==php repository==
<syntaxhighlight lang=bash>
<syntaxhighlight lang=bash>
apt -y install lsb-release apt-transport-https ca-certificates
apt -y install lsb-release apt-transport-https ca-certificates
Line 100: Line 148:
php -v
php -v
</syntaxhighlight>
</syntaxhighlight>
==Upgrade==
Nice overview of how to upgrade can be found on [https://php.watch/articles/php-8-5-installation-upgrade-guide-debian-ubuntu php-watch]
Installing multiple package can easily be done like <code>install php8.3-{fpm,curl,mbstring,mysql,xml}</code>

Latest revision as of 13:59, 25 September 2026

Basics

Script language for dynamic web-pages. The syntax and concepts used are similar to Perl

Limited number of loops
 
for ($i = 0; $i <= 6; $i++) {
  echo "Loop number: $i ";
}
escapeshellcmd(shellcommand)
Return the shellcommand with everything that might confuse the shell escaped.
exec(<cmd>,<outputarray>,<returnvar>)
Executed <cmd> in the shell, append the command output to he array <outputarray> and set <returnvar> to the returnvalue of the command.
Also the last line of the command output is returned
shell_exec(<cmd>)
Execute <cmd> (output from excapedshellcmd) in the shell, return the command output.
date("Y-m-d h:i:s")
Current timestamp (YYYY-mm-dd HH:MM:SS).
Format "U" is unixtime (seconds since epoch)
sprintf("%7.2f", $float )
Format a number (7 digits, 2 decimals)
number_format($number, 2, '.', ',')
Format $number with 2 decimals, . as decimal separator and , as thousand separator.
strpos($string, $search,$start)
Return position of $search exists in $string. When it is not in, return FALSE. Start searching at position $start (optional). Simple test on strpos - if (strpos(x,y)) {} - does not differ between position 0 and FALSE. Test on position 2 or count from the end by setting $start to a negative value (possible since PHP7.1).
str_replace($old, $new, $string)
Return $string with $old replaced by $new
trim($string, 'abc')
Remove characters a, b and c from the start and the end of $string. If no characters are specified all whitespace will be removed.
round($float,<precision>)
Round $float to <precision> decimals (0 is default)

Regular expressions

PHP is Perl-like, patterns need delimiters (default is /<pattern>/ )

preg_match($pattern, $string)
Return 1 if $pattern exists in $string
preg_split('/\s*\=+\s*/',$string
Split $string into an array on a pattern (in this example on white-spaces and equality signs.
preg_replace('/#.*$/',,$string);
Replace matches with the pattern in $string (in this example to remove comments from a line)

Files

Almost all you need to know about files. For writing open with 'w' and fwrite($fh,$line)

$fh = fopen($filename, 'r') or die('Unable to open '.$file);
while(!feof($fh)) {
  $line =  fgets($fh);
}
fclose($fh)

Read directory

$dir = "./";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh))){
      echo "filename:" . $file . "\n";
    }
    closedir($dh);
  }
}

Functions

All variables are local to the function. You have to pass everything it needs, or declare variables as GLOBAL

function func1($arg1, $arg2)
{
    GLOBAL $vardeclaredoutside
    <codeblock>
    return $value;
}

Only one value can be returned but you can return arrays.

function func1()
{
    <codeblock>
    return array ($value1, $value2);
}

list($val1,$val2) = func1();

Arrays

arr = []
(Create) empty array
arr1 = [val1, val2, val3]
arr1 = array(val1, val2, val3)
Create an indexed array. The keys are the range 0..arraylength.
array_push($arr1,val1,val2)
Add elements val1 and val2 to the end of $arr1
$arr1 = array(key1=>val1, key2=>val2, key3=>val3)
$arr2[key1] = val1
Create an associative array (like a Perl#Hashes or a Python dictionay)
count($arr1)
Return the number of elements (length) of an array
end($arr1)
Return the value of the last element in $arr1 and set the pointer to it.
join(',',$arr1)
Join elements in arr1 with ',' as separator.
foreach($arr1 as $value) { codeblock }
Loop over an indexed array
foreach($arr1 as $key => $value) { codeblock }
Loop over an associative array
unset($arr1[key])
Remove the key element from $array. Numerical keys will not be reindexed.

Install

On debian (and its derivates)

apt-get install php-fpm php-mysql
Install php7 and mysql support
Fix php security by editing /etc/php/7.0/fpm/php.ini
Uncomment line with cgi.fix_pathinfo and set it to 0

php repository

apt -y install lsb-release apt-transport-https ca-certificates
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
sudo apt update
sudo apt -y install php7.4
php -v

Upgrade

Nice overview of how to upgrade can be found on php-watch

Installing multiple package can easily be done like install php8.3-{fpm,curl,mbstring,mysql,xml}