Questions about this topic? Sign up to ask in the talk tab.

Difference between revisions of "PHP"

From NetSec
Jump to: navigation, search
(Variables)
 
(43 intermediate revisions by 6 users not shown)
Line 1: Line 1:
PHP is one of many [[interpreted languages]] written in [[C]].
+
<b>P</b>HP <b>H</b>ypertext <b>P</b>reprocessor Language is a server side [[interpreted languages|interpreted language]] written in [[C]] that runs primarily on [[Linux]] environments. PHP scripts can be run directly or served as webpages.
 +
 
 
=Development Environment=
 
=Development Environment=
==PHP CLI==
+
 
 +
== PHP CLI ==
 
{{quote|Many [[Linux]] distributions package the [[PHP]] CLI separately|Xochipilli}}
 
{{quote|Many [[Linux]] distributions package the [[PHP]] CLI separately|Xochipilli}}
  
* php -l check syntax
+
*To check the syntax of a PHP file (lint):
* php -v version
+
* php -e oneliner
+
  
==Pear/Pecl==
+
  {{LinuxCMD|php -l /path/to/script.php}}
  
=Your first application=
+
* ''Short for:''
=Variables and data types=
+
{{code|text=<source lang="bash">  php --syntax-check /path/to/script.php</source>}}
[[PHP]] is a dynamically typed language.
+
=Boolean Logic=
+
==Ternary Conditionals==
+
=Loops=
+
=User Input=
+
=User-Defined Functions=
+
  
Defining functions in [[PHP]] is accomplished using the function keyword, followed by the function name and comma delimited arguments, surrounded by parenthesis:
+
* To check the syntax of all of the php files in the cwd (current working directory) :
 +
 
 +
  {{LinuxCMD|find $(pwd) -name \*.php -exec php -l '{}' \;}}
 +
 
 +
*To see the current version of PHP (CLI):
 +
 
 +
  {{LinuxCMD|php -v}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --version</source>}}
 +
 
 +
*To execute PHP code via CLI (without PHP tags):
 +
 
 +
  {{LinuxCMD|php -r 'PHP CODE HERE'}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --run 'PHP CODE HERE'</source>}}
 +
 
 +
{{Notice|You do not need to enclose the code in PHP begin and end tags, but you must single quote the code, so strings must be double quoted inside of it.}}
 +
 
 +
*To define variables while running a PHP script:
 +
 
 +
  {{LinuxCMD|php -d foo=bar /path/to/script.php}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --define foo=bar /path/to/script.php</source>}}
 +
 
 +
*To run a script silently:
 +
 
 +
  {{LinuxCMD|php -q /path/to/silent_script.php}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --no-header /path/to/silent_script.php</source>}}
 +
 
 +
{{Info|This will suppress HTTP header output, so this is CGI only.}}
 +
 
 +
*To load a Zend extension for use with a script in CLI:
 +
 
 +
  {{LinuxCMD|php -z /path/to/zend/extension.so /path/to/script.php}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --zend-extension /path/to/zend/extension.so /path/to/script.php</source>}}
 +
 
 +
*To see a list of modules that PHP CLI has loaded:
 +
 
 +
  {{LinuxCMD|php -m}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --modules</source>}}
 +
 
 +
*To benchmark execution times of a script N times:
 +
 
 +
  {{LinuxCMD|php -T TIMES /path/to/script.php}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --timing '''TIMES''' /path/to/script.php</source>}}
 +
 
 +
*To generate extended information for debugging or profiling:
 +
 
 +
  php -e /path/to/script.php
 +
 
 +
*To hide sensitive arguments from external tools:
 +
 
 +
  {{LinuxCMD|php -H -d mypassword=blah -d myuser=user /path/to/script.php}}
 +
 
 +
* ''Short for:''
 +
{{code|text=<source lang="bash">  php --hide-args -d mypassword=blah -d myuser=user /path/to/script.php</source>}}
 +
 
 +
== PEAR/PECL ==
 +
 
 +
[http://pear.php.net/ PEAR] and [http://pecl.php.net/ PECL] are repositories for re-usable PHP libraries and code for common tasks.  Below are links to lists of packages that are available for use:
 +
 
 +
*[http://pecl.php.net/packages.php PECL :: Package Browser]
 +
*[http://pear.php.net/packages.php PEAR Packages]
 +
 
 +
== Development PHP.INI ==
 +
 
 +
For use in development environments, you will want to rid your code of any and all errors which might disclose information about your setup.  To assist you in doing this, there are a few variables in PHP.INI that might be helpful:
 +
 
 +
  error_reporting=8192
 +
  display_errors=On
 +
  display_startup_errors=On
 +
  log_errors=On
 +
  error_log=error_log
 +
  report_memleaks=On
 +
  expose_php=On
 +
  asp_tags=Off
 +
 
 +
{{Notice|We turn asp_tags Off because valid PHP code headers should be used anyway, in case asp_tags is Off in production, which it should be.}}
 +
 
 +
= PHP Basics =
 +
 
 +
== Variables ==
 +
 
 +
A variable is how you store a value such as a string or integer.  An example where a variable would be used is if you wanted to handle a string multiple times throughout your application.  Here is an example of a variable and how it can be used:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
$variable = "NetSec ";
 +
$variable1 = "Rules!";
 +
echo "$variable $variable1";
 +
?>
 +
</source>}}
 +
 
 +
This snippet of code will display the following:
 +
  NetSec Rules!
 +
 
 +
== Operators ==
 +
 
 +
Operators are used to compare variables, mathematics, and more.  For example, you can set a variable equal to another variable using the '=' operator.
 +
 
 +
*List of operators:
 +
 
 +
  + - Addition
 +
  - - Subtraction
 +
  * - Multiplication
 +
  / - Division
 +
  % - Modulus
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
$add = 1 + 1;
 +
$subtract = 5 - 2;
 +
$multiply = 6 * 5;
 +
$divide = 14/7;
 +
$modulus = 5 % 2;
 +
 
 +
echo "1 + 1 = $add";
 +
echo "5 - 2 = $subtract";
 +
echo "6 * 5 = $multiply";
 +
echo "14 / 7 = $divide";
 +
echo "5 % 2 = $modulus";
 +
?>
 +
</source>}}
 +
 
 +
Comparison operators are used to evaluate true or false when comparing variables and/or values
 +
 
 +
*List of comparison operators:
 +
 
 +
  == - Equal To
 +
  != - Not Equal To
 +
  < - Less than
 +
  > - Greater than
 +
  <= - Less Than or Equal To
 +
  >= - Greater Than or Equal To
 +
 
 +
== Data Types ==
 +
 
 +
[[PHP]] is a dynamically-typed language, consisting of '''integers''', '''arrays''', '''associative arrays''', '''strings''', and '''classes'''.
 +
 
 +
=== Integers ===
 +
 
 +
In PHP, variables can be casted as an integer simply by assigning the variable a numeric value, such as:
 +
 
 +
{{code|text=<source lang="php"><?php
 +
    $var = 1;
 +
?></source>}}
 +
 
 +
=== Strings ===
 +
 
 +
String type will automatically be set if the variable has <nowiki>''</nowiki> or <nowiki>""</nowiki> surrounding the value.
 +
 
 +
{{code|text=<source lang="php"><?php
 +
  $str = "string here";
 +
?></source>}}
 +
 
 +
=== Arrays ===
 +
 
 +
Arrays are of the 'mixed' type, that is to say, you can adjoin elements of any type inside of an array, and even associative arrays if you wanted.  Some examples are:
 +
 
 +
{{code|text=<source lang="php"><?php
 +
  $arrA = array(1, 2, 3);
 +
  $arrB = array('1', '2', '3');
 +
  $arrC = array(1, '2', 3, '4');
 +
?></source>}}
 +
 
 +
=== Associative Arrays ===
 +
 
 +
Similar to other languages, PHP can hold key => value pairs inside of an array object, like so:
 +
 
 +
{{code|text=<source lang="php"><?php
 +
  $asArrA = array(
 +
    'a' => 1,
 +
    'b' => '1',
 +
    'c' => array(1,2,3),
 +
    'd' => $arrC
 +
  );
 +
?></source>}}
 +
 
 +
Above is the more readable way to create an associate array.  There is also direct assignment upon initialization like so:
 +
 
 +
{{code|text=<source lang="php"><?php
 +
  $asArrB['a'] = $arrA;  // [a] => array(1,2,3);
 +
  $asArrB['b'] = $arrB    // [b] => array('1','2','3');
 +
  $asArrB['c'] = $arrC;  // [c] => array(1,'2',3,'4');
 +
  $asArrB['d'] = $asArrA; // [d] => ([a] => 1, [b] => '1', ...)
 +
?></source>}}
 +
 
 +
=== Classes ===
 +
 
 +
Classes are a way of defining custom datatypes and function libraries for PHP code.  Most of PEAR and PECL is designed this way so as to import functions using OOP or Object-Oriented Programming.
 +
 
 +
Here's an example of a class:
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
class MyClass {
 +
 
 +
  public $version = 1.0;
 +
  public $mystr  = 'hello world';
 +
 
 +
  public function PrintHello() {
 +
    print $this->mystr . "\n";
 +
  }
  
{{code
 
|text=
 
<source lang="php">
 
function myFunction(arg1, arg2) {
 
...
 
 
}
 
}
</source>
+
?>
}}
+
</source>}}
 +
 
 +
So, to actually use this class, it has to exist prior to instanciation of an object with that classes name.  Usually, a programmer might save the file with the class definition as: '''./classes/class.MyClass.php''' but there are several heirarchies in which to guide your filename decisions.  This is beyond the scope of this article, so the structure will be left as an excercise to the reader.
 +
 
 +
Some example inclusion and usage:
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
require_once 'classes/class.MyClass.php';
 +
$foo = new MyClass;
 +
$foo->PrintHello();
 +
?>
 +
</source>}}
 +
 
 +
==== Arrow Operator ====
 +
 
 +
When accessing the methods (functions) and properties (class variables) of a class, you will be using the Arrow Operator '''->'''
 +
 
 +
This is put between the instanciated variable and the method or property, like so:
 +
 
 +
{{code|text=<source lang="php"><?php
 +
  print $foo->mystr;
 +
  $foo->PrintHello();
 +
?></source>}}
 +
 
 +
==== Scope Resolution Operator ====
 +
 
 +
This operator will let you access methods and constants defined inside of a class, or from inside of a class.
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
class MyClass2 {
 +
  const MY_STRING = 'hello world';
 +
}
 +
?>
 +
</source>}}
 +
 
 +
From here, as long as the class is loaded, the properties of MyClass2 are available outside of the class via the Scope Resolution Operator, as shown below:
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
require_once './classes/class.MyClass2.php';
 +
echo MyClass2::MY_STRING;
 +
?>
 +
</source>}}
 +
 
 +
==== Extending Classes ====
 +
 
 +
In many cases, there may be a need to extend the functionality of a generic or Base class, with functions from a new class.  To facilitate this, you can use the '''extends''' class keyword.  Here a Base class is defined:
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
class Base {
 +
  public $strA = 'hello world';
 +
  public $strB = 'peekaboo';
 +
}
 +
?>
 +
</source>}}
 +
 
 +
There we have our Base class, which holds two public strings, so let's create an extension of that class to print them using the '''extends''' keyword:
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
class Printer extends Base {
 +
  public function PrintBase() {
 +
    print parent::strA;
 +
    print parent::strB;
 +
  }
 +
  public function PrinterPrintBase() {
 +
    print $this->strA;
 +
    print $this->strB;
 +
  }
 +
}
 +
?>
 +
</source>}}
 +
 
 +
Now, instead of just instanciating the Base class, you can instanciate the Printer class instead, which will inherit the values and functions of the Base class, with the added variables and functions of the Printer class.
 +
 
 +
{{code|text=<source lang='php'>
 +
<?php
 +
require_once './classes/class.Base.php';
 +
require_once './classes/class.Printer.php';
 +
$foo = new Printer;
 +
$foo->PrintBase();
 +
// This will output 'hello world' and 'peekaboo' from the Base class.
 +
$foo->PrinterPrintBase();
 +
// Because $strA and $strB were inherited from the Base class, you can now reference them using the Arrow Operator.
 +
?>
 +
</source>}}
 +
 
 +
The special name '''parent::''' refers to the class from which your instanciated class was derived.  Parent should be used in the case that your inheritance tree changes, so you will not have to go replace all references to a singular class name.
 +
 
 +
== Functions ==
 +
 
 +
Defining functions in [[PHP]] is accomplished using the '''function''' keyword, followed by the function name and comma delimited arguments, surrounded by parenthesis:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
function myFunction($arg1, $arg2) {
 +
  // your function code here
 +
}
 +
?>
 +
</source>}}
 +
 
 +
You may also wish to have default values for variables if none are passed for the particular argument:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
function myFunction($arg1, $arg2 = '') {
 +
  // your function code here
 +
  // if myFunction() is called with only one argument passed, $arg2 will automatically be set to ''
 +
  // if myFunction() is called with two arguments, $arg2 will inherit the value of the 2nd argument passed
 +
}
 +
?>
 +
</source>}}
  
 
If the function is encapsulated in an object, you may specify the visibility of the function, public, protected or private.
 
If the function is encapsulated in an object, you may specify the visibility of the function, public, protected or private.
  
{{code
+
{{code|text=<source lang="php">
|text=
+
<?php
<source lang="php">
+
 
class MyClass
 
class MyClass
 
{
 
{
     public function myFunction(arg1, arg2) {
+
     public function myFunction($arg1, $arg2) {
    ...
+
      // myFunction code here
 
     }
 
     }
...
 
 
}
 
}
</source>
+
?>
}}
+
</source>}}
  
Unlike languages, such as [[Perl]] or [[Python]], [[PHP]] member functions implicitly extract their parent into the $this variable.
+
The above class will enable the use of such code as:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
$foo = new MyClass;
 +
$foo->myFunction('bar');
 +
$foo->myFunction('bar', 'baz');
 +
?>
 +
</source>}}
 +
 
 +
Unlike some programming languages, like [[Perl]] or [[Python]], [[PHP]] member functions implicitly extract their parent into the $this variable.
 +
 
 +
== Boolean Logic ==
 +
 
 +
=== Ternary Conditionals ===
 +
 
 +
In PHP, if else statements typically look like this:
 +
 
 +
{{code|text=<source lang="php">
 +
if( $a == $b ) {
 +
    print "Equal!";
 +
}
 +
else {
 +
    print "Not Equal!";
 +
}
 +
</source>}}
 +
 
 +
However, there is shorthand for this called a Ternary conditional. We can write the same
 +
if else statement like this:
 +
 
 +
{{code|text=<source lang="php">
 +
($a == $b) ? print "Equal!" : print "Not Equal!";
 +
</source>}}
 +
 
 +
Where the general form is:
 +
 
 +
{{code|text=<source lang="php">
 +
(condition) ? if condition is true : if condition is false;
 +
</source>}}
 +
 
 +
== Loops ==
 +
 
 +
PHP has four main types of loops.
 +
 
 +
=== for ===
 +
 
 +
This loop is good for performing a set of instructions a set number of times. For example:
 +
 
 +
{{code|text=<source lang="php">
 +
for($i=0; $i<5; $i++) {
 +
    print "i = " . $i . "\n";
 +
}
 +
</source>}}
 +
 
 +
The above will print the value of i 5 times and the values will be:
 +
 
 +
    i = 0
 +
    i = 1
 +
    i = 2
 +
    i = 3
 +
    i = 4
 +
 
 +
=== foreach ===
 +
 
 +
This is probably the most common loop in all of PHP. It makes going through the elements of an array really easy.
 +
For example:
 +
 
 +
{{code|text=<source lang="php">
 +
$names = array("Jack", "Jill", "Mike", "Sally", "Steve");
 +
 
 +
foreach($names as $name) {
 +
    print $name . "\n";
 +
}
 +
 
 +
</source>}}
 +
 
 +
The output of this code will be
 +
 
 +
  Jack
 +
  Jill
 +
  Mike
 +
  Sally
 +
  Steve
 +
 
 +
Another really neat thing you could have done with this is the following:
 +
 
 +
{{code|text=<source lang="php">
 +
$names = array("Jack", "Jill", "Mike", "Sally", "Steve");
 +
 
 +
foreach($names as $key => $name) {
 +
    print "Entry #: " . $key . " Name = " . $name . "\n";
 +
}
 +
 
 +
</source>}}
 +
 
 +
The output will be:
 +
 
 +
  Entry #: 0 Name = Jack
 +
  Entry #: 1 Name = Jill
 +
  Entry #: 2 Name = Mike
 +
  Entry #: 3 Name = Sally
 +
  Entry #: 4 Name = Steve
 +
 
 +
Notice that in this example we define a $key. This key tells us what index of the array we are on. This is especially powerful when you use associative arrays like this:
 +
 
 +
{{code|text=<source lang="php">
 +
$names = array("Manager" => "Jack", "Sales" => "Jill", "Accounting" => "Mike", "HR" => "Sally", "CEO" => "Steve");
 +
 
 +
foreach($names as $key => $name) {
 +
    print "Position: " . $key . " Name = " . $name . "\n";
 +
}
 +
</source>}}
 +
 
 +
  Position: Manager Name = Jack
 +
  Position: Sales Name = Jill
 +
  Position: Accounting Name = Mike
 +
  Position: HR Name = Sally
 +
  Position: CEO Name = Steve
 +
 
 +
=== while ===
 +
 
 +
The while loop is probably the most simple of them all. In it's most basic form:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
while( true statement ) {
 +
  // do something
 +
}
 +
?>
 +
</source>}}
 +
 
 +
In this case, while "true statement" remains true, we will keep looping. For example:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
$i = 5;
 +
while( $i < 10 ) {
 +
  $i = $i + 1; // This could be shortened to $i++; But I'm being intentionally verbose.
 +
}
 +
?>
 +
</source>}}
 +
 
 +
The above code will continue to add 1 to $i until $i = 10, at which point the loop will stop. $i will retain it's value of 10.
 +
 
 +
Alternatively, there is another syntax for while:
 +
 
 +
{{code|text=<source lang="php">
 +
<?php
 +
while(expr):
 +
  // do something
 +
endwhile;
 +
?>
 +
</source>}}
 +
 
 +
Within the loop, there are of course ways of skipping and breaking out of the loop completely, they are:
 +
 
 +
  break;
 +
 
 +
Which will break out of the while() loop completely.
 +
 
 +
  continue;
 +
 
 +
Which will skip to the end of the current iteration and run through to the next iteration.
 +
 
 +
=== do-while ===
 +
 
 +
This loop is very similar to the while loop. Example:
 +
 
 +
{{code|text=<source lang="php">
 +
$a = 0;
 +
do {
 +
    print "Hello: " . $a . "\n";
 +
    $a = $a + 1;
 +
} while( $a < 5);
 +
</source>}}
 +
 
 +
The output of this will be:
 +
 
 +
  Hello: 0
 +
  Hello: 1
 +
  Hello: 2
 +
  Hello: 3
 +
  Hello: 4
 +
 
 +
 
 +
There is one major difference between the while and the do-while: The condition is evaluated AFTER the code is run. In a normal while loop, the condition is evaluated '''BEFORE''' the code in the  { } is run. So for example
 +
 
 +
With a normal while loop:
 +
 
 +
{{code|text=<source lang="php">
 +
while( 1 == 0) {
 +
    print "Hello!";
 +
}
 +
</source>}}
 +
 
 +
In this case "Hello" never gets printed because "1 == 0" gets evaluated BEFORE the code within the braces gets executed.
 +
 
 +
However, this changes in the following do-while example:
 +
 
 +
{{code|text=<source lang="php">
 +
do {
 +
    print "Hello!";
 +
} while( 1 == 0);
 +
</source>}}
 +
 
 +
The word "Hello" will get executed exactly once because the condition "1 == 0" gets executed AFTER the code between the braces is executed.
 +
 
 +
== User Input ==
  
 
=Security=
 
=Security=
* Type Handling
+
===code===
* XSS
+
==== Dangerous functions ====
* SQL Injection
+
:*include()
 +
:*eval()
 +
:*mysql_query()
 +
:*pgsql_query()
 +
:*phpinfo()
 +
:*system()
  
Preventing [[SQL injection]] in [[PHP]] applications is relatively simple, so long as you are thorough. String input, surrounded by single quotes can be sanitized with [http://php.net/manual/en/function.mysql-real-escape-string.php mysql_real_escape_string()], which will escape dangerous characters such as single quotes (as well as \, so that you cannot escape the escapes!). Sanitizing integer input can be done simply by casting the input to int, like so:
+
==== Dangerous practices ====
 +
:*include()
 +
:*echo(), print(), sprintf()
 +
:*string sanitizing using non-recursive string replacement
 +
:*improper type handling
  
 +
==== Best practices ====
 +
'''The Golden Rule''': Treat all user input as if it's malicious. Anything that gets transferred from the browser to the server (session variable especially) is a new vector for attacking your web app.
 +
 +
* File inclusion
 +
 +
* Type Handling
 
{{code
 
{{code
 
|text=
 
|text=
Line 60: Line 596:
 
</source>
 
</source>
 
}}
 
}}
 +
 +
* XSS
 +
 +
* SQL Injection
 +
 +
Preventing [[SQL injection]] in [[PHP]] applications is relatively simple, so long as you are thorough. String input, surrounded by single quotes can be sanitized with [http://php.net/manual/en/function.mysql-real-escape-string.php mysql_real_escape_string()], which will escape dangerous characters such as single quotes (as well as \, so that you cannot escape the escapes!). Sanitizing integer input can be done simply by casting the input to integer.
 +
 +
===php.ini===
 +
 +
= PHP-FPM =
 +
 +
PHP-FPM has been around since 2009, but is now in mainline PHP since 5.4.0RC2.  PHP-FPM is also known as FastCGI Process Manager, and does an excellent job at serving PHP powered content much more rapidly than mpm_worker/mpm_prefork on Apache.  The configuration for PHP-FPM is somewhat complex, but is really easy once you get used to it and finish customizing everything.  Take the following pool configuration for example:
 +
 +
<syntaxhighlight lang="ini">
 +
  [wordpress]
 +
  user = wordpress
 +
  group = www-data
 +
  listen = /var/run/php5-fpm/app.sock
 +
  listen.owner = wordpress
 +
  listen.group = www-data
 +
  listen.mode = 0666
 +
  chdir = /home/wordpress/web
 +
  pm = dynamic
 +
  pm.max_children = 50
 +
  pm.start_servers = 10
 +
  pm.min_spare_servers = 5
 +
  pm.max_spare_servers = 15
 +
  pm.max_requests = 1000
 +
  php_admin_value[memory_limit] = 96M
 +
  php_admin_value[session.save_path] = tcp://127.0.0.1:11211
 +
  php_admin_value[open_basedir] = /home/wordpress/web
 +
  php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,posix_mkfifo,pg_lo_import,dbmopen,dbase_open,popen,chgrp,chown,chmod,symlink
 +
  php_admin_value[disable_classes] = pBot
 +
  php_admin_value[post_max_size] = 100M
 +
  php_admin_value[upload_max_filesize] = 100M
 +
  php_admin_value[user_agent] = "WordPress (http://www.my-website.com)"
 +
</syntaxhighlight>
 +
 +
This will do a few things:
 +
 +
*Sets the UNIX socket (to be used with [[NGINX#Upstream_.28proxy.2Fload_balancer.29|NGINX]]'s upstream directive via '''unix:/var/run/php5-fpm/app.sock''')
 +
*Sets the UID/GID of the socket to be of the user, and group to www-data so NGINX can read it
 +
*Changes directory to '''/home/wordpress/web''' before execution, so everything is relative to that path.
 +
*Sets the Process Management model to Dynamic, which will tune the number of servers and workers based on usage
 +
*Sets session management to use Memcached over TCP (requires socket support)
 +
 +
{{Info|You can use TCP sockets to listen on instead of UNIX sockets, but that comes with it's own overhead, and you have to configure your firewall if it's not listening on localhost.  You have been advised.}}
 +
 +
[[Category:Programming Languages]]
 +
 +
See Also : [[PHP Patching]]
 +
 +
{{programming}}{{social}}
 +
 +
[[Category:Interpreted languages]]

Latest revision as of 05:00, 29 May 2015

PHP Hypertext Preprocessor Language is a server side interpreted language written in C that runs primarily on Linux environments. PHP scripts can be run directly or served as webpages.

Development Environment

PHP CLI

Xochipilli says
Many Linux distributions package the PHP CLI separately
  • To check the syntax of a PHP file (lint):
Terminal

localhost:~ $ php -l /path/to/script.php

  • Short for:
  php --syntax-check /path/to/script.php
  • To check the syntax of all of the php files in the cwd (current working directory) :
Terminal

localhost:~ $ find $(pwd) -name \*.php -exec php -l '{}' \;

  • To see the current version of PHP (CLI):
Terminal

localhost:~ $ php -v

  • Short for:
  php --version
  • To execute PHP code via CLI (without PHP tags):
Terminal

localhost:~ $ php -r 'PHP CODE HERE'

  • Short for:
  php --run 'PHP CODE HERE'
Notice: You do not need to enclose the code in PHP begin and end tags, but you must single quote the code, so strings must be double quoted inside of it.
  • To define variables while running a PHP script:
Terminal

localhost:~ $ {{{1}}}

  • Short for:
  php --define foo=bar /path/to/script.php
  • To run a script silently:
Terminal

localhost:~ $ php -q /path/to/silent_script.php

  • Short for:
  php --no-header /path/to/silent_script.php
c3el4.png This will suppress HTTP header output, so this is CGI only.
  • To load a Zend extension for use with a script in CLI:
Terminal

localhost:~ $ php -z /path/to/zend/extension.so /path/to/script.php

  • Short for:
  php --zend-extension /path/to/zend/extension.so /path/to/script.php
  • To see a list of modules that PHP CLI has loaded:
Terminal

localhost:~ $ php -m

  • Short for:
  php --modules
  • To benchmark execution times of a script N times:
Terminal

localhost:~ $ php -T TIMES /path/to/script.php

  • Short for:
  php --timing '''TIMES''' /path/to/script.php
  • To generate extended information for debugging or profiling:
 php -e /path/to/script.php
  • To hide sensitive arguments from external tools:
Terminal

localhost:~ $ {{{1}}}

  • Short for:
  php --hide-args -d mypassword=blah -d myuser=user /path/to/script.php

PEAR/PECL

PEAR and PECL are repositories for re-usable PHP libraries and code for common tasks. Below are links to lists of packages that are available for use:

Development PHP.INI

For use in development environments, you will want to rid your code of any and all errors which might disclose information about your setup. To assist you in doing this, there are a few variables in PHP.INI that might be helpful:

 error_reporting=8192
 display_errors=On
 display_startup_errors=On
 log_errors=On
 error_log=error_log
 report_memleaks=On
 expose_php=On
 asp_tags=Off
Notice: We turn asp_tags Off because valid PHP code headers should be used anyway, in case asp_tags is Off in production, which it should be.

PHP Basics

Variables

A variable is how you store a value such as a string or integer. An example where a variable would be used is if you wanted to handle a string multiple times throughout your application. Here is an example of a variable and how it can be used:

 
<?php
$variable = "NetSec ";
$variable1 = "Rules!";
echo "$variable $variable1";
?>
 

This snippet of code will display the following:

 NetSec Rules!

Operators

Operators are used to compare variables, mathematics, and more. For example, you can set a variable equal to another variable using the '=' operator.

  • List of operators:
 + - Addition
 - - Subtraction
 * - Multiplication
 / - Division
 % - Modulus
 
<?php
$add = 1 + 1;
$subtract = 5 - 2;
$multiply = 6 * 5;
$divide = 14/7;
$modulus = 5 % 2;
 
echo "1 + 1 = $add";
echo "5 - 2 = $subtract";
echo "6 * 5 = $multiply";
echo "14 / 7 = $divide";
echo "5 % 2 = $modulus";
?>
 

Comparison operators are used to evaluate true or false when comparing variables and/or values

  • List of comparison operators:
 == - Equal To
 != - Not Equal To
 < - Less than
 > - Greater than
 <= - Less Than or Equal To
 >= - Greater Than or Equal To

Data Types

PHP is a dynamically-typed language, consisting of integers, arrays, associative arrays, strings, and classes.

Integers

In PHP, variables can be casted as an integer simply by assigning the variable a numeric value, such as:

<?php
    $var = 1;
?>

Strings

String type will automatically be set if the variable has '' or "" surrounding the value.

<?php
  $str = "string here";
?>

Arrays

Arrays are of the 'mixed' type, that is to say, you can adjoin elements of any type inside of an array, and even associative arrays if you wanted. Some examples are:

<?php
  $arrA = array(1, 2, 3);
  $arrB = array('1', '2', '3');
  $arrC = array(1, '2', 3, '4');
?>

Associative Arrays

Similar to other languages, PHP can hold key => value pairs inside of an array object, like so:

<?php
  $asArrA = array(
    'a' => 1,
    'b' => '1',
    'c' => array(1,2,3),
    'd' => $arrC
  );
?>

Above is the more readable way to create an associate array. There is also direct assignment upon initialization like so:

<?php
  $asArrB['a'] = $arrA;   // [a] => array(1,2,3);
  $asArrB['b'] = $arrB    // [b] => array('1','2','3');
  $asArrB['c'] = $arrC;   // [c] => array(1,'2',3,'4');
  $asArrB['d'] = $asArrA; // [d] => ([a] => 1, [b] => '1', ...)
?>

Classes

Classes are a way of defining custom datatypes and function libraries for PHP code. Most of PEAR and PECL is designed this way so as to import functions using OOP or Object-Oriented Programming.

Here's an example of a class:

 
<?php
class MyClass {
 
  public $version = 1.0;
  public $mystr   = 'hello world';
 
  public function PrintHello() {
    print $this->mystr . "\n";
  }
 
}
?>
 

So, to actually use this class, it has to exist prior to instanciation of an object with that classes name. Usually, a programmer might save the file with the class definition as: ./classes/class.MyClass.php but there are several heirarchies in which to guide your filename decisions. This is beyond the scope of this article, so the structure will be left as an excercise to the reader.

Some example inclusion and usage:

 
<?php
require_once 'classes/class.MyClass.php';
$foo = new MyClass;
$foo->PrintHello();
?>
 

Arrow Operator

When accessing the methods (functions) and properties (class variables) of a class, you will be using the Arrow Operator ->

This is put between the instanciated variable and the method or property, like so:

<?php
  print $foo->mystr;
  $foo->PrintHello();
?>

Scope Resolution Operator

This operator will let you access methods and constants defined inside of a class, or from inside of a class.

 
<?php
class MyClass2 {
  const MY_STRING = 'hello world';
}
?>
 

From here, as long as the class is loaded, the properties of MyClass2 are available outside of the class via the Scope Resolution Operator, as shown below:

 
<?php
require_once './classes/class.MyClass2.php';
echo MyClass2::MY_STRING;
?>
 

Extending Classes

In many cases, there may be a need to extend the functionality of a generic or Base class, with functions from a new class. To facilitate this, you can use the extends class keyword. Here a Base class is defined:

 
<?php
class Base {
  public $strA = 'hello world';
  public $strB = 'peekaboo';
}
?>
 

There we have our Base class, which holds two public strings, so let's create an extension of that class to print them using the extends keyword:

 
<?php
class Printer extends Base {
  public function PrintBase() {
    print parent::strA;
    print parent::strB;
  }
  public function PrinterPrintBase() {
    print $this->strA;
    print $this->strB;
  }
}
?>
 

Now, instead of just instanciating the Base class, you can instanciate the Printer class instead, which will inherit the values and functions of the Base class, with the added variables and functions of the Printer class.

 
<?php
require_once './classes/class.Base.php';
require_once './classes/class.Printer.php';
$foo = new Printer;
$foo->PrintBase();
// This will output 'hello world' and 'peekaboo' from the Base class.
$foo->PrinterPrintBase();
// Because $strA and $strB were inherited from the Base class, you can now reference them using the Arrow Operator.
?>
 

The special name parent:: refers to the class from which your instanciated class was derived. Parent should be used in the case that your inheritance tree changes, so you will not have to go replace all references to a singular class name.

Functions

Defining functions in PHP is accomplished using the function keyword, followed by the function name and comma delimited arguments, surrounded by parenthesis:

 
<?php
function myFunction($arg1, $arg2) {
  // your function code here
}
?>
 

You may also wish to have default values for variables if none are passed for the particular argument:

 
<?php
function myFunction($arg1, $arg2 = '') {
  // your function code here
  // if myFunction() is called with only one argument passed, $arg2 will automatically be set to ''
  // if myFunction() is called with two arguments, $arg2 will inherit the value of the 2nd argument passed
}
?>
 

If the function is encapsulated in an object, you may specify the visibility of the function, public, protected or private.

 
<?php
class MyClass
{
    public function myFunction($arg1, $arg2) {
      // myFunction code here
    }
}
?>
 

The above class will enable the use of such code as:

 
<?php
$foo = new MyClass;
$foo->myFunction('bar');
$foo->myFunction('bar', 'baz');
?>
 

Unlike some programming languages, like Perl or Python, PHP member functions implicitly extract their parent into the $this variable.

Boolean Logic

Ternary Conditionals

In PHP, if else statements typically look like this:

 
if( $a == $b ) {
    print "Equal!";
}
else {
    print "Not Equal!";
}
 

However, there is shorthand for this called a Ternary conditional. We can write the same if else statement like this:

 
($a == $b) ? print "Equal!" : print "Not Equal!";
 

Where the general form is:

 
(condition) ? if condition is true : if condition is false;
 

Loops

PHP has four main types of loops.

for

This loop is good for performing a set of instructions a set number of times. For example:

 
for($i=0; $i<5; $i++) {
    print "i = " . $i . "\n";
}
 

The above will print the value of i 5 times and the values will be:

   i = 0
   i = 1
   i = 2
   i = 3
   i = 4

foreach

This is probably the most common loop in all of PHP. It makes going through the elements of an array really easy. For example:

 
$names = array("Jack", "Jill", "Mike", "Sally", "Steve");
 
foreach($names as $name) {
    print $name . "\n";
}
 
 

The output of this code will be

 Jack 
 Jill
 Mike
 Sally
 Steve

Another really neat thing you could have done with this is the following:

 
$names = array("Jack", "Jill", "Mike", "Sally", "Steve");
 
foreach($names as $key => $name) {
    print "Entry #: " . $key . " Name = " . $name . "\n";
}
 
 

The output will be:

 Entry #: 0 Name = Jack 
 Entry #: 1 Name = Jill
 Entry #: 2 Name = Mike
 Entry #: 3 Name = Sally
 Entry #: 4 Name = Steve

Notice that in this example we define a $key. This key tells us what index of the array we are on. This is especially powerful when you use associative arrays like this:

 
$names = array("Manager" => "Jack", "Sales" => "Jill", "Accounting" => "Mike", "HR" => "Sally", "CEO" => "Steve");
 
foreach($names as $key => $name) {
    print "Position: " . $key . " Name = " . $name . "\n";
}
 
 Position: Manager Name = Jack
 Position: Sales Name = Jill 
 Position: Accounting Name = Mike
 Position: HR Name = Sally
 Position: CEO Name = Steve

while

The while loop is probably the most simple of them all. In it's most basic form:

 
<?php
while( true statement ) {
   // do something
}
?>
 

In this case, while "true statement" remains true, we will keep looping. For example:

 
<?php
$i = 5;
while( $i < 10 ) {
   $i = $i + 1; // This could be shortened to $i++; But I'm being intentionally verbose.
}
?>
 

The above code will continue to add 1 to $i until $i = 10, at which point the loop will stop. $i will retain it's value of 10.

Alternatively, there is another syntax for while:

 
<?php
while(expr):
  // do something
endwhile;
?>
 

Within the loop, there are of course ways of skipping and breaking out of the loop completely, they are:

 break;

Which will break out of the while() loop completely.

 continue;

Which will skip to the end of the current iteration and run through to the next iteration.

do-while

This loop is very similar to the while loop. Example:

 
$a = 0;
do {
    print "Hello: " . $a . "\n";
    $a = $a + 1;
} while( $a < 5);
 

The output of this will be:

 Hello: 0
 Hello: 1
 Hello: 2
 Hello: 3
 Hello: 4


There is one major difference between the while and the do-while: The condition is evaluated AFTER the code is run. In a normal while loop, the condition is evaluated BEFORE the code in the { } is run. So for example

With a normal while loop:

 
while( 1 == 0) {
    print "Hello!";
}
 

In this case "Hello" never gets printed because "1 == 0" gets evaluated BEFORE the code within the braces gets executed.

However, this changes in the following do-while example:

 
do {
    print "Hello!";
} while( 1 == 0);
 

The word "Hello" will get executed exactly once because the condition "1 == 0" gets executed AFTER the code between the braces is executed.

User Input

Security

code

Dangerous functions

  • include()
  • eval()
  • mysql_query()
  • pgsql_query()
  • phpinfo()
  • system()

Dangerous practices

  • include()
  • echo(), print(), sprintf()
  • string sanitizing using non-recursive string replacement
  • improper type handling

Best practices

The Golden Rule: Treat all user input as if it's malicious. Anything that gets transferred from the browser to the server (session variable especially) is a new vector for attacking your web app.

  • File inclusion
  • Type Handling
 
$clean_int = (int)$dangerous_int;
 
  • XSS
  • SQL Injection

Preventing SQL injection in PHP applications is relatively simple, so long as you are thorough. String input, surrounded by single quotes can be sanitized with mysql_real_escape_string(), which will escape dangerous characters such as single quotes (as well as \, so that you cannot escape the escapes!). Sanitizing integer input can be done simply by casting the input to integer.

php.ini

PHP-FPM

PHP-FPM has been around since 2009, but is now in mainline PHP since 5.4.0RC2. PHP-FPM is also known as FastCGI Process Manager, and does an excellent job at serving PHP powered content much more rapidly than mpm_worker/mpm_prefork on Apache. The configuration for PHP-FPM is somewhat complex, but is really easy once you get used to it and finish customizing everything. Take the following pool configuration for example:

<syntaxhighlight lang="ini">

 [wordpress]
 user = wordpress
 group = www-data
 listen = /var/run/php5-fpm/app.sock
 listen.owner = wordpress
 listen.group = www-data
 listen.mode = 0666
 chdir = /home/wordpress/web
 pm = dynamic
 pm.max_children = 50
 pm.start_servers = 10
 pm.min_spare_servers = 5
 pm.max_spare_servers = 15
 pm.max_requests = 1000
 php_admin_value[memory_limit] = 96M
 php_admin_value[session.save_path] = tcp://127.0.0.1:11211
 php_admin_value[open_basedir] = /home/wordpress/web
 php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,posix_mkfifo,pg_lo_import,dbmopen,dbase_open,popen,chgrp,chown,chmod,symlink
 php_admin_value[disable_classes] = pBot
 php_admin_value[post_max_size] = 100M
 php_admin_value[upload_max_filesize] = 100M
 php_admin_value[user_agent] = "WordPress (http://www.my-website.com)"

</syntaxhighlight>

This will do a few things:

  • Sets the UNIX socket (to be used with NGINX's upstream directive via unix:/var/run/php5-fpm/app.sock)
  • Sets the UID/GID of the socket to be of the user, and group to www-data so NGINX can read it
  • Changes directory to /home/wordpress/web before execution, so everything is relative to that path.
  • Sets the Process Management model to Dynamic, which will tune the number of servers and workers based on usage
  • Sets session management to use Memcached over TCP (requires socket support)
c3el4.png You can use TCP sockets to listen on instead of UNIX sockets, but that comes with it's own overhead, and you have to configure your firewall if it's not listening on localhost. You have been advised.

See Also : PHP Patching

PHP is part of a series on programming.
<center>
</center>