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’]);


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 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();
}
?>