DevDungeon
- Labs
Knowledge
Social
DevDungeon
Knowledge
Social
This is an old revision of the document!
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
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 servers page for more info on configuring
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 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 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 is an optional tool for managing depedencies.
Here are some snippets for reference.
Here is a simple “Hello world” application.
<?php echo "Hello, world!";
<?php // Show all PHP configs/extensions phpinfo();
<?php // Add this to turn on all errors (disable in production!) // The ini_set options could also go in php.ini ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
<?php function greet($name, $greeting="Hi") { print("$greeting, $name!"); } greet("NanoDano"); // Hi, NanoDano!
<?php // Pick one method for loading another PHP file include('my_lib.php'); // Include if available require('my_lib.php'); // Fail if not available require_once('my_lib.php'); // Ensure not loaded twice
<html> <body> <?php if ($_POST['something']) { print("Received: " . $_POST['something']; } <form method="post"> <input type="text" name="something" id="something" /> <br /> <button type="submit">Submit</button> </form> </body> </html>
Use the PHP function header() to send a new Location
header.
<?php // Set HTTP header to redirect // Must go before any content is output header('Location: /'); // Defaults to 302 // Or specify status code //header('Location: /', TRUE, 301); exit; // If you want to ensure nothing else gets output
This example is for SQLite3 using the PHP PDO_SQLITE, but essentially the same for other databases too.
apt install php-pdo-sqlite
<?php // Connect (Use `sqlite::memory:` for memory-only) $db = new PDO('sqlite:'.__DIR__.'/bookmarks.sqlite3'); // Create table $db->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'].'<br />'); } $db = null; // Close it
// 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);
<?php $socket = stream_socket_server("tcp://192.168.1.5:8000", $errno, $errstr); if (!$socket) { echo "$errstr ($errno)\n"; die('Could not create socket'); } while (true) { while ($conn = stream_socket_accept($socket, -1, $peername)) { fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n"); echo "Connection received from: $peername\n"; fclose($conn); } } fclose($socket);
<?php $certificateData = array( "countryName" => "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);
<?php $context = stream_context_create(); // local_cert must be in PEM format stream_context_set_option($context, 'ssl', 'local_cert', $pemfile); // Pass Phrase (password) of private key stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase); stream_context_set_option($context, 'ssl', 'allow_self_signed', true); stream_context_set_option($context, 'ssl', 'verify_peer', false); // Create the server socket $socket = stream_socket_server( 'ssl://0.0.0.0:9001', $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context ); // fwrite/fread to $socket
<?php // Simple SSL client $socket = stream_socket_client("ssl://192.168.1.2:5522", $errno, $errstr); if ($socket) { echo fread($socket, 2000); }
<?php $host = '192.168.1.2'; $port = 5522; $timeout = 30; $cert = 'e:\www\workspace\php\sockets\server.pem'; $context = stream_context_create( array('ssl'=>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"; }