PATH
C:\wamp\bin\php\version\ to PATH via Computer Settingsecho 'export PATH=/Applications/MAMP/bin/php/phpversion/bin/:$PATH' >> ~/.bash_profile.zip onto your filesystem and you're good to gophp.ini
php.ini shipped with Wampserver/MAMP is configured mostly correctlyphp -a to get an interative shell at which you can type in PHP statements
; ends a statementquit or exit to leave the shellbramus$ php -a
Interactive shell
php > echo 'hello';
hello
php > quit
bramus$php -r "one line of PHP code" to run a single line of PHP code
bramus$ php -r "echo 'hello' . PHP_EOL;"
hello
bramus$php [-f] file.php to “execute” a file that contains PHP code
<?php and ?>?> is optional.<?php
echo 'hello' . PHP_EOL;
?>bramus$ php cli-example.php
hello
bramus$.php extension and the PHP interpreter will interpret the file
php -S localhost:8080
' or "
echo or print to output something onscreen.
bramus$ php -a
Interactive shell
php > echo 'hello';
hello
php > echo('hello');
hello
php > print 'hello';
hello
php > print('hello');
hello
;
php > echo 'hello'
php > ;
hello
$php > $a = 3;
php > echo $a;
3php > $a = 3;
php > echo gettype($a);
integer
php > $a = 'Hello';
php > echo gettype($a);
stringphp > $a = 3;
php > echo gettype($a);
integer
php > $a = (string) $a;
php > echo gettype($a);
string$firstName and $firstname are not the same!
php > $firstName = 'Bramus';
php > echo $firstName;
Bramus
php > echo $firstname;
Notice: Undefined variable: firstname in php shell code on line 1.
+, PHP will think you're adding numbers (weak typing!)
php > $firstName = 'Bramus';
php > $lastName = 'Van Damme';
php > echo $firstName + ' ' + $lastName;
0
php > echo $firstName . ' ' . $lastName;
Bramus Van Damme
", PHP will try to substitute any string that could resemble a variable
php > $firstName = 'Bramus';
php > echo "variable: $firstName\n";
variable: Bramus
php > echo "variable: \$firstName\n";
variable: $firstName
php > echo 'variable: $firstName\n';
variable: $firstName\n
php > echo 'variable: \$firstName\n';
variable: \$firstName\n
php > echo 'variable: ' . $firstName . '\n';
variable: Bramus\n
php > echo 'variable: ' . $firstName . "\n";
variable: Bramus
php > echo 'variable: ' . $firstName . PHP_EOL;
variable: Bramus' to prevent interpolationPHP_EOL instead of "\n"php > $arr = array();
php > $arr[] = 'se7en';
php > $arr[] = 123;
php > $arr[] = true;
php > echo $arr[1];
123php > $arr = array();
php > $arr[2] = 'se7en';
php > $arr[] = 123;
php > $arr[] = true;
php > echo $arr[3];
123php > $arr = array();
php > $arr[2] = 'se7en';
php > $arr[8] = 123;
php > $arr[4] = true;
php > echo $arr[8];
123php > $arr = array();
php > $arr['BE'] = 'Belgium';
php > $arr['NL'] = 'The Netherlands';
php > $arr['FR'] = 'France';
php > echo $arr['BE'];
Belgiumphp > $arr1 = array('Brussels', 'Ghent', 'Antwerp');php > $arr2 = array('NL' => 'The Netherlands', 'BE' => 'Belgium');php > $arr2 = array(
php ( 'NL' => 'The Netherlands',
php ( 'BE' => 'Belgium'
php ( );php > $arr1 = ['Brussels', 'Ghent', 'Antwerp'];// Single line comment
/* Multi
line
comment
*/
/**
* Preferred way
* to layout
* multi-line
* comments
*/<?php
if ($condition) {
// do something
}
if ($condition) {
// do something
} else {
// do something else
}
switch ($var) {
case $value1:
// do something
break;
case $value2:
// do something
break;
default:
// do something
}<?php
$a = 7;
if ($a < 9) {
echo '$a is less than 9';
} else {
echo '$a is greater than 9';
}TAB inside curly brackets<?php
$a = 7;
echo (($a < 9) ? '$a is less than 9' : '$a is greater than 9');<?php
echo $nickName ?: $firstName;$nickName is truthy then it will be outputted. If not $firstName will.<?php
while ($condition) {
// do something
}
do {
// do something
} while ($condition);
for ($x = 0; $x < 5; $x++) {
// do something
}
foreach ($arr as $value) {
// do something
}
foreach ($arr as $key => $value) {
// do something
}break; and continue;php > for ($x = 1; $x <= 6; $x++) {
php { echo 'Hello 2ICT' . $x . PHP_EOL;
php { }
Hello 2ICT1
Hello 2ICT2
Hello 2ICT3
Hello 2ICT4
Hello 2ICT5
Hello 2ICT6php > $countries = array('BE' => 'Belgium', 'NL' => 'The Netherlands');
php > foreach ($countries as $key => $value) {
php { echo $key . ' = ' . $value . PHP_EOL;
php { }
BE = Belgium
NL = The Netherlands==, !=, <, >, <=, >=&&, ||, !, &, |$var--, $var++, --$var, ++$var+=, *=, …php > $a = 13; // integer
php > $b = 13.0; // double
php > echo ($a == $b) ? 'equal' : 'not equal';
equal
php > echo ($a === $b) ? 'equal' : 'not equal';
not equaladdslashes/stripslashes — see 04.formsltrim/rtrim/trim — strips leading/trailing/enclosing whitespacestr_replace — replaces a part of a string with an other valuestrip_tags — strips html from a stringstrlen — returns the length of a stringstrtolower/strtoupper — convert a string to uppercase/lowercasesubstr — extract a part of a stringceil — round numerical values upfloor — round numerical values downround — round numerical values mathematicallyrand/mt_rand — generate a random numbersqrt — calculate the square root of a numbersizeof/count — get the size of an arraysort — sort an arrayasort — sort an associative arrayexplode — split a string on a given delimiter and get an arrayimplode — opposite of explodearray_push — push an element onto an arrayarray_pop — get an element off the end of an arrayarray_key_exists — check if a key in an associative array exists<?php
// Our chopStringEnd function
function chopStringEnd($str, $len, $ending) {
if (strlen($str) < $len) {
return $str;
} else {
return substr($str, 0, $len - strlen($str)) . $ending;
}
}
// Our variables
$origStr = '/Users/bramus/Dropbox/Kaho/Lesactiviteiten/Webscripting1';
$cutoffLength = 40;
$endStr = '...';
// Go!
echo chopStringEnd($origStr, $cutoffLength, $endStr);<?php
// Our chopStringEnd function
function chopStringEnd($str, $len = 30, $ending = '---') {
if (strlen($str) < $len) {
return $str;
} else {
return substr($str, 0, $len - strlen($str)) . $ending;
}
}
// Our variables
$origStr = '/Users/bramus/Dropbox/Kaho/Lesactiviteiten/Webscripting1';
$cutoffLength = 40;
$endStr = '...';
// Go!
echo chopStringEnd($origStr, $cutoffLength, $endStr) . PHP_EOL;
echo chopStringEnd($origStr, $cutoffLength) . PHP_EOL;
echo chopStringEnd($origStr);<?php
/**
* Chops a string at the given length with the given ending
*
* @param string $str The initial String
* @param int $len The length to chop off at
* @param string $ending The ending to add
*
* @return string The circumcised up string
*/
function chopStringEnd($str, $len = 30, $ending = '---') {
if (strlen($str) < $len) {
return $str;
} else {
return substr($str, 0, $len - strlen($str)) . $ending;
}
}
...<?php
$host = 'http://www.myhost.com/';
function absUrl($relUrl) {
return $host.$relUrl;
}
echo absUrl('files/uploads/me.jpg');Notice: Undefined variable: host in /Users/bramus/Dropbox/Kaho/Lesactiviteiten/.../assets/01/examples/scoping1.php on line 8
files/uploads/me.jpgglobal keyword to the rescue
<?php
$host = 'http://www.myhost.com/';
function absUrl($relUrl) {
global $host;
return $host . $relUrl;
}
echo absUrl('files/uploads/me.jpg');<?php
$host = 'http://www.myhost.com/';
function absUrl($relUrl, $host) {
return $host . $relUrl;
}
echo absUrl('files/uploads/me.jpg', $host);<?php
function absUrl($relUrl, $host = 'http://www.myhost.com/') {
return $host . $relUrl;
}
echo absUrl('files/uploads/me.jpg');define(), a function that shipped with PHP4
<?php
define('HOST', 'http://www.myhost.com/');
function absUrl($relUrl) {
return HOST . $relUrl;
}
echo absUrl('files/uploads/me.jpg');define() to define global constants, never use the global keyword
use keyword to inject a variable into a function
<?php
$host = 'http://www.myhost.com/';
$absUrl = function ($relUrl) use ($host) {
return $host . $relUrl;
};
echo $absUrl('files/uploads/me.jpg');define() for now.
<?php
error_reporting(E_ALL); // = Report all errors
ini_set('display_errors', 'on'); // = Show the errors on screen
php.ini file@<?php
function divide($numerator, $denominator) {
return $numerator / $denominator;
}
echo divide(1, 2) . PHP_EOL; // 0.5
echo divide(1, 0) . PHP_EOL; // "Warning: Division by zero"
echo @divide(1, 0) . PHP_EOL; // (suppressed)
echo divide(1, 2) . PHP_EOL; // 0.5Exception
php > $arr = array('one', 'two', 'three');
php > echo $arr;
Arrayprint_r() and var_dump() instead to inspect variables
php > print_r($arr);
Array
(
[0] => one
[1] => two
[2] => three
)
php > var_dump($arr);
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
string(5) "three"
}print_r() and var_dump() is no real debugging
0 = January 1 1970, 00:00:00 GMT86400 = Januari 2 1970, 00:00:00 GMT31536000 = Januari 1 1971, 00:00:00 GMT440423100 = December 26 1983, 11:45:00 GMT946684800 = Januari 1 2000, 00:00:00 GMT1234567890 = February 13 2009, 23:31:30 GMTtime() returns the number of seconds since the epochmktime() allows you to build a timestamp for a given hour, minute, second, month, day and yearstrtotime(string $time, [int $now])
$time is something like 2012-24-09 but can also be next fridaydate(string $format, [int $timestamp])
$timestamp is empty, the current one is used$format param needs to be built manually
format character |
Description | Example returned values |
|---|---|---|
| d | Day of the month, 2 digits with leading zeros | 01 to 31 |
| D | A textual representation of a day, three letters | Mon through Sun |
| l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday |
| w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
| F | A full textual representation of a month, such as January or March | January through December |
| m | Numeric representation of a month, with leading zeros | 01 through 12 |
| M | A short textual representation of a month, three letters | Jan through Dec |
| Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
| y | A two digit representation of a year | Examples: 99 or 03 |
| H | 24-hour format of an hour with leading zeros | 00 through 23 |
| i | Minutes with leading zeros | 00 to 59 |
| s | Seconds, with leading zeros | 00 through 59 |
<?php
echo date('l');
echo date('l jS \of F Y h:i:s A');
echo 'July 1, 2000 is on a ' . date('l', mktime(0, 0, 0, 7, 1, 2000));<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = mktime(17,16,18,3,10,2001);
date_default_timezone_set('America/Phoenix');
echo date('F j, Y, g:i a'); // March 10, 2001, 5:16 pm
echo date('m.d.y'); // 03.10.01
echo date('j, n, Y'); // 10, 3, 2001
echo date('Ymd'); // 20010310
echo date('h-i-s, j-m-y, it is'); // 05-16-18, 10-03-01, 1631 1618
echo date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
echo date('D M j G:i:s T Y'); // Sat Mar 10 17:16:18 MST 2001
echo date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
echo date('H:i:s'); // 17:16:18$argc and $argv
<?php
echo 'Number of arguments ' . $argc . PHP_EOL;
foreach ($argv as $key => $value) {
echo 'Argument #' . $key . ' : ' . $value . PHP_EOL;
}bramus$ php cli-args1.php foo bar baz
Number of arguments 4
Argument #0 : args1.php
Argument #1 : foo
Argument #2 : bar
Argument #3 : baz<?php
$args = getopt('ab:c::');
# nothing = don't accept any value (why? WHYYYY?)
# trailing : = required
# trailing :: = optional
var_dump($args);bramus$ php cli-args2.php -a -b 2 -c3
array(3) {
["a"]=>
bool(false)
["b"]=>
string(1) "2"
["c"]=>
string(1) "3"
}<?php
$args = getopt('', array('a', 'b:', 'c::'));
# nothing = don't accept any value (why? WHYYYY?)
# trailing : = required
# trailing :: = optional
var_dump($args);bramus$ php cli-args3.php --a --b "2" --c=3
array(3) {
["a"]=>
bool(false)
["b"]=>
string(1) "2"
["c"]=>
string(1) "3"
}readline() to ask for input whilst the script is runnning
<?php
$name = readline('What is your name? ');
$city = readline('Where do you live? ');
echo 'Hello ' . $name . ' from ' . $city . PHP_EOL;bramus$ php cli-interactive.php
What is your name? Bramus
Where do you live? Vinkt
Hello Bramus from VinktSTDIN = input
<?php
while(!feof(STDIN)) {
$line = trim(fgets(STDIN));
if(strlen($line) > 0) {
echo strrev($line).PHP_EOL;
}
}bramus$ cat cli-stdin-input.txt
monkey
elephant
cow
giraffe
bramus$ cat cli-stdin-input.txt | php cli-stdin.php
yeknom
tnahpele
woc
effarigSTDOUT/STDERR = output
bramus$ php -r "fwrite(STDOUT, 'hello world');"
hello worldbramus$ php -r "fwrite(STDERR, 'hello world');"
hello worldSTDOUT and STDERR?
bramus$ php -r "fwrite(STDOUT, 'stdout world') . fwrite(STDERR, 'stderr world');" > /dev/null
stderr worldreadline() isn't available everywhere
STDIN
function getInput($question = '') {
if (!function_exists('readline')) {
echo $question . ' ';
return stream_get_line(STDIN, 1024, PHP_EOL);
} else {
return readline($question . ' ');
}
}
$name = getInput('What is your name?');
$city = getInput('Where do you live?');
echo 'Hello ' . $name . ' from ' . $city . PHP_EOL;php -l faulty.php
<?php
echo $foo;
for ($x = 0; $x < 5; x++) {
echo $x;
}bramus$ php -l faulty.php
Parse error: parse error, expecting `')'' in faulty.php on line 4
Errors parsing faulty.phpphp -i
bramus$ php -i
phpinfo()
PHP Version => 5.4.24
System => Darwin brm.local 13.3.0 Darwin Kernel Version 13.3.0: Tue Jun 3 21:27:35 PDT 2014; root:xnu-2422.110.17~1/RELEASE_X86_64 x86_64
Build Date => Jan 19 2014 21:18:21
Configure Command => '/private/var/tmp/apache_mod_php/apache_mod_php-87.2~1/php/configure' '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info'...<?php
phpinfo();php -v
bramus$ php -v
PHP 5.4.24 (cli) (built: Jan 19 2014 21:32:15)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologiesphp -s file.php
<?php. The closing tag may be omittederror_reporting() set to E_ALL and display_errors set to Onif-else,do-while,for/foreach, switch,...TAB, not a few spacesglobal but preferably use a constant/definenull
$_REQUEST (see 04.forms)