PHP: Difference between revisions
Jump to navigation
Jump to search
(Created page with "== References == TBC") |
|||
(26 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
== References == |
== References == |
||
* [http://php.net/manual/en/langref.php Language reference on php.net] |
|||
TBC |
|||
* [http://www.w3schools.com/php/default.asp php tutorial on w3schools.com] (check the menu on the left) |
|||
:* [http://www.w3schools.com/php/php_ref_string.asp string functions] |
|||
Cheat sheets: |
|||
* [https://dzone.com/refcardz/php-54-scalable php DZone cheat sheet] |
|||
* [http://files.cnblogs.com/files/E-WALKER/PhpQuickRef.pdf php Quick Reference] |
|||
== Install == |
|||
=== On Windows === |
|||
Download the zip archive on http://windows.php.net/download/: |
|||
* [http://windows.php.net/downloads/releases/php-5.6.30-nts-Win32-VC11-x86.zip PHP 5.6.30 32-bit - Non Thread Safe] (faster). |
|||
; To install |
|||
* Create a directory {{file|C:\php}} and unzip archive inside. |
|||
* Add {{file|C:\php}} to system environment path <code>PATH</code>. |
|||
* Copy {{file|C:\php\php.ini-production}} to {{file|C:\php.ini}}. |
|||
: Alternatively use the development version for more debug. But production ini is handy to mute deprecated API warnings |
|||
; Enable a few extensions |
|||
* To use '''HTTPS''' or '''SSL''', uncomment the line: |
|||
<source lang="text"> |
|||
extension=php_openssl.dll |
|||
</source> |
|||
* To use '''SOAP''', uncomment the line: |
|||
<source lang="text"> |
|||
extension=php_soap.dll |
|||
</source> |
|||
* To use '''Curl''', uncomment the line: |
|||
<source lang="text"> |
|||
extension=php_curl.dll |
|||
</source> |
|||
* To use '''XML RPC''', uncomment the line: |
|||
<source lang="text"> |
|||
extension=php_xmlrpc.dll |
|||
</source> |
|||
; Add/change certificate CA |
|||
* Edit {{file|php.ini}}: |
|||
<source lang="text"> |
|||
openssl.cafile=C:/path/to/sslCertificates/cacert.pem |
|||
</source> |
|||
== Invocation == |
|||
<source lang=bash> |
|||
php -a # Start PHP in interactive mode |
|||
</source> |
|||
== Syntax == |
|||
=== Data types === |
|||
<source lang=php> |
|||
/* boolean */ |
|||
$x = true; |
|||
$y = false; |
|||
/* integers */ |
|||
$i = 42; |
|||
/* arrays */ |
|||
$attr = array(); // an empty array |
|||
$cars = array("Volvo","BMW","Toyota"); |
|||
$cars[0] = "Volvo"; |
|||
$attr = array("border"=>"myborder", "mode"=>"mymode"); // associative array |
|||
$attr['border'] = "myborder"; |
|||
/* strings */ |
|||
'abc' . 'def' // concatenation |
|||
"abc $var def" // variable reference in strings |
|||
$s=str_replace("\n","",$s); // Replace a substring in a string |
|||
$s=str_replace(array("\r","\n","\t"," "),"",$s; // ... idem, with several substrings (also support several "replace" strings) |
|||
</source> |
|||
=== Operators === |
|||
<source lang=php> |
|||
/* arithmetic */ |
|||
$x + $y; |
|||
$x - $y; |
|||
$x * $y; |
|||
$x / $y; |
|||
$x % $y; |
|||
$x ** $y; // exponentiation |
|||
/* assigment */ |
|||
$x = $y; |
|||
$x += $y;A // ... and all others: -= *= /= %= |
|||
/* comparison */ |
|||
$x == $y; // ... and all others: != > < >= <= |
|||
$x <> $y; // same as != |
|||
$x === $y; // identical operator (are equal and of the same type) |
|||
$x !== $y; // not identical operator (are not equal or are not of the same type) |
|||
/* increment / decrement */ |
|||
$x++; // and $x-- |
|||
++$x; // and --$x |
|||
/* logical */ |
|||
$x and $y; // or '&&' |
|||
$x or $y; // or '||' |
|||
$x xor $y; |
|||
!$x; |
|||
/* string */ |
|||
$x . $y; // concatenation |
|||
$x .= $y; // concatenation assignment |
|||
/* array */ |
|||
$x + $y; // union |
|||
$x == $y; // equality |
|||
$x === $y; // identity |
|||
$x != $y; // inequality, or '<>' |
|||
$x !== $y; // non-identity |
|||
/* ternary */ |
|||
$x = $y < 2 ? 3 : 5; |
|||
</source> |
|||
=== Miscellaneous === |
|||
<source lang=php> |
|||
/* OO */ |
|||
self::$static_property; |
|||
$this->property; |
|||
self::CONSTANT; |
|||
/* special keywords */ |
|||
self; // The current class |
|||
$this; // The current object |
|||
NULL; // The null reference |
|||
/* magic constants -- http://php.net/manual/en/language.constants.predefined.php */ |
|||
__FILE__ // The full path and filename of the file with symlinks resolved |
|||
__DIR__ // Equivalent to dirname(__FILE__). Since PHP 5.3.0 |
|||
/* Scope */ |
|||
global $wgScriptPath; // Declare $wgScriptPath as global when in a local scope |
|||
</source> |
|||
=== Control flow === |
|||
* http://php.net/manual/en/control-structures.foreach.php |
|||
<source lang="php"> |
|||
$arr = array(1, 2, 3, 4); |
|||
foreach ($arr as $value) { echo "$key => $value"; } // By value |
|||
foreach ($arr as $key => $value) { echo "$value"; } // By key and value |
|||
foreach ($arr as &$value) { $value = $value * 2; } // By reference |
|||
unset($value); // RECOMMENDED! Break the reference with the last element |
|||
foreach (array(1, 2, 3, 4) as &$value) { $value = $value * 2; } // By reference on an array value - only PHP >5.5.0 |
|||
</source> |
|||
=== Include and Require === |
|||
<source lang="php"> |
|||
include 'mylibrary.php'; |
|||
</source> |
|||
== How-to == |
|||
=== Convert string to Boolean === |
|||
<source lang=php> |
|||
$test_mode = $string === 'true' ? true : false; |
|||
</source> |
|||
=== Print human-readable information about a variable === |
|||
Use [http://php.net/manual/en/function.print-r.php <code>print_r</code>]: |
|||
<source lang=php> |
|||
<?php |
|||
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => 'orange'); |
|||
print_r ($a); |
|||
?> |
|||
</source> |
|||
This produces: |
|||
<pre> |
|||
Array |
|||
( |
|||
[a] => apple |
|||
[b] => banana |
|||
[c] => orange |
|||
) |
|||
</pre> |
|||
=== Split a string by string === |
|||
Use [http://php.net/manual/en/function.explode.php <code>explode</code>]: |
|||
<source lang="php"> |
|||
print_r(explode(' ', 'one two three four')); |
|||
</source> |
|||
This produces |
|||
<pre> |
|||
Array |
|||
( |
|||
[0] => one |
|||
[1] => two |
|||
[2] => three |
|||
[3] => four |
|||
) |
|||
</pre> |
|||
=== Detect if an array key is defined === |
|||
Use either <code>array_key_exists</code> (slow but works even if value is <code>null</code), or <code>isset</code> (faster, but fails if assigned value is <code>null</code>) [http://php.net/manual/en/function.array-key-exists.php]: |
|||
<source lang="php"> |
|||
$foo = array(); |
|||
$foo['bar'] = NULL; |
|||
var_dump(isset($foo['bar'])); |
|||
var_dump(array_key_exists('bar', $foo)); |
|||
</source> |
|||
== Unicode support == |
|||
* First, if PHP file contains special character, make sure the PHP file is encoded in UTF-8: |
|||
<source lang=bash> |
|||
file -bi FenTT.php # To get current encoding |
|||
iconv -f $encoding -t UTF-8 -o FenTT.out.php FenTT.php # Specify correct source $encoding as given above (note that converting us-ascii is useless) |
|||
</source> |
|||
* Specify the default multi-byte encoding: |
|||
<source lang=bash> |
|||
mb_internal_encoding("UTF-8"); |
|||
</source> |
|||
* Next store unicode char as follows [http://stackoverflow.com/questions/6058394/unicode-character-in-php-string]: |
|||
<source lang=bash> |
|||
$S = '\u2654\u2655\u2656\u2657'; |
|||
$S = json_decode('"'.$S.'"'); |
|||
</source> |
|||
* Then access the string using the multi-byte API [http://www.yiiframework.com/wiki/16/how-to-set-up-unicode/], like [http://de.php.net/manual/en/ref.mbstring.php]: |
|||
<source lang=bash> |
|||
$D = mb_substr($S,2,1); // instead of $D=$S[2] |
|||
</source> |
|||
See [http://php.net/manual/en/language.types.string.php#language.types.string.details php reference - string details] for more information on how strings are handled internally in php. |
|||
== PHP to Javascript == |
|||
=== Encode PHP variable in Javascript === |
|||
Use the <code>json_encode($myarray)</code>: |
|||
<source lang=php> |
|||
$my_array = array(person => "personA", id => 12); |
|||
return "<script>" . json_encode($my_array) . "</script>"; |
|||
return |
|||
</source> |
|||
To pretty-print JSON, use <code>JSON_PRETTY_PRINT</code>: |
|||
<source lang=php> |
|||
echo json_encode($my_array, JSON_PRETTY_PRINT); |
|||
</source> |
Latest revision as of 05:50, 16 October 2018
References
- Language reference on php.net
- php tutorial on w3schools.com (check the menu on the left)
Cheat sheets:
Install
On Windows
Download the zip archive on http://windows.php.net/download/:
- PHP 5.6.30 32-bit - Non Thread Safe (faster).
- To install
- Create a directory C:\php and unzip archive inside.
- Add C:\php to system environment path
PATH
. - Copy C:\php\php.ini-production to C:\php.ini.
- Alternatively use the development version for more debug. But production ini is handy to mute deprecated API warnings
- Enable a few extensions
- To use HTTPS or SSL, uncomment the line:
extension=php_openssl.dll
- To use SOAP, uncomment the line:
extension=php_soap.dll
- To use Curl, uncomment the line:
extension=php_curl.dll
- To use XML RPC, uncomment the line:
extension=php_xmlrpc.dll
- Add/change certificate CA
- Edit php.ini:
openssl.cafile=C:/path/to/sslCertificates/cacert.pem
Invocation
php -a # Start PHP in interactive mode
Syntax
Data types
/* boolean */
$x = true;
$y = false;
/* integers */
$i = 42;
/* arrays */
$attr = array(); // an empty array
$cars = array("Volvo","BMW","Toyota");
$cars[0] = "Volvo";
$attr = array("border"=>"myborder", "mode"=>"mymode"); // associative array
$attr['border'] = "myborder";
/* strings */
'abc' . 'def' // concatenation
"abc $var def" // variable reference in strings
$s=str_replace("\n","",$s); // Replace a substring in a string
$s=str_replace(array("\r","\n","\t"," "),"",$s; // ... idem, with several substrings (also support several "replace" strings)
Operators
/* arithmetic */
$x + $y;
$x - $y;
$x * $y;
$x / $y;
$x % $y;
$x ** $y; // exponentiation
/* assigment */
$x = $y;
$x += $y;A // ... and all others: -= *= /= %=
/* comparison */
$x == $y; // ... and all others: != > < >= <=
$x <> $y; // same as !=
$x === $y; // identical operator (are equal and of the same type)
$x !== $y; // not identical operator (are not equal or are not of the same type)
/* increment / decrement */
$x++; // and $x--
++$x; // and --$x
/* logical */
$x and $y; // or '&&'
$x or $y; // or '||'
$x xor $y;
!$x;
/* string */
$x . $y; // concatenation
$x .= $y; // concatenation assignment
/* array */
$x + $y; // union
$x == $y; // equality
$x === $y; // identity
$x != $y; // inequality, or '<>'
$x !== $y; // non-identity
/* ternary */
$x = $y < 2 ? 3 : 5;
Miscellaneous
/* OO */
self::$static_property;
$this->property;
self::CONSTANT;
/* special keywords */
self; // The current class
$this; // The current object
NULL; // The null reference
/* magic constants -- http://php.net/manual/en/language.constants.predefined.php */
__FILE__ // The full path and filename of the file with symlinks resolved
__DIR__ // Equivalent to dirname(__FILE__). Since PHP 5.3.0
/* Scope */
global $wgScriptPath; // Declare $wgScriptPath as global when in a local scope
Control flow
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) { echo "$key => $value"; } // By value
foreach ($arr as $key => $value) { echo "$value"; } // By key and value
foreach ($arr as &$value) { $value = $value * 2; } // By reference
unset($value); // RECOMMENDED! Break the reference with the last element
foreach (array(1, 2, 3, 4) as &$value) { $value = $value * 2; } // By reference on an array value - only PHP >5.5.0
Include and Require
include 'mylibrary.php';
How-to
Convert string to Boolean
$test_mode = $string === 'true' ? true : false;
Print human-readable information about a variable
Use print_r
:
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => 'orange');
print_r ($a);
?>
This produces:
Array ( [a] => apple [b] => banana [c] => orange )
Split a string by string
Use explode
:
print_r(explode(' ', 'one two three four'));
This produces
Array ( [0] => one [1] => two [2] => three [3] => four )
Detect if an array key is defined
Use either array_key_exists
(slow but works even if value is null</code), or
isset
(faster, but fails if assigned value is null
) [1]:
$foo = array();
$foo['bar'] = NULL;
var_dump(isset($foo['bar']));
var_dump(array_key_exists('bar', $foo));
Unicode support
- First, if PHP file contains special character, make sure the PHP file is encoded in UTF-8:
file -bi FenTT.php # To get current encoding
iconv -f $encoding -t UTF-8 -o FenTT.out.php FenTT.php # Specify correct source $encoding as given above (note that converting us-ascii is useless)
- Specify the default multi-byte encoding:
mb_internal_encoding("UTF-8");
- Next store unicode char as follows [2]:
$S = '\u2654\u2655\u2656\u2657';
$S = json_decode('"'.$S.'"');
$D = mb_substr($S,2,1); // instead of $D=$S[2]
See php reference - string details for more information on how strings are handled internally in php.
PHP to Javascript
Encode PHP variable in Javascript
Use the json_encode($myarray)
:
$my_array = array(person => "personA", id => 12);
return "<script>" . json_encode($my_array) . "</script>";
return
To pretty-print JSON, use JSON_PRETTY_PRINT
:
echo json_encode($my_array, JSON_PRETTY_PRINT);