Passing Array Using Html Form Hidden Element

May 6, 2007

Html form hidden element is used to pass information which is not visible to the user but used internaly by underlying scripts. For example the status of the process or step of multi step form submission. PHP array is an important language structure used in manipulation of multiple values associated with single object. Sometimes it is required to pass these values accross the pages between browser and the server. Following method can be used to pass PHP Arrays using html form hidden elements.

Using individual array element

This method uses seperate hidden element for each element in array. This can be done by following method.

foreach ($my_array as $key => $value)
{
 echo ‘<input type=hidden name=”my_array[]” value=”‘.htmlspecialchars($value).'”>';
}

This will generate an array in html form. And when submitted can be accessed by form handling PHP script using following code.
$my_array = $_POST['my_array'];

Combining all array elements in one value to hidden element

In this method all elements in an array are combined in single value using implode() PHP function. implode() will return a string combining all the array elements in the same order, seperated by given string. Then this combined value can be passed in html form hidden element. See below.
$single_value = implode(“,”, $my_array);
echo ‘<input type=hidden name=”single_value” value=”‘.htmlspecialchars($single_value).'”>';

And when submitted the array can be retreived using explode() PHP function. explode() will return an array by spliting the string using the given seperator. See code below.
$my_array = explode(“,”,$_POST['single_value']);


PHP Cookies Tutorial And PHP Cookies Examples

March 6, 2007

In the course of developing highly interactive web sites it is necessary to deal with large amount of data flow between client browswer and web server. It is quite cumbersome handling such large amount of data using hidden fiels in HTML forms. This problem can be overcomed by using HTTP cookies. HTTP cookies are the bunch of data/text sent by the server to the web browswer. Web browser store this data locally and send back to the server each time it accesses the server before it expires. Note that now a days Most browsers allow users choice to accept cookies or not, sometime rejection causes web site to not work properly.

setcookie() function.
This function in PHP Language is used to work with HTTP cookies. setcookie() defines a cookie to be sent along with the rest of the HTTP headers. This must be called before sending any output to the browser because cookies are part of the HTTP header. On successful it will return TRUE. But this does not mean that client browser has ccepted cookie.

setcookie() syntax.
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

  • name: This argument sets the name of the cookie.
    for example setcookie(‘mycookie’, …) will set mycookie and is called $_COOKIE['mycookie'] at server side.
  • value: This will set the value of the cookie. Since this values is stored on the client browser extra care must be taken that it does not store some secure information e.g passwords. The values is accessed by $_COOKIE['mycookie'] at the web server.
  • expire: Sets the expire time of cookie. It is Unix timestamp so generally it is used with time() function. For example time()+60*30. This will set the cookie to expire in 30 minutes. If not set the cookie is not persistent and will expire when the browser closes.
  • path: The path of cookies are used to organise cookies based on the path at web server. If set to ‘/’ this cookie is availabe to all directories. If set to ‘/dir1/’ this cookie is availabe to dir1 only and all sub directories of /dir1 i.e /dir1/sub1. Note that the default value is the current directory so if the current directory is ‘/dir1/’ and you want to set it for all directories it must be ‘/’
  • domain: This argument will decide in which domain cookie is accesible. Value ‘www.mydomin.com’
    makes it accesible to www sub-domain only. To make it accessible to all subdomains of mydomin.com a value
    ‘.mydomin.com’ must be set.
  • secure: Value 1 indicates the cookie must be used on secure (https) connection. Default value is 0.

setcookie() Examples.
setcookie(‘mycookie’, ‘Test mycookie’); This will set ‘mycookie’ with value ‘Test mycookie’ will expire when browser closes.
setcookie(‘mycookie’, ‘Test mycookie’, time()+3600*24); This will expire in 1 day.
setcookie(‘mycookie’, ‘Test mycookie’, time()+3600*24, “/dir1/”); Available to /dir1 directory and all subdirectories under it.

Accessing cookie values at server.
At server in PHP script, cookies sent from the client browser will be turned into PHP variables. After PHP 4.1.0 the global array variable $_COOKIE is set for cookies from the client. $HTTP_COOKIE_VARS is also present which is availabe before PHP 4.1.0. See example below.
echo $_COOKIE["mycookie"]; This will output “Test mycookie” in our example.

Testing cookie.
On successful return of setcookie() does not mean that client browser has accepted the cookie or cookie is set successfully. It must be checked on next loading of the page if a cookie was successfully set or not. This can be done by using PHP function print_r($_COOKIE) function. This will show weather the cookie is set or not.

Deleting a cookie.
Cookies can be deleted by setting its value to “” and all other parameters must be the same as they were set at the time of sending the cookie. We must ensure that the expiration date is in the past when deleting the cookie. See examples below.

setcookie (“mycookie”, “”, time() – 3600);
setcookie (“mycookie”, “”, time() – 3600, “/dir1/”);

Multiple cookies.
Multiple cookies can be set using following.
setcookie(‘mycookie1′, ‘Test mycookie1′);
setcookie(‘mycookie2′, ‘Test mycookie2′);
setcookie(‘mycookie3′, ‘Test mycookie3′);
setcookie(‘mycookie4′, ‘Test mycookie4′);

And can be accessed by following.
echo $_COOKIE["mycookie1"];
echo $_COOKIE["mycookie2"];
echo $_COOKIE["mycookie3"];
echo $_COOKIE["mycookie4"];

Cookies Array.
We can use PHP array in cookies. see example below
setcookie(“mycookie[0]“, “value1″);
setcookie(“mycookie[1]“, “value2″);
setcookie(“mycookie1['one']“, “value11″);
setcookie(“mycookie1['five']“, “value15″);

This is similar of setting many cookies but the values are placed in the PHP array at the
receing PHP script.

foreach ($_COOKIE['mycookie'] as $key => $value) {
  echo “$key:$value “;
  }
This will print 0:value1 1:value2
And
foreach ($_COOKIE['mycookie1'] as $key => $value) {
  echo “$key:$value “;
  }
Will print print one:value11 five:value15


PHP Arrays Tutorial and PHP Array Examples

February 25, 2007

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

PHP Array Syntax: Create an Array
language-construct array() is used to create an array in PHP. See example below

array( [key =>] value
  , …
  )
key: key may be an integer or string
value: A value can be of any PHP type

Examples
$arr = array(“foo” => “bar”, 12 => true);
echo $arr["foo"]; this will print bar
echo $arr[12]; this will print 1

if you provide the brackets with no key specified, then the maximum of the existing integer indices +1 is taken as key. see below

$arr = array(5 => 1, 12 => 2); This will create an array with 2 elements
$arr[] = 56;     new key will be maximum key + 1 i.e $arr[13] = 56
$arr["x"] = 42;  This adds a new element to the array with key “x”

array(5 => 43, 32, 56, “b” => 12); This array is the same as following.
array(5 => 43, 6 => 32, 7 => 56, “b” => 12);

Handling arrays from html form inputs to php scripts
Following example will show we can use an array from html form inputs.

HTML form with array
<input type=”checkbox” name=”selected_ids[]” value=”1″>
<input type=”checkbox” name=”selected_ids[]” value=”2″>
<input type=”checkbox” name=”selected_ids[]” value=”3″>
<input type=”checkbox” name=”selected_ids[]” value=”11″>
<input type=”checkbox” name=”selected_ids[]” value=”12″>
<input type=”checkbox” name=”selected_ids[]” value=”13″>

When we submit above form, it will generate $_POST['selected_ids'][] array to the form handling php script. This array holds all selected checkbox values from above html form. foreach() construct can be used to extract values from the array. Following code example will show how we can extract those values from the returning array.

foreach ($_POST['selected_ids'] as $key => $value) {
    echo “Key: $key; Value: $value<br>”;
}
for example if 1,2 and 12 is selected from the above html form then above code will print
Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12


Using remote files in PHP

February 17, 2007

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements. In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option –enable-url-fopen-wrapper.

Getting the title of a remote page
For example, you can use code below to to open a file from a remote web server and extract title of the page.

<?php
$file = fopen (“http://www.example.com/&#8221;, “r”);
if (!$file) {
    echo “<p>Unable to open remote file.\n”;
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (eregi (“<title>(.*)</title>”, $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?> 

Reading the contents of a remote file
fread function can be used to read content of remote file. This is shown in example below. You should collect the data together in chunks as shown in the example below because reading will stop after a packet is available.

<?php
$handle = fopen(“http://www.example.com/&#8221;, “rb”);
$contents = ”;
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?> 

reading the contents of a file into array
file function returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Each line in the resulting array will include the line ending, so you still need to use rtrim() if you do not want the line ending present.

<?php
// Get a file into an array.  In this example we’ll go through HTTP to get
// the HTML source of a URL.
$lines = file(‘http://www.example.com/&#8217;);

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo “Line #<b>{$line_num}</b> : ” . htmlspecialchars($line) . “<br />\n”;
}
?>

reading the contents of a file into a string

file_get_contents() returns the file in a string. This is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

<?php
$content_string = file_get_contents(‘www.example.com/products.html’);
?>

Storing data on a remote server
You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail. You need to specify the username and password within the URL, such as ‘ftp://user:password@ftp.example.com/path/to/file’.

<?php
$file = fopen (“ftp://ftp.example.com/incoming/outputfile”, “w”);
if (!$file) {
    echo “<p>Unable to open remote file for writing.\n”;
    exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . “\n”);
fclose ($file);
?> 


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”;
}


PHP HTML basic tips and tricks

January 30, 2007

PHP is an HTML-embedded scripting language. The goal of the language is to allow web developers to write dynamically generated pages quickly. In the course of web development of using PHP PHP and HTML interact a lot. PHP can generate HTML, and HTML can pass information to PHP.

Encoding/decoding when passing a data through a form or URL
Certain characters, for example ‘&’, have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages.

Passing a value through HTML FORM you must include it in double quotes, and htmlspecialchars() the whole value. For exampe see the code below

<?php echo “<input name=’data’ type=’hidden’ value=’” . htmlspecialchars($data) . “‘>”; ?>

While passing a value through URL you must encode it with urlencode(). It will convert all non-alphanumeric characters except -_. with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. See example below.
<?php echo “<a href='” . htmlspecialchars(“/nextpage.php?stage=23&data=” .urlencode($data) . “‘>\n”; ?>

Creating a PHP arrays in a HTML form

To get your FORM result sent as an array to your PHP script you name the INPUT, SELECT, TEXTAREA elements like this:
<input name=”MyArray[]“>
<input name=”MyArray[]”>
<input name=”MyArray[]”>
<input name=”MyArray[]”>

If you do not specify the keys, the array gets filled in the order the elements appear in the form. Above example will contain keys 0, 1, 2 and 3. Notice the square brackets after the variable name, that’s what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name=”MyArray[]“>
<input name=”MyArray[]”>
<input name=”MyOtherArray[]“>
<input name=”MyOtherArray[]”>
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It’s also possible to assign specific keys to your arrays:
<input name=”AnotherArray[]”>
<input name=”AnotherArray[]”>
<input name=”AnotherArray[email]“>
<input name=”AnotherArray[phone]“>

The AnotherArray array will now contain the keys 0, 1, email and phone.

Getting results from a select multiple HTML tag.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name=”var” multiple=”yes”>
Each selected option will arrive at the action handler as var=option1, var=option2, var=option3. Each option will overwrite the contents of the previous $var variable. The solution is to use PHP’s “array from form element” feature. The following should be used:
<select name=”var[]” multiple=”yes”>
Now first item becomes $var[0], the next $var[1], etc.

Passing a variable from Javascript to PHP
Since Javascript is a client-side technology, and PHP is a server-side technology, the two languages cannot directly share variables. It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this — it allows PHP code to capture screen height and width, something that is normally only possible on the client side.
<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo “Screen width is: “. $_GET['width'] .”<br />\n”;
  echo “Screen height is: “. $_GET['height'] .”<br />\n”;
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   — post variables will need to handled differently)

  echo “<script language=’javascript’>\n”;
  echo ”  location.href=\”${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}”
            . “&width=\” + screen.width + \”&height=\” + screen.height;\n”;
  echo “</script>\n”;
  exit();
}
?> 


HTML Form Elements Values usage Examples in PHP

January 28, 2007

During the development of interactive web sites using PHP and HTML it is requiredto deal with data flow between user/browser and the server. This is achieved by using HTML forms and supporting HTML form elements. Following examples shows how these form elements can be used in HTML andPHP to allow interaction between user and the server.

Text input HTML form element

This input form element can be used for a single lime text input from the user. For example user first name, user e-mail, phone numbers etc. The syntax in HTML form is as below

<input type=”text” name=”username”>
<input type=”text” name=”email”>

This will display an input box in the browser and the values of this element canbe accessed at the form handling php script by following.
<?php echo “User Name:”.$_POST['username']; ?>

Password type. The defulat type of HTML input element is text. The special password type of input can be used as following
<input type=”password” name=”password”>

and can be accessed in PHP similar to above input element.
<?php echo “The Password is:”.$_POST['password']; ?>

Hidden type. The hidden field is used to send information from browser to the server without having to input it. Typically this is used to send some logical data that has nothing to do with user but used at the server in PHP program logic. For example state, action, or passing the result to the other module etc. Please note that you encode the value using htmlspecialchars() function.
<input type=”hidden” name=”action” value=”<?php echo htmlspecialchars(‘step2′); ?>”>

and the value of this field can be accessed in PHP by following.
<?php echo “The Value of action is:”.$_POST['action']; ?>

Textarea multiline text HTML form element

This form element can be used for a multi-line text input from the user. For example product description. The syntax is as below.

<textarea name=”description” rows=”5″ cols=”50″></textarea>

This will display a multi-line input area in the browser and the size can be controlled using rows and cols tag. The text value input by user can be accessed in PHP by following

<?php echo “Product Description:”.$_POST['description']; ?>

Select (Pull Down menu) and Select multiple HTML form element

This type of HTML form element is used to allow user to select from multiple choices. For example selecting a month or a day. The html syntax is as below.

<select name=”year”>
<option value=”2004″>2004</option>
<option value=”2005″>2005</option>
<option value=”2006″>2006</option>
<option value=”2007″>2007</option>
<option value=”2008″>2008</option>
</select>

The value of selected choice can be accessed in form handling PHP script as following
<?php echo “Selected Year is:”.$_POST['year']; ?>

The variation to this allows user to select multiple choices from the given options.
This can be done by following select multiple syntax

<select multiple name=”colors[]” size=”4″>
<option value=”Red”>Red
<option value=”Yellow”>Yellow
<option value=”Blue”>Blue
<option value=”Green”>Green
<option value=”White”>White
<option value=”Black”>Black
</select>

The size tag can be used to control how many rows should be visible. And note the use of ‘[]’ following the name of the select box. This will denote that it is an array and the choices can be accessed in form handling PHP script by following.

<?php
foreach ($_POST['colors'] as $key => $value) {
echo “Key: $key; Value: $value<br>”;
}
?>
If Red and Green is selected then above code will print
0: Red
1: Green

Radio button HTML form element

Radio button in HTML form is an alternative method that allows user to select from given options. Unlike drop down menu this is used to create more visibilty in the input form.

<input type=”radio” name=”colour” value=”Red”>Red
<input type=”radio” name=”colour” value=”Orange”>Orange
<input type=”radio” name=”colour” value=”Blue”>Blue

The value of the selection can be accessed in PHP as following
<?php echo “Selected Color is:”.$_POST['colour']; ?>

Check Box button HTML form element

This is an alternative way of allowing user to select multiple choices from the given options. Following example show the use of Check Boxes in an HTML form

<input type=”radio” name=”colour[]” value=”Red”>Red
<input type=”radio” name=”colour[]” value=”Orange”>Orange
<input type=”radio” name=”colour[]” value=”Blue”>Blue
<input type=”radio” name=”colour[]” value=”Violet”>Violet
<input type=”radio” name=”colour[]” value=”Black”>Black

Again here PHP array is used to access the selected choices from the user.
<?php
foreach ($_POST['colors'] as $key => $value) {
echo “Key: $key; Value: $value<br>”;
}
?>

If Red and Violet is selected then above code will display
0: Red
1: Violet


Follow

Get every new post delivered to your Inbox.