====== PHP Programming ======
PHP is a web-native language that essentially embeds itself within HTML.
While the wiki is still being built, refer to: [[https://www.devdungeon.com/topics/php]] and [[https://github.com/DevDungeon/Cookbook/tree/master/php]]
===== Installing =====
In Debian and most Linux distributions, it's as simple as using the package manager:
apt install php php-pdo-sqlite
php --version
# For Apache2 httpd
apt install apache2 libapache2-mod-php
See the [[:web|web servers]] page for more info on configuring
===== Built-in webserver =====
PHP has a built-in web server that is useful for local developing and testing.
# Serves current directory, no directory listing
php -S localhost:9999
# Specify path to serve
php -S localhost:9999 -t /path/to/serve
===== Phar files =====
Phar files are essentially tarballs of PHP content. In addition to the convenience of having a single .phar containing many files, the phar can be marked executable and treated like an executable Java JAR. See the [[https://www.php.net/manual/en/intro.phar.php|official phar documentation]].
It can be treated as a special protocol for referencing files like this: ''phar:%%//%%myphar.phar/file.php''
You can read or include files in this manner.
===== Composer =====
Composer is an optional tool for managing depedencies.
See: [[https://www.devdungeon.com/content/php-composer-basics]]
===== Code examples =====
Here are some snippets for reference.
==== Hello world ====
Here is a simple "Hello world" application.
==== PHP info ====
==== Show all errors ====
==== Functions ====
==== Include a PHP file ====
==== Forms ====
==== Redirect ====
Use the PHP function [[https://www.php.net/manual/en/function.header.php|header()]] to send a new ''Location'' header.
==== SQLite database ====
This example is for SQLite3 using the [[https://www.php.net/manual/en/ref.pdo-sqlite.php|PHP PDO_SQLITE]], but essentially the same for other databases too.
''apt install php-pdo-sqlite''
exec(
"CREATE TABLE IF NOT EXISTS urls (
url TEXT,
notes TEXT
)"
);
// Prepared statement for changes
$query = $db->prepare('INSERT INTO urls (url) VALUES (?)');
$query->execute(['https://www.devdungeon.com/']);
// Query
$result = $db->query('SELECT * FROM urls');
foreach ($result as $result) {
print($result['url'].' ');
}
$db = null; // Close it
==== libgit2 ====
See: https://www.devdungeon.com/content/how-perform-git-operations-php
==== Crop images ====
// Crop using GD (`apt install php-gd`)
$src_img = imagecreatefrompng('300x200.png');
if(!$src_img) {
die('Error when reading the source image.');
}
$thumbnail = imagecreatetruecolor(200, 200);
if(!$thumbnail) {
die('Error when creating the destination image.');
}
// Take 200x200 from 200x200 starting at 50,0
$result = imagecopyresampled($thumbnail, $src_img, 0, 0, 50, 0, 200, 200, 200, 200);
if(!$result) {
die('Error when generating the thumbnail.');
}
$result = imagejpeg($thumbnail, '200x200gd.png');
if(!$result) {
die('Error when saving the thumbnail.');
}
$result = imagedestroy($thumbnail);
if(!$result) {
die('Error when destroying the image.');
}
// Crop image using Imagick (`apt install php-imagick`)
$inFile = "300x200.png";
$outFile = "200x200_imagick.png";
$image = new Imagick($inFile);
$image->cropImage(200,200, 50,0);
$image->writeImage($outFile);
==== JSON ====
JSON string
$json_string = json_encode(['my_key' => 'my value', 'other_key' => 'other value']);
echo $json_string;
# JSON string -> PHP object
$json_string = '{"my_key":"my value","other_key":"other value"}';
$my_array = json_decode($json_string);
print_r($my_array)
// Dump/read from file
file_put_contents('test.json', json_encode([2, 4, 6]));
$my_array = json_decode(file_get_contents('test.json'));
print_r($my_array);
==== Sockets ====
=== TCP server ===
=== Generate SSL certificate ===
"US",
"stateOrProvinceName" => "Texas",
"localityName" => "Houston",
"organizationName" => "Example.com",
"organizationalUnitName" => "Development",
"commonName" => "My Company",
"emailAddress" => "example@example.com"
);
// Generate certificate
$privateKey = openssl_pkey_new();
$certificate = openssl_csr_new($certificateData, $privateKey);
$certificate = openssl_csr_sign($certificate, null, $privateKey, 365);
// Generate PEM file
$pem_passphrase = 'abracadabra'; // empty for no passphrase
$pem = array();
openssl_x509_export($certificate, $pem[0]);
openssl_pkey_export($privateKey, $pem[1], $pem_passphrase);
$pem = implode($pem);
// Save PEM file
$pemfile = './server.pem';
file_put_contents($pemfile, $pem);
=== SSL server ===
=== SSL client ===
array('local_cert'=> $cert))
);
if ($socket = stream_socket_client(
'ssl://'.$host.':'.$port,
$errno,
$errstr,
30,
STREAM_CLIENT_CONNECT,
$context)
) {
fwrite($socket, "\n");
echo fread($socket,8192);
fclose($socket);
} else {
echo "ERROR: $errno - $errstr\n";
}
==== Tail a file ====
&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer \n";
ob_flush();
flush();
}
pclose($handle);
==== Simple HTTP request ====
==== cURL requests ====
Install [[https://packages.debian.org/buster/php-curl|php-curl]] on Debian. [[https://curl.se|cURL]] lets you make all kinds of requests, not just HTTP. See my tutorial: [[https://www.devdungeon.com/content/curl-tutorial|cURL Tutorial]].