2012

Php Configuration File (php.ini)

The 'php.ini' file is the default configuration file for running applications that require PHP. It is used to control variables such as script execution time, upload sizes etc. Some common setting variables with description are as follows:

Category Variable Default Value Description
Register Global register_globals Off Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. For more detail read here
File Upload file_uploads On Whether to allow HTTP file uploads.
upload_tmp_dir NULL Temporary directory for HTTP uploaded files (will use system default if not specified).
upload_max_filesize 2M Maximum allowed size for uploaded files. PHP allows shortcuts for bit values, including K (kilo), M (mega) sand G (giga).
max_file_uploads 20 The maximum number of files allowed to be uploaded simultaneously.
Post post_max_size 8M Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than 'upload_max_filesize'. Default value is 8Mb.
Session session.gc_maxlifetime 1440 Default sessin time in php. The default value is on seconds (1440 sec = 24 min)
session.auto_start 0 Initialize session on request startup.(Turning on session support automatically at site level)
Resource Limit max_execution_time 30 Maximum execution time of each script, in seconds.
Error Reporting error_reporting E_ALL Display types of error. E_ALL display all types of error.

Full directives can be found at here (php official website).

Types of error in PHP

There are three basic types of runtime errors in PHP :

  1. Notices
    These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.  

  2. Warnings
    These are more serious errors - for example, attempting to include () a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination. 

  3. Fatal Errors
    These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place. 
        
Internally, these variations are represented by twelve different error types. 

  1. E_ERROR: A fatal error that causes script termination.
  2. E_WARNING: Run-time warning that does not cause script termination.
  3. E_PARSE: Compile time parse error.
  4. E_NOTICE: Run time notice caused due to error in code.
  5. E_CORE_ERROR: Fatal errors that occur during PHP's initial start-up (installation).
  6. E_CORE_WARNING: Warnings that occur during PHP's initial start-up.
  7. E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
  8. E_USER_ERROR: User-generated error message.
  9. E_USER_WARNING: User-generated warning message.
  10. E_USER_NOTICE: User-generated notice message.
  11. E_STRICT: Run-time notices.
  12. E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error 
  • E_ALL: Catches all errors and warnings

Types of connection

There are two types of connection with database in php. They are
  1. Non-Persistent connection : Connection is closed at end of script (end of page).
    mysql_connect(server,user,pwd,newlink,clientflag);

  2. Persistent connection : Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
    mysql_pconnect(server,user,pwd,newlink,clientflag);

Note : Persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Note : mysql_close(connection) // function closes a non-persistent MySQL connection.

If persistent connections don't have any added functionality, what are they good for?

Database Connection Mysql

Steps of using MySql db from Php.

  1. Create a database connection.
  2. Select a database.
  3. Perform a SQL query.
  4. Perform your operations on SQL query results.
  5. Close database connection. 
1. Create a database connection.
Php uses following funtions for making a databse connection .
mysql_connec(server,user,pwd,newlink,clientflag) // Non persistance connection
mysql_pconnec(server,user,pwd,newlink,clientflag) // Persistance connection.

Parameter Description
server Optional. Hostname of server. Default value is "localhost:3306"
user Optional. Username on the database. Default value is the name of the user that owns the server process
pwd Optional. Username on the database. Default is ""
newlink Optional. Reuse database connection created by previous call to mysql_connect
clientflag Optional. Can be a combination of the following constants:
  • MYSQL_CLIENT_SSL - Use SSL encryption
  • MYSQL_CLIENT_COMPRESS - Use compression protocol
  • MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names
  • MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection

2. Select a database.
Php use following function for selecting database.
mysql_select_db(database,connection)
   database -- Specifies the database to select.
   connection -- (Optiona)l. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

3. Perform a SQL query.
Php have following function to executes a query on a MySQL database.
mysql_query(query,connection)
   query -- SQL query to execute (eg. SELECT query, UPDATE query...etc);
   connection -- (Optional) MySQL connection name. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.
This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
4. Close database connection. 
Php uses following function for closing a connection.
mysql_close(connection) // function closes a non-persistent MySQL connection.

Sample Code :
<?php
$con = mysql_connect("server","username","password");
if (!$con)   {
  die('Unable to connect: ' . mysql_error());  
}else{
mysql_select_db('database_name');
}
$sql = "SELECT * FROM Customer";
mysql_query($sql,$con);
// do some more precessing ..
mysql_close($con);
?>

Database Connection


  • PHP provides built-in database connection class/functios for a wide range of databases such as MySQL, PostgreSQL, Oracle, Berkeley DB, Informix, mSQL, Lotus Notes.
  • PHP also provides database connectivity for specific databases which involves PHP configuration steps.

Please refer following url for detail database connectivity for different databases
http://www.php.net/manual/en/

Web Services



Web service are applications using open protocols and standards to exchange data between applications or systems.Software applications written in various programming languages(Php, Python, Java etc.) and running on various platforms(Linux, Windows etc.) can use web services to exchange data over computer networks(Internet, Intranet, etc) in a manner similar to inter-process communication on a single computer.

Security


1. Avoid using uninitialized variable. 
If the register_globals(php.ini) is turned on , the uninitialized variable can cause security breach.

Example:


Following code is used to recognize admin in 'test.php' script.

<?php
    if($user==0) {
          $admin = true;
    }
?>

If register_globals is on, the url http://www.testdomain.com/test.php?user=0 will declare $user as a global variable with no code required and thus provide admin status.




2. Never trust user data

Example:

<?php
    readfile($_POST['filename']);
?>

In this case if you really want the user to be able to specify a filename that gets used in any of PHP's file functions, do something like this:

<?php
    $doc_root = $_SERVER['DOCUMENT_ROOT'];
    $filename = realpath($filename);
    readfile($doc_root.$filename);
?>

You may also want to strip out any path and only take the filename component. An easy way to do that is to use the basename() function. Or perhaps check the extension of the file. You can get the extension using this code:

<?php
$ext = substr($str,strrpos($str,'.'));
?>


3. Make sure users can't pass in arguments that executes other system calls, make sure that the argument itself is ok and only accesses data you want the users to have access to.

Example:

<?php
system("ls $dir");
?>

In this example you want to make sure that the user can't pass in $dir set to something like: ".;cat/etc/passwd". The remedy is to use escapeshellarg() which places the argument inside single quotes and escapes any single quote characters in the string.

<?php
$dir=escapeshellarg($dir);
system("ls $dir");
?>


4. Place included files outside of the DOCUMENT_ROOT directory.

Many users place code in multiple files and include these files:
<?php
require 'functions.inc';
?>

Or perhaps

<?php
require 'functions.php';
?>

Both of these can be problematic if the included file is accessible somewhere under the DOCUMENT_ROOT directory. The best solution is to place these files outside of the DOCUMENT_ROOT directory where they are not accessible directly. You can add this external directory to your include_path configuration setting. Another option is to reject any direct requests for these files in your Apache configuration. You can use a rule like this in your "httpd.conf" file:

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

Register Globals

PHP automatically creates global variables containing data from a variety of external sources EGPCS (Environment, GET, POST, Cookie, Server).register_globals setting in PHP's configuration file (php.ini)(which can be either On or Off) tells whether or not to register the contents of the EGPCS variables as global variables.

Example 1:
To start a session use session_start() and to register a variable in this session use the $_SESSION array.

<?php
session_start();
$_SESSION['my_var'] = 'Hello World';
?>
If register_globals is enabled then your session variables will be available as normal variables on subsequent pages.
<?php
session_start();
echo $my_var;
?>
And If register_globals is enabled, then it will only be in the $_SESSION array.
<?php
session_start();
echo $_SESSION['my_var'];
?>


Example 2:

If register_globals is on, the url http://www.testdomain.com/test.php?id=3 will declare $id as a global variable with no code required.


Note : This feature is a great security risk, and you should ensure that register_globals is Off for all scripts (as of PHP 4.2.0 this is the default).

PHP Opcode Caches

Opcode (operation codes) caching is used to accelerate execution of browser request by caching the operational code. Caching the compiled bytecode(Opcode) of php script avoid the overhead of parsing & compiling code every time.
           The cached code is stored in shared memory or ram and directly is available for execution, without spending time for slow disk reads and memory copying at runtime.



Fig 1 : Execution of PHP script without an Opcode Cache


Execution of PHP script with an Opcode Cache


Fig 2: Execution of PHP script with an Opcode Cache 


There are number of Opcode Caches available. Some of them are :

  1. APC (Alternative PHP Cache) is a free and open opcode cache for PHP. APC framework optimizes PHP intermediate code and caches data and compiled code from the PHP bytecode compiler in memory.
  2. Zend Cache - commercial (developed by zend the php company).
  3. IonCube Accelerator - free, but closed source, Launched in 2001.
  4. XCache is a fast, stable PHP opcode cacher that has been tested and is now running on production servers under high load.



Best practice (optimization)

1. References
Use of references are slower than making copies of original data and than manipulate it. So use references only when you have large data structs to save memory. The use of references depends on your system, if your system is CPU bound avoid using the references and if your system is memory bound use references.

2. Persistent Database connections
Generally databases are slower to establish connections so it is better to use persistent db connection. But persistent connections will consume and tie up resources even when not in use so watch your resource limits before making tradeoff.

3. Avoid using regex
Php have good sets of string manipulation functions:

    <?php ereg_replace("-","_",$str); ?>Bad
    <?php str_replace("-", "_", $str);?>Good


4. mysql_unbuffered_query()
The function mysql_unbuffered_query() is same as mysql_query() except that instead of waiting for the entire query to execute and storing the result in the client API, it makes results available to you as soon as possible and they are not allocated in the client API. So you get access to data quicker and uses less memory. You can't use mysql_num_rows() on the result resource and it is likely to be slightly slower for small selects.

Sessions

Sessions are used to store data on server and retrieve it for a user while they travel through a series of pages, or page iterations, on your site. They are same as cookie , the only difference is that they are stored at server while cookie stored at client machine.

To start session
<?php
    session_start();
    $_SESSION['variable1'] = 'value1';
?>

To retrieve variable on other script/page use
<?php
    session_start();
    echo $_SESSION['variable1'];
?>

Cookies

Storing data at client machine.The expires time is in seconds.

Setting a session cookie
<?php
setcookie('Cookie_name','value','expire_time');
// If expire_time set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
?>

Setting a persistant cookie
<?php
setcookie('Cookie_name','value',mktime.time()+60*60); // Expires after 60 min.
?>

Reading a cookie
<?php
echo $_COOKIE['Cookie_name'];
?>

Deleting the Cookies
<?php
setcookie('Cookie_name','',mktime.time()-60); // Set expire time to negative time deletes a cookie.
?>

Other Optional Parameters
Path, Domain, and Secure parameters can also be set to restrict a cookie to a certain path, domain or
in the case of the Secure parameter, limit the cookie to only be set if the request came in over an SSL
connection.

Common Problem : Short expiry cookies depend on users having their system clocks set correctly.
Solution : Don't depend on the users having their clocks set right. Embed the timeout based on your server's
clock in the cookie.
Example:
At the cookie setting script :
<?php
$variable = 'Data to be stored in cookie'; // Data to be store
$value = time()+60 .':'.$varaible; // Concatenate the current(server) time + Data to be store
setcookie('Cookie_name',$value);
?>
At the receiving (getting cookie)script :
<?php
$value = $_COOKIE['Cookie_name']; // Getting the whole string stored in cookie
$valueArray = explode(':',$value);

if($valueArray[0]<=time()){ // Is valid cookie
    $variable = $valueArray[1];
}else{ // Expired cookie
    setcookie('Cookie_name','',mktime.time()-60); // deleting the cookie
}
?>

HTTP Headers

You can add headers to the HTTP response in PHP using the Header() function. Since the response
headers are sent before any of the actual response data, you have to send these headers before
outputting any data.
Examples :

Example 1. Prompt user to save a generated PDF file.
<?php
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");
?>

Example 2. Redirect browser
<?php
header("Location: http://www.example.com/");
?>

Example 3. Hide away your environment information (if you cannot do this at server level)
<?php
header('Server: ');
header('X-Powered-By: ');
?>

Removing Cache from the page

There are two methods of avoiding a page to be stored in browser cache. 1st method is better because each browser interprete Meta tag differently.

1. Using the PHP Header. Use the following code before rendering any output to the browser.
    <?php
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header("Cache-Control: post-check=0, pre-check=0", false);
    header('Pragma: no-cache');
    header('Expires: Mon,26 Jul 1980 05:00:00 GMT');
    header("Last-Modified: Tue,01 Jan 2000 00:00:00 GMT");
    ?>

2. Using the HTML Meta tag.
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

Newer Posts

Related Posts Plugin for WordPress, Blogger...
Powered by Blogger.