Thursday, February 12, 2009

Understanding the difference between post and get

Let me explain with an example

<form name="form1" action="test.php" method="GET">
<input type="textbox" name="username">
<input type="textbox" name="useraddress">
</form>

Here in the form we have method="GET". Thus when the form is submitted the URL will be shown as
test.php?username=rajesh&useraddress=testing123

Each line after the basic URL begins with the name attribute of one of the form elements,
followed by an equal sign and the contents of the input fields. URLs cannot
contain spaces or certain characters (such as my smiley), so the browser encodes
them as hexadecimal values, a process known as URL encoding.

The first name attribute is preceded by a question mark (?) and the others by an
ampersand (&). You’ll see this type of URL when using search engines, which helps
explain why everything after the question mark is known as a query string.

Now when you use the same form with method="POST"

<form name="form1" action="test.php" method="POST">
<input type="textbox" name="username">
<input type="textbox" name="useraddress">
</form>

Here nothing can be shown in the URL except the php page test.php.So no global variables are shown in the URL.If you want to test the POST values use the below code

<pre>
<?php if ($_POST) {print_r($_POST);} ?>
</pre>

This displays the contents of the $_POST superglobal array if any post data has
been sent.

When you click the Refresh button in your browser. You will probably see a warning similar to the following. This tells you that the data will be resent, which is exactly what you want. Click OK or Send depending on your browser.

Simply in one word we can say "get method sends your data in a very exposed way, making it vulnerable to alteration. Also, some browsers limit the maximum length of a URL, so it can be used only for small amounts of data."

About the post in one word "The post method is more secure and can be used for much larger amounts of data".

By default, PHP permits up to 8MB of post data, although hosting companies may set a smaller limit.

Because of these advantages, you should normally use the post method with forms. The get method is used mainly in conjunction with database searches, and has the advantage that you can bookmark a search result because all the data is in the URL.

Leia Mais…

Monday, February 9, 2009

Displaying a random image

Displaying a random image is very easy. All you need is a list of available images, which you store in an indexed array. Since indexed arrays are numbered from 0, you can select one of the images by generating a random number between 0and one less than the length of the array. All accomplished in a few lines of code . . .
Assuming images are already in the images folder.
Assuming you have created include folder

1. Create a blank PHP page in the includes folder and name it random_image.php.
Insert the following code:

<?php
$images = array('kinkakuji', 'maiko', 'maiko_phone', 'monk',
'fountains', 'ryoanji', 'menu', 'basin');
$i = rand(0, count($images)-1);
$selectedImage = "images/{$images[$i]}.jpg";
?>

This is the complete script: an array of image names minus the .jpg filename
extension (there’s no need to repeat shared information—they’re all JPEG), a random
number generator, and a string that builds the correct pathname for the
selected file.Here we use function rand() to generate the random number between the selected images count to display the image randomly. So every time you refresh your browser Every time you change the $images array,you need to count how many elements it contains and change the maximum

The random number is used in the final line to build the correct pathname for the
selected file. The variable $images[$i] is embedded in a double-quoted string
with no whitespace separating it from surrounding characters, so it’s enclosed in
curly braces. Arrays start at 0, so if the random number is 1, $selectedImage is
images/maiko.jpg.

2. Open index.php and include random_image.php by inserting the command in the
same code block as title.inc.php like this:
<?php include('includes/title.inc.php');
include('includes/random_image.php'); ?>
Since random_image.php doesn’t send any direct output to the browser, it’s quite
safe to put it above the DOCTYPE without forcing browsers into quirks mode.

3. Scroll down inside index.php and locate the code that displays the image in the
maincontent <div>. It looks like this:
<div id="pictureWrapper">
<img src="images/basin.jpg" alt="Water basin at Ryoanji temple" width="350" height="237" class="picBorder" />
</div>

4. Instead of using images/basin.jpg as a fixed image, replace it with $selectedImage. All the images have different dimensions, so delete the width and height attributes, and use a generic alt attribute. The code in step 3 should now look like this:

<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" />
</div>

5. Save both random_image.php and index.php, and load index.php into a browser.
The image should now be chosen at random. Click the Reload button in your
browser, and you should see a variety of images,

Adding a Caption to the image:

arrays can hold any type of data, including other arrays. To store more than one piece of information about an image, each image in the original $images array needs to be represented by a separate array. Each subarray has two elements: the filename and a caption.

This PHP solution builds on the previous one, so continue working with the same files.

1. Open random_image.php and change the code like this:
<?php
$images = array(
array('file' => 'kinkakuji',
'caption' => 'The Golden Pavilion in Kyoto'),
array('file' => 'maiko',
'caption' => 'Maiko—trainee geishas in Kyoto'),
array('file' => 'maiko_phone',
'caption' => 'Every maiko should have one—a mobile,
of course'),
array('file' => 'monk',
'caption' => 'Monk begging for alms in Kyoto'),
array('file' => 'fountains',
'caption' => 'Fountains in central Tokyo'),
array('file' => 'ryoanji',
'caption' => 'Autumn leaves at Ryoanji temple, Kyoto'),
array('file' => 'menu',
'caption' => 'Menu outside restaurant in Pontocho, Kyoto'),
array('file' => 'basin',
'caption' => 'Water basin at Ryoanji temple, Kyoto')
);
$i = rand(0, count($images)-1);
$selectedImage = "images/{$images[$i]['file']}.jpg";
$caption = $images[$i]['caption'];
?>
it’s an ordinary indexed array that contains eight items, each of which is an associative array containing definitions for 'file' and 'caption'. The definition of the multidimensional array forms a single statement, so there are no semicolons until
end.All the array elements in between are separated by commas. The deep indenting isn’t necessary, but it makes the code a lot easier to read.

The variable used to select the image also needs to be changed, because
$images[$i] no longer contains a string, but an array. To get the correct filename
for the image, you need to use $images[$i]['file']. The caption for the selected
image is contained in $images[$i]['caption'] and stored in a shorter variable.

2. You now need to amend the code in index.php to display the caption like this:
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" />
<p id="caption"><?php echo $caption; ?></p>
</div>

3. Add the following code to random_image.php just before the closing PHP tag:
if (file_exists($selectedImage) && is_readable($selectedImage)) {
$imageSize = getimagesize($selectedImage);
}

The if statement uses two functions, file_exists() and is_readable(), to make
sure $selectedImage not only exists, but also that it’s accessible (it may be corrupted or have the wrong permissions). These functions return Boolean values
(true or false), so they can be used directly as part of the conditional statement.

The single line inside the if statement uses the function getimagesize() to get the
image’s dimensions. The function returns an array containing four elements. By
assigning the result to $imageSize, you can extract the following information:
$imageSize[0]: The width of the image in pixels
$imageSize[1]: The height of the image in pixels
$imageSize[2]: A number indicating the type of file (see Chapter 8 for details)
$imageSize[3]: A string containing the height and width for use in an <img> tag

4. Finally let’s fix the code in step 2. Change it like this:
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" <?php echo $imageSize[3]; ?> />
<p id="caption"><?php echo $caption; ?></p>
</div>

5. Although this sets the dimensions for the image, you still need to control the width of the caption. You can’t use PHP inside an external stylesheet, but there’s nothing stopping you from creating a style block in the <head> of index.php. Put this code just before the closing </hea> tag:
<?php
if (isset($imageSize)) {
?>
<style type="text/css">
p#caption {
width: <?php echo $imageSize[0]; ?>px;
}
</styl>
<?php } ?>

9. The conditional statement at the foot of random_image.php sets $imageSize only if
the selected image both exists and is readable, so if $imageSize has been set, you
know it’s all systems go. Add the opening and closing blocks of a conditional statement around the <div> that displays the image in index.php like this:

<?php if (isset($imageSize)) { ?>
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image"
class="picBorder" <?php echo $imageSize[3]; ?> />
<p id="caption"><?php echo $caption; ?></div>
<?php } ?>

Images that exist will display normally, but you’ll avoid any embarrassing error messages in case of a missing or corrupt file—a much more professional look.

Note: When you are using include function better to provide condition before including the page like

$file = 'includes/randomimage.php'
if (file_exists($file) && is_readable($file)) {
include($file);
}

Leia Mais…

Tuesday, February 3, 2009

Automatically generating a page’s title from filename

basename(): Given a string containing a path to a file, this function will return the base name of the file.

STEPS:

1. Create a new PHP file and insert the following code between a pair of PHP tags

echo basename($_SERVER['SCRIPT_NAME'], '.php');

2.Save the page with any name you like (as long as it has a .php filename extension),
and load it into a browser. It should display the name of the file stripped of the
.php extension. The download file displays scriptname2.

You now have the basis for automatically creating the page title for every page in
your site, using basename(), $_SERVER['SCRIPT_NAME'], and an include file.

3. Create a new PHP file called title.inc.php and save it in the includes folder.

4. Strip out any code inserted by your file, and type in the following code
(the finished code for title.inc.php is in the test/includes folder of the download
files):
$title = basename($_SERVER['SCRIPT_NAME'], '.php');
?>

This finds the filename of the current page, strips the .php filename extension, and
assigns the result to a variable called $title.
Note: The code for this include file must be enclosed in PHP tags. This is because the whole file needs to be treated as PHP. Unlike the menu, it won’t be displayed directly inside other pages.

5. Open a PHP page in your script editor. If you’re using the test site, use
testcontact.php. Include title.inc.php by typing this above the DOCTYPE declaration:


6. Amend the "<title>" tag like this:
<title> My Test Php website </title>

This uses echo to display the value of $title. Because the string is enclosed in double quotes, PHP displays the value of $title

The variable $title has also been enclosed in curly braces because there is no
space between the em dash and $title. Although not always necessary, it’s a good
idea to enclose variables in braces when using them without any whitespace in a
double-quoted string, as it makes the variable clear to you and the PHP engine.

7. Save both pages and load the web page into a browser.

8. if you prefer an initial capital letter for the part of the title derived from the filename? Nothing could be simpler. PHP has a neat little function called ucfirst(), which does exactly that (the name is easy to remember once you realize that uc stands for “uppercase”). Add another line to the code in
step 4 like this:
$title = basename($_SERVER['SCRIPT_NAME'], '.php');
$title = ucfirst($title);
?>

9. A drawback with this technique is that filenames consist of only one word—at least
they should. If you’ve picked up bad habits from Windows and Mac OS X permitting
spaces in filenames, get out of them immediately. Spaces are not allowed in
URLs, which is why most web design software replaces spaces with %20. You can get
around this problem, though, by using an underscore. Change the name of the file
you’re working with so that it uses two words separated by an underscore. For
example, change contact.php to contact_us.php.

10. Change the code in title.inc.php like this:
$title = basename($_SERVER['SCRIPT_NAME'], '.php');
$title = str_replace('_', ' ', $title);
$title = ucwords($title);
?>

12. Save title.inc.php and load into a browser the file that you renamed

Leia Mais…

Monday, February 2, 2009

Creating arrays in PHP

There are two types of arrays
1.Indexed Arrays
2.Associative Arrays

1. Indexed Arrays:
Indexed arrays uses numbers to identify each element

Example:
To build an indexed array the direct way, use numbers instead of strings. Indexed arrays are numbered from 0,
$TestList[0] = 'wine';
$TestList[1] = 'fish';
$TestList[2] = 'bread';
$TestList[3] = 'grapes';
$TestList[4] = 'cheese';

2.Associative Arrays :
Associative arrays use strings to identify each element

Example:
$book['title'] = 'PHP Solutions: Dynamic Web Design Made Easy';
$book['author'] = 'XXXXXXXXXXXXXX';
$book['publisher'] = 'YYYYYYY';
$book['ISBN'] = '1234567';

Although both are perfectly valid ways of creating arrays, it’s a nuisance to have to type out the variable name each time.

Using array() to build an indexed array:
Instead of declaring each array element individually, you declare the variable name
once, and assign all the elements by passing them as a comma-separated list to array()

Example
$TestList= array('wine', 'fish', 'bread', 'grapes', 'cheese');

PHP numbers each array element automatically, beginning from 0, so this creates exactly the same array as if you had numbered them individually.

To add a new element to the end of the array, use a pair of empty square brackets like $TestList[] = 'coffee';
So finally total values becomes $TestList[5].

Using array() to build an associative array

The shorthand way of creating an associative array uses the => operator (an equal sign followed by a greater-than sign) to assign a value to each array key. The basic structure looks like
$arrayName = array('key1' => 'element1', 'key2' => 'element2');
Example:
$book = array('title' => 'PHP Solutions: Dynamic Web Design Made Easy',
'author' => 'XXXXX',
'publisher' => 'YYYYYYY',
'ISBN' => '123456');

Using array() to create an empty array
The very two reasons for creating an empty array are

1.Initializing as array - To create an array so that it’s ready to have elements added to it inside a loop.
2.To clear all elements from an existing array

Example : $TestList= array();

Multidimensional arrays

Array elements can store any data type, including other arrays.
Example:
$books = array(
array(
'title' => 'PHP Solutions: Dynamic Web Design Made Easy',
'author' => 'XXXX',
'publisher' => 'YYYYYY',
'ISBN' => '122122'),
array(
'title' => 'Beginning PHP and MySQL 5',
'author' => 'CCCCCCCC',
'publisher' => 'WWWWW',
'ISBN' => '999999')
);

This example shows associative arrays nested inside an indexed array, but multidimensional arrays can nest either type. To refer to a specific element use the key of both arrays.
for example: $books[1]['author'] -- outputs "CCCCCCCC".

Using print_r() to inspect an array

To check the content of an array during testing, pass the array to print_r()
Example: print_r($books);
OUTPUT will be:
Array
{
[0] => Array
{
'title' => 'PHP Solutions: Dynamic Web Design Made Easy',
'author' => 'XXXX',
'publisher' => 'YYYYYY',
'ISBN' => '122122'),
}
[1] => Array
{
'title' => 'Beginning PHP and MySQL 5',
'author' => 'CCCCCCCC',
'publisher' => 'WWWWW',
'ISBN' => '999999')
}
}

Note:Always use print_r() to inspect arrays; echo and print don’t work. To display the contents of an array in a web page use a foreach loop.

Leia Mais…

Sunday, February 1, 2009

Data Types In PHP

Even though PHP is weakly typed, it uses the following eight data types

Integer: This is a whole number, such as 1, 25, 42, or 2006. Integers must not contain any commas or other punctuation as thousand-separators. You can also use hexadecimal numbers, which should be preceded by 0x (e.g., 0xFFFFFF, 0x000000).

Floating-point number: This is a number that contains a decimal point, such as 9.99, 98.6, or 2.1. Like integers, floating-point numbers must not contain thousandseparators.(This type is also referred to as float or double.)

String: A string is text of any length. It can be as short as zero characters (an empty string), and it has no upper limit.

Boolean: This type has only two values: true or false.

Array: An array is a variable that is capable of storing multiple values, although it may contain none at all (an empty array). Arrays can hold any data type, including other arrays. An array of arrays is called a multidimensional array.

Object: PHP has powerful object-oriented capabilities, which are mainly of interest to advanced users. Objects are used when connecting to a database with the MySQL Improved extension or PHP Data Objects (PDO).

Resource: When PHP connects to an external data source, such as a file or database,it stores a reference to it as a resource.

NULL: This is a special data type that indicates that a variable has no value.

Leia Mais…