PHP

From Omnia
Jump to navigation Jump to search

PHP

Code

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: [1]

> (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: [2]

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: [3]

strtolower( string $str );

Upper case: [4]

strtoupper( string $str );

Heredoc: [5]

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
This variable is evaluated: $var
EOD;

phpinfo

phpinfo - http://php.net/manual/en/function.phpinfo.php

phpinfo();

To see if mysql is supported:

echo "<?php phpinfo(); ?>" | php | grep -i "mysql support"

file io

fopen — Opens file or URL: [6]

# resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
$handle = fopen("/home/rasmus/file.txt", "r");

<pr> 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: [7]

# int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
readfile( $file );

file — Reads entire file into an array: [8]

# array file ( string $filename [, int $flags = 0 [, resource $context ]] )
$lines = file('http://www.example.com/');

fread — Binary-safe file read: [9]

# 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: [10]

# 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 [11]

# string date ( string $format [, int $timestamp = time() ] )
$strdate = date('Y-m-d');
# 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)

<h1><font color="red">Unauthorized!</font></h1>
<!--
HTTP_HOST:			<?php echo $_SERVER["HTTP_HOST"]       ?> 
SERVER_NAME:		<?php echo $_SERVER["SERVER_NAME"]     ?> 
SERVER_ADDR:		<?php echo $_SERVER["SERVER_ADDR"]     ?> 
REMOTE_ADDR:		<?php echo $_SERVER["REMOTE_ADDR"]     ?> 
DOCUMENT_ROOT:		<?php echo $_SERVER["DOCUMENT_ROOT"]   ?> 
SCRIPT_FILENAME:	<?php echo $_SERVER["SCRIPT_FILENAME"] ?> 
REQUEST_METHOD:		<?php echo $_SERVER["REQUEST_METHOD"]  ?> 
SCRIPT_NAME:		<?php echo $_SERVER["SCRIPT_NAME"]     ?> 
PHP_SELF:			<?php echo $_SERVER["PHP_SELF"]        ?> 
-->

Regular Expression

Match: [12]

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

$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)

# string exec ( string $command [, array &$output [, int &$return_var ]] )
$lastline = exec( $command, $output, $return_var );
exec( $command, $output = array() ); 

passthru — Execute an external program and display raw output: (output to buffer)

# void passthru ( string $command [, int &$return_var ] )
passthru( $command, $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 [13]

# 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@example.com>
   User <user@example.com>, Another User <anotheruser@example.com>

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 <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\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 ---

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->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"]. "<br>";
    }
} 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 "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\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

---

Sockets

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)<br />\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);
}

Advanced Code

Upload Single File

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Build ESX ISO</title>
    <meta charset="utf-8"/>
  </head>
  <body>

<?php 

$upload_file = $_FILES['fileselect'];
// $upload_file is array of:
// [name] => 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 "<p>UPLOAD SUCCESS: $fn</p>";
        } else {
            echo "<p>UPLOAD FAILURE: $fn</p>";
        }
    }  
}  

?>

<form id="upload" action="single.php" method="POST" enctype="multipart/form-data">  
<fieldset>  
<legend>HTML File Upload</legend>  
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />  
<div>  
    <label for="fileselect">File to upload:</label>  
    <input type="file" id="fileselect" name="fileselect" />  
</div>  
<div id="submitbutton">  
    <button type="submit">Upload File</button>  
</div>  
</fieldset>  
</form>

  </body>
</html>

References:

Upload Multiple Files

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>untitled</title>
    <meta charset="utf-8"/>
  </head>
  <body>

<?php 

// Note: Make sure to create an 'uploads/' folder next to this script
// and give apache permissions to write to it.

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

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

  </body>
</html>

References:

Editors

Requirements:

  • Syntax Highlighting
  • Function reference
  • Function completion

Wants:

  • Jump to function
  • HTML page view


Lists:


NetBeans:


Eclipse:

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 ...

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 and MD5

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:

  • 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.
$argc - count of arguments
$argv[] - arguments array

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:

#!/usr/bin/php

Optimizing PHP


PHP vs Python vs Perl

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 "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP Authentication example

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/');
?>
<html>
<head>
<meta http-equiv="REFRESH" content="0; url=http://www.google.com/" />
<body>
<p>Please follow <a href="http://www.google.com/">this link</a>.</p>
</body>
</html>

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'?>
<movies>
 <movie name="joe">
  <title>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

xml

PHP: SimpleXML - Manual

PHP: SimpleXMLElement - Manual

Example:

<?php


$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie name="joe">
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El ActÓr</actor>
   </character>
  </characters>
  <plot>
   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.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
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 "<pre>";
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)."<br />\n";

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

    usleep(3000000);
}
?>

References: PHP: ob_flush - Manual

Windows IIS Installation

  1. Install IIS
  2. Install FastCGI for IIS:
  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:

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:

keywords