PHP

variables
Variable: $str = "string"; $int = 1; $flt = 3.141; $obj = new Object; $arry = array(1, 2, 3); $empty_array = array; $null = NULL;

global variable: (to access inside function) $var = 1 function a { global $var; }

Check if variable is empty: empty($var)

Check if variable is set: isset($var)

Control Structures
if else elseif/else if while do-while for foreach break continue switch declare return require include require_once include_once goto

if
Comparison Operators: > (bigger than) >= (bigger than or equal to) == (equal) != (not equal) <> (not equal) < (smaller than) <= (smaller than or equal to)

Strict equivalence operators: === (equal to and same type) !== (not equal to or not same type)

Logical Operators: Example 	Name 	Result $a and $b 	And 	TRUE if both $a and $b are TRUE. $a or $b 	Or 	TRUE if either $a or $b is TRUE. $a xor $b 	Xor 	TRUE if either $a or $b is TRUE, but not both. ! $a 	Not 	TRUE if $a is not TRUE. $a && $b 	And 	TRUE if both $a and $b are TRUE. $a || $b 	Or 	TRUE if either $a or $b is TRUE.

Ternary Operator - http://php.net/manual/en/language.operators.comparison.php: (expr1) ? (expr2_on_true) : (expr3_on_false); $var = (expr1) ? (expr2_on_true) : (expr3_on_false) ; $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

for
for (setup_expr1; cond_expr2; loop_expr3) statement

for ($i = 1; $i <= 10; $i++) { echo $i; }

foreach
Note: foreach works only on arrays and 'iterate objects'

foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement

foreach( $myarray as $value) { ... } foreach( $myarray as $key => $value) { ... }

while
while( [statement] ) { ... }

break and continue
break - ends execution of the current for, foreach, while, do-while or switch structure.

for(...) { ...  break;  # exit for loop }

continue - is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

for(...) { ...  continue;  # continue to next iteration }

switch
Series of IF statements (similar to 'case statment' in other languages)

switch ($i) { case 0: echo "i equals 0"; break; default: echo "i is not equal to 0"; }

Strings
Lower case: strtolower( string $str );

Upper case: strtoupper( string $str );

Heredoc: $str = <<" | php | grep -i "mysql support"

file io
fopen — Opens file or URL: $handle = fopen("/home/rasmus/file.txt", "r");
 * 1) resource fopen ( string $filename, string $mode [, bool $use_include_path = false [, resource $context ]] )

 mode 	Description 'r' 	Open for reading only; place the file pointer at the beginning of the file. 'r+' 	Open for reading and writing; place the file pointer at the beginning of the file. 'w' 	Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' 	Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'a' 	Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. 'a+' 	Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

read
Make array of lines of file: $lines = file( $file );

Read line from file: (1024 byte buffer) $line = fgets( $file, 1024 );

readfile - Reads a file and writes it to the output buffer: readfile( $file );
 * 1) int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

file — Reads entire file into an array: $lines = file('http://www.example.com/');
 * 1) array file ( string $filename [, int $flags = 0 [, resource $context ]] )

fread — Binary-safe file read:
 * 1) string fread ( resource $handle, int $length )

// get contents of a file into a string $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle);

Reading a file line by line: $handle = @fopen("/tmp/inputfile.txt", "r"); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; }   if (!feof($handle)) { echo "Error: unexpected fgets fail\n"; }   fclose($handle); }

write
fwrite — Binary-safe file write:
 * 1) int fwrite ( resource $handle, string $string [, int $length ] )

$fp = fopen('data.txt', 'w') or die('unable to open for writing'); fwrite($fp, '1'); fclose($fp);

Include other PHP Code
include - statement includes and evaluates the specified file include_once - statement includes and evaluates the specified file only if not already loaded require - is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. require_once - statement is identical to require except PHP will check if the file has already been included

include 'vars.php';

Date and Time
date - Format a local time/date $strdate = date('Y-m-d');
 * 1) string date ( string $format [, int $timestamp = time ] )
 * 1) 2010-06-01

format	Example

Day d	01 to 31 D	Mon, Sun j	1 to 31 w	0 (sun) to 6 (sat) z	0 to 365

Month n	1 to 12 m	01 to 12 M	Jan to Dec

Year Y	1999 y	99

Time g	1 - 12 a	am / pm G	0 - 23 h	01 - 12 H (hr)	01 - 23 i (min)	00 - 59 s (sec)	00 - 59 U	Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

HTTP POST and GET and REQUEST
$var = $_POST["param"]; $var = $_GET["param"]; $var = $_REQUEST["param"]; # includes GET, POST, and COOKIE # order is based on PHP variables_order configuration directive

$user = empty($_REQUEST["user"]) ? '' : trim($_REQUEST["user"]);

$_SERVER
$_SERVER["HTTP_HOST"]		# default.t0e.org $_SERVER["SERVER_NAME"]		# default.t0e.org $_SERVER["SERVER_ADDR"]		# 24.2.94.68 $_SERVER["REMOTE_ADDR"]		# 10.10.10.5 $_SERVER["DOCUMENT_ROOT"]	# /www/default $_SERVER["SCRIPT_FILENAME"]	# /www/default/index.php $_SERVER["REQUEST_METHOD"]	# GET $_SERVER["SCRIPT_NAME"]		# /index.php $_SERVER["PHP_SELF"]		# /index.php

Default error page: (don't forget space at end) Unauthorized!

Regular Expression
Match: findcount = preg_match('/^([a-zA-Z0-9_]*)$/', $user ) findcount = preg_match('/^([a-zA-Z0-9_]*)$/', $user, $matches ) echo $matches[1]; # first paren match
 * 1) int preg_match ( string $pattern, string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

$matches will be an array filled with captured parenthesized subpattern (0 will have full pattern, 1 will have first match)

External Command Execution
exec — Execute an external program: (output to return string) $lastline = exec( $command, $output, $return_var ); exec( $command, $output = array );
 * 1) string exec ( string $command [, array &$output [, int &$return_var ]] )

passthru — Execute an external program and display raw output: (output to buffer) passthru( $command, $return_var );
 * 1) void passthru ( string $command [, int &$return_var ] )

system — Execute an external program and display the output: (output to buffer) string system ( string $command [, int &$return_var ] ) $lastline = system( $command, $return_var );

Source: PHP: passthru - Manual

File System
PHP: file_exists - Manual - http://php.net/manual/en/function.file-exists.php bool file_exists ( string $filename )

PHP: rename - Manual - http://php.net/manual/en/function.rename.php bool rename ( string $oldname, string $newname [, resource $context ] )

email
ini_set("SMTP","smtp.example.com" ); ini_set('sendmail_from', 'user@example.com');

mail - Send mail
 * 1) bool mail ( string $to, string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

To Addresses in this format: user@example.com user@example.com, anotheruser@example.com User  User , Another User 

NOTE NOTE: I had to use "\n" instead of "\r\n" to work on an older debian system!

$to     = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com'. "\r\n". 'Reply-To: webmaster@example.com'. "\r\n". 'X-Mailer: PHP/'. phpversion;

mail($to, $subject, $message, $headers);

HTML email: // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0'. "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1'. "\r\n";

// Additional headers $headers .= 'To: Mary , Kelly '. "\r\n"; $headers .= 'From: Birthday Reminder '. "\r\n"; $headers .= 'Cc: birthdayarchive@example.com'. "\r\n"; $headers .= 'Bcc: birthdaycheck@example.com'. "\r\n";

// Mail it mail($to, $subject, $message, $headers);

MySQL
--- mysqli ---

connect_error) { die("Connection failed: " . $conn->connect_error); }

$sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql);

if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc) { echo "id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]. " ";   } } else { echo "0 results"; } $conn->close; ?>

Select - https://www.w3schools.com/php/php_mysql_select.asp

Insert - https://www.w3schools.com/php/php_mysql_insert.asp

--- old style ---

<?php // Connecting, selecting database $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error); echo 'Connected successfully'; mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query $query = 'SELECT * FROM my_table'; $result = mysql_query($query) or die('Query failed: ' . mysql_error);

// Printing results in HTML echo " \n";

// Free resultset mysql_free_result($result);

// Closing connection mysql_close($link); ?>

PHP: MySQL extension overview example - Manual - http://php.net/manual/en/mysql.examples-basic.php

---

stream_socket_client
@ $fp = stream_socket_client("tcp://localhost:60002", $errno, $errstr, 30); if (!$fp) { echo "FAILURE: Unable to connect to server: $errstr $errno"; die; } fwrite($fp, $send_data); $recv_data = fgets($fp, 1024); fclose($fp);

$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno) \n"; } else { fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); }   fclose($fp); }

Upload Single File
<!DOCTYPE html> Build ESX ISO 

 screenshot.png // [type] => image/png // [tmp_name] => /tmp/phpPiUA5v // [error] => 0 // [size] => 14537

if($upload_file) { if ($upload_file['error'] == UPLOAD_ERR_OK) { $fn = $upload_file['name']; if (move_uploaded_file( $upload_file['tmp_name'], 'uploads/'. $fn)) { echo " UPLOAD SUCCESS: $fn "; } else { echo " UPLOAD FAILURE: $fn "; }   }  }

?>

 HTML File Upload  File to upload:  Upload File

References:
 * PHP: move_uploaded_file - Manual - http://php.net/manual/en/function.move-uploaded-file.php
 * How to Asynchronously Upload Files Using HTML5 and Ajax - SitePoint - http://www.sitepoint.com/html5-ajax-file-upload/

Upload Multiple Files
<!DOCTYPE html> untitled 

 $err) { if ($err == UPLOAD_ERR_OK) { $fn = $files['name'][$id]; if (move_uploaded_file( $files['tmp_name'][$id], 'uploads/'. $fn)) { echo " File $fn uploaded. "; } else { echo " Error: failure to upload $fn! "; }   }  }  ?>

<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data"> HTML File Upload <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" /> Files to upload: <input type="file" id="fileselect" name="fileselect[]" multiple="multiple" /> Upload Files

References:
 * PHP: move_uploaded_file - Manual - http://php.net/manual/en/function.move-uploaded-file.php
 * How to Asynchronously Upload Files Using HTML5 and Ajax - SitePoint - http://www.sitepoint.com/html5-ajax-file-upload/

Editors
Requirements:
 * Syntax Highlighting
 * Function reference
 * Function completion

Wants:
 * Jump to function
 * HTML page view

Lists:
 * PHP Editor Review
 * List of PHP editors - Wikipedia
 * Seven great PHP IDEs compared

NetBeans:
 * PHP NetBeans
 * NetBeans PHP IDE | VT's Tech Blog
 * php: Installing and configuring PHP, Apache, and MySQL for PHP development in Windows
 * PHP Learning Trail - NetBeans IDE Tutorials, Guides and Articles
 * Debugging PHP Source Code in the NetBeans IDE for PHP Editor
 * php: Installing and configuring PHP, Apache, and MySQL for PHP development in Windows
 * FTP only (no SFTP)

Eclipse:
 * Eclipse
 * Eclipse PHP Integrated Development Environment (proposal only)
 * Eclipse (good solution)
 * Download Classic version, then install PHPEclipse plugin
 * PHPEclipse
 * SourceForge.net: PHPeclipse - PHP Eclipse-Plugin
 * Installation - PHPEclipse
 * Zend Studio for Eclipse ($400)
 * SFTP Plug-in for Eclipse
 * Eclipse SFTP Plugin (ESftp) - Homepage
 * Eclipse SFTP Plugin (ESftp) - Homepage (redirected)
 * Eclipse SFTP Plugin (ESftp) - Sourceforge site

Increasing Available Memory
The default memory limit is about 8MB: PHP Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate ... bytes) in ...


 * Increase memory in your php.ini
 * PHP Allowed Memory Size Exchausted Fatal Error

Executing External Applications

 * Execution Operators
 * Description: PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec.
 * Example: $output = `ls -al`;
 * exec
 * Description: exec — Execute an external program
 * Syntax: string exec ( string $command [, array &$output [, int &$return_var]] )
 * Return Values: The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru function.
 * Example: echo exec('whoami');
 * system
 * Description: system — Execute an external program and display the output
 * Syntax: string system ( string $command [, int &$return_var] )
 * Return Values: Returns the last line of the command output on success, and FALSE on failure.
 * Example: $last_line = system('ls', $retval);
 * passthru
 * Description: passthru — Execute an external program and display raw output
 * Syntax: void passthru ( string $command [, int &$return_var] )
 * Return Values: No value is returned.
 * shell_exec
 * Description: shell_exec — Execute command via shell and return the complete output as a string
 * Return Values: The output from the executed command.
 * Example: $output = shell_exec('ls -lart');

Crypt
crypt $secret = "password"; $crypt_secret = crypt($secret); $salt = substr($crypt_secret, 0, 2); ... $user_input = $_POST["password"] if( crypt( $user_input, $salt ) == $crypt_secret ) echo "correct password"; # or if( crypt( $user_input, $crypt_secret ) == $crypt_secret ) echo "correct password";

MD5
md5 $secret = "password"; $hash = md5($secret); ... if( md5($user_input) == $hash ) echo "correct password";

Command Line PHP
PHP.net: Using PHP from the command line

Arguments: $argc - count of arguments $argv[] - arguments array
 * As of PHP 4.3.0, the PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI.

STDIN: $stdin = fopen('php://stdin', 'r'); STDOUT: $stdout = fopen('php://stdout', 'w'); STDERR: $stderr = fopen('php://stderr', 'w');
 * You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

File Header:
 * 1) !/usr/bin/php

Optimizing PHP

 * A HOWTO on Optimizing PHP
 * Lazy PHP: Part 1


 * Fastest languages for memcached

PHP vs Python vs Perl

 * The real difference between PHP and Python
 * Python vs. PHP
 * PHP vs. Python vs. Perl
 * Fastest languages for memcached
 * Python vs PHP
 * Java versus PHP versus Python versus Ruby - Job Comparison
 * Python vs Ruby
 * PHP vs. Python

PHP Frameworks
See PHP Frameworks

HTTP Authentication
PHP: HTTP authentication with PHP - Manual

Example #1 Basic HTTP Authentication example: <?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo " Hello {$_SERVER['PHP_AUTH_USER']}. "; echo " You entered {$_SERVER['PHP_AUTH_PW']} as your password. "; } ?>

Example #2 Digest HTTP Authentication example
 * See http://us3.php.net/features.http-auth

HTTP Redirect
<?php header('Location: http://www.google.com/'); ?>

Over the top: <?php header('HTTP/1.1 301 Moved Permanently'); header('Location: http://www.google.com/'); ?> <meta http-equiv="REFRESH" content="0; url=http://www.google.com/" /> Please follow <a href="http://www.google.com/">this link</a>.

Logging to Apache
PHP: error_log - Manual error_log("Oracle database not available!");

Backtrace
Similar to Java's Stack Trace:

PHP: debug_backtrace - Manual var_dump(debug_backtrace);

Here Document
PHP heredoc: $xmlstr = <<<XML <?xml version='1.0' standalone='yes'?> PHP: Behind the Parser XML;

xml
PHP: SimpleXML - Manual

PHP: SimpleXMLElement - Manual

Example: <?php

$xmlstr = <<<XML <?xml version='1.0' standalone='yes'?> PHP: Behind the Parser Ms. Coder Onlivia Actora Mr. Coder El Act&#211;r So, this language. It's like, a programming language. Or is it a  scripting language? All is revealed in this thrilling horror spoof of a documentary. <great-lines> PHP solves all my web problems </great-lines> 7  5 XML;

$xml = new SimpleXMLElement($xmlstr);

// or //if(!$xml=simplexml_load_file('users.xml')){ //   trigger_error('Error reading XML file',E_USER_ERROR); //}

function dospecial($xml) { // Example of printing entity value if ($xml->getName == "line") { // method #1 echo "::Value: ". $xml. "\n\n"; } if ($xml->getName == "character") { // method #2 echo "::Value:(name) ". $xml->name. "\n\n"; } // Example of printing entity attribute if ($xml->getName == "rating") { // method #1 echo "::Attribute:(type) ". $xml["type"]. "\n\n"; // method #2 foreach($xml->attributes as $name => $value) { echo "::Attribute:(" . $name . ") ". $value. "\n\n"; } } }

// Walk the XML tree function nav($xml, $space) { $space .= " - "; echo $space. $xml->getName. "\n\n"; dospecial($xml); foreach ($xml->children as $node) { nav($node, $space); } }

$space=""; echo " "; nav($xml, $space); echo " ";

Flush Buffer to Browser
httpd.conf: DocumentRoot /www/admin <Directory /> AllowOverride All </Directory>

.htaccess: php_value output_buffering "0"

code.php: ob_start;

echo str_pad('Loading... ',4096)." \n";

for($i=0;$i<70;$i++) {   echo 'printing... ';   ob_flush; flush;

usleep(3000000); } ?>

References: PHP: ob_flush - Manual

Windows IIS Installation

 * 1) Install IIS
 * 2) Install FastCGI for IIS:
 * http://www.iis.net/download/fastcgi
 * 1) Install PHP (Select IIS FastCGI)

PHP Lint
Syntax check only (lint): php -l script.php

Minimal HTTP Header Signature
/etc/php.ini expose_php = Off

References:
 * Hide Apache ServerSignature/ServerTokens/PHP X-Powered-By - http://www.if-not-true-then-false.com/2009/howto-hide-and-modify-apache-server-information-serversignature-and-servertokens-and-hide-php-version-x-powered-by/

GD
Install: yum install php-gd gd

Test: php -r 'print_r(gd_info);'

Issues
Error: PHP Warning: POST Content-Length of [N] bytes exceeds the limit of [N] bytes in Unknown on line 0

Solution: (php.ini) memory_limit = 128M post_max_size = 3M upload_max_filesize = 500K

References:
 * PHP Warning: POST Content-Length of n bytes exceeds the limit of 3145728 bytes in Unknown on line 0 - Stack Overflow - http://stackoverflow.com/questions/11738949/php-warning-post-content-length-of-n-bytes-exceeds-the-limit-of-3145728-bytes-i