PHP File Upload

February 15, 2007

PHP can be used to receive files from any RFC-1867 compliant browser. This can be used to upload both text and binary files from browsers. See the file upload html form below:

<form enctype=”multipart/form-data” action=”handle_upload.php” method=”post”>
 <input type=”hidden” name=”MAX_FILE_SIZE” value=”30000″>
 Select File: <input name=”myfile” type=”file”>
 <input type=”submit” value=”Upload”>
</form>

  • MAX_FILE_SIZE hidden field restrict the maximum filesize accepted in bytes and must precede the file input field
  • enctype=”multipart/form-data” is used to handle file uploads and file will be uploaded as MIME data streams. Otherwise the file upload will not work.

The Variables, in PHP script which receives file upload, differs depending on the PHP version and configuration. The $_FILES exists as of PHP 4.1.0 The $HTTP_POST_FILES array has existed since PHP 4.0.0. These arrays hold uploaded file information. Using $_FILES is preferred.
The contents of $_FILES from above script is as follows.

  • $_FILES[‘myfile’][‘name’] The original name of the file on the client machine.
  • $_FILES[‘myfile’][‘type’] The mime type of the file, if the browser provided this information. An example would be “image/gif”.
  • $_FILES[‘myfile’][‘size’] The size, in bytes, of the uploaded file.
  • $_FILES[‘myfile’][‘tmp_name’] The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES[‘myfile’][‘error’] Since PHP 4.2.0, PHP returns an appropriate following error code along with the file array
    UPLOAD_ERR_OK – Value: 0; There is no error, the file uploaded with success.
    UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
    UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
    UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
    UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.

Uploaded Files will by default be stored in the server’s default temporary directory. Variable $_FILES[‘myfile’][‘tmp_name’] will hold the info about where it is stored. The move_uploaded_file function needs to be used to store the uploaded file to the correct location. See the code below:

$uploaddir = “uploads/”;
$uploadfile = $uploaddir . basename( $_FILES[‘myfile’][‘name’]);

if(move_uploaded_file($_FILES[‘myfile’][‘tmp_name’], $uploadfile))
{
  echo “The file has been uploaded successfully”;
}
else
{
  echo “There was an error uploading the file”;
}

Advertisements

php connection status and connection handling

January 24, 2007

There are three possible php connection states are maintained Internally. They are NORMAL, ABORTED and TIMEOUT. When the script is running normally the NORMAL php connection state is active. If the connection between client and server is stopped or disconnected it is in ABORTED state. If the max_execution_time of PHP script is expired the TIMEOUT state is active. The max_execution_time value is defined in the php.ini if it is not defined the default value is 30 seconds. There are functions availabe in PHP that can be used to control php connection status.

ignore_user_abort() function By default the php script is aborted when client stops or disconneted. Sometime it is required to always have the scripts run to completion. This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only eturn the current setting. This behaviour can also be set via the ignore_user_abort php.ini directive as well as through the corresponding “php_value ignore_user_abort” Apache .conf directive.

register_shutdown_function() function. By default the php script is aborted when client stops or disconneted. One exception to this is if you have registered a shutdown function using register_shutdown_function(). This registered shutdown function will get called when the script is aborted by client disconnect. Note that this registered shutdown function will get called even if the script is terminating normally. For example such call register_shutdown_function(my_register_function) will register my_register_function() and will get called when underlying php script is terminating. Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. It is not possible to send any output to the browser in registered shutdown functions because they are called after the request has been completed including sending any output.

connection_aborted() function. This function returns TRUE if client disconnected. Typically this function is useful in registered shutdown functions to do something different in case of a client disconnect and php connection status is ABORTED.

Controling script execution time set_time_limit() function. The default timeout for any php script is 30 seconds. This can be changed using the max_execution_time php.ini directive or the corresponding “php_value max_execution_time” Apache .conf directive. This can also be controled run time by using set_time_limit() function. This function sets the number of seconds a script is allowed to run. If seconds is set to zero, no time limit is imposed. When called, set_time_limit() restarts the timeout counter from zero. i.e if the timeout is the default 30 seconds, and after 25 seconds into script execution a call set_time_limit(20) is made, the script will allow to run for a total of 45 seconds before timing out.

connection_timeout() function. This function returns TRUE if php connection status is TIMEOUT. Typically this function is useful in registered shutdown functions to do something different in case of php connection status is TIMEOUT.

connection_status() function. Note that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible when ignore_user_abort is set and client disconnected. At this time script will keep running but PHP will still note that it is ABORTED. If it then TIMEOUT it will stop execution of the script and registered shutdown function will be called if registered. At this point connection_timeout() and connection_aborted() will return TRUE. connection_status() can also be used which returns the connection status bitfield. So, if both states are active it would return 3.


php basics

January 23, 2007

PHP (Hypertext Preprocessor) ia an Open Source general purpose web scripting language. It is widely used for Web development because it can easily be embedded into HTML. PHP is an easy to learn and you can start developing dynamic webpages very quickly. Moreover PHP can be used in other development areas e.g Command line scripting.

<html>
  <head>
  <title>Embedding PHP in HTML</title>
  </head>
  <body>
  <?php echo “Hi, I can easily be embedded into HTML !!!”; ?>
  </body>
</html>

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

Retrieving IP Address of visitors
You can see from the example above how easily PHP code can be embeded into HTML. Now let us see something more useful. We will check the IP address of the visitor of the page. This can be achieved using PHP as follows.

<html>
    <head>
        <title>IP Address of visitor</title>
    </head>
    <body>
        Your IP Address is : <?php echo $_SERVER[‘REMOTE_ADDR’]; ?>
    </body>
</html>

Working with forms
Here we will see how to use PHP in working with HTML forms. We will see how one can use PHP to access data filled in HTML forms. Let us have form with Name and Phone Number fields as below.

<form action=”action.php” method=”post”>
 Name: <input type=”text” name=”name”>
 Phome: <input type=”text” name=”phone”>
 <input type=”Submit” value=”Submit”>
</form>

Now we will see how values of these fields can be accessed using PHP.

Name: <?php echo $_POST[‘name’]; ?>
Phone: <?php echo $_POST[‘phone’]; ?>