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

PHP

From NetSec
Revision as of 02:06, 23 June 2012 by User (Talk | contribs) (Variables)

Jump to: navigation, search

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.

RPU0j.png This article needs immediate attention, and is in desperate need of content.

Development Environment

PHP CLI

Xochipilli says
Many Linux distributions package the PHP CLI separately
  • To check the syntax of a PHP file (lint):
 php -l /path/to/script.php
 php --syntax-check /path/to/script.php
  • To see the current version of PHP (CLI):
 php -v
 php --version
  • To execute PHP code via CLI (without PHP tags):
 php -r 'PHP CODE HERE'
 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:
 php -d foo=bar /path/to/script.php
 php --define foo=bar /path/to/script.php
  • To run a script silently:
 php -q /path/to/silent_script.php
 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:
 php -z /path/to/zend/extension.so /path/to/script.php
 php --zend-extension /path/to/zend/extension.so /path/to/script.php
  • To see a list of modules that PHP CLI has loaded:
 php -m
 php --modules
  • To benchmark execution times of a script N times:
 php -T TIMES /path/to/script.php
 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:
 php -H -d mypassword=blah -d myuser=user /path/to/script.php
 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.

Your first application

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 = "Blackhat Academy ";
$variable1 = "Rules!";
echo "$variable $variable1";
?>
 

This snippet of code will display the following:

 Blackhat Academy Rules!

Data Types

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

Integers

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

 $var = 1;

Strings

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

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

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

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

 $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', ...)

Objects

Classes

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:

 
while( true statement ) {
   ...
}
 

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

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

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.

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
 
$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
 
=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:
 
{{code
|text=
<source lang="php">
function myFunction(arg1, arg2) {
...
}
 

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

 
class MyClass
{
    public function myFunction(arg1, arg2) {
    ...
    }
...
}
 

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

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

See Also : PHP Patching

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