Wednesday, February 25, 2009

Sending Mails with Attachments

Sending mails with an attachment is more similar to the Sending the general mails. We need to concentrate on the content types.

Example:

we have a form

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data" name="form1">
From name: <input type="text" name="fromname">
From e-mail: <input type="text" name="fromemail">
File: <input type="file" name="filename">
<input type="submit" name="Submit" value="Submit">
</form>

Here we have an to email address text box and the from email textbox an and file option is provided to upload the file.

Here now when an attchment is done and uploaded, Then we retrieve the from email address and the to email address and proceed to the below code

if ($_SERVER['REQUEST_METHOD']=="POST"){

// here we check the form is posted or not

$to="totest@testing.com"; // here we retrieve to email address value

$subject="E-mail with attachment"; // Here we store the subject of the mail.

$from = stripslashes($_POST['fromname']) // Here we retrieve the from email address

Now store the file information(uploaded value) to variables for easier access.

$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];

Now we start creating the message content

$message="<html><body><h1>your are trying to send a mail with attachment</h1>";
$message=$message. "Here is your file: $name";

// if the upload succeded, the file will exist
if (file_exists($tmp_name)){

// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){

// open the file for a binary read
$file = fopen($tmp_name,'rb');

// read the file content into a variable
$data = fread($file,filesize($tmp_name));

// close the file
fclose($file);

// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";

// next, we'll build the message body
// note that we insert two dashes in front of the
// MIME boundary when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";

// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content and set another boundary to
// indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

// now we just send the message
if (@mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
}

Leia Mais…

Monday, February 23, 2009

Handling multiple-choice form elements

To work successfully with forms, you need to know how to handle multiple-choice elements, namely:

1. Radio buttons
2. Check boxes
3. Drop-down option menus
4. Multiple-choice lists

1. Radio buttons:Radio button groups allow you to pick only one value. This makes it easy to retrieve the selected one.All buttons in the same group must share the same name attribute, so the $_POST array contains the value attribute of whichever radio button is selected. If no button is selected, the radio button group’s $_POST array element remains unset. This
is different from the behavior of text input fields, which are always included in the
$_POST array, even if they contain nothing.You need to take this into account in the code that preserves the selected value when a required field is omitted.

For Example in a form we have a radio buttons
<input type="radio" name="testing" value="radiovalue1">
<input type="radio" name="testing" value="radiovalue2">

To retrieve the value we write the code as
1. We will check whether radio button is clicked or not by
$OK = isset($_POST['testing']) ? true : false;
This uses the conditional operator to check whether $_POST['testing'] is set. The
only reason for this line is to avoid having to type isset($_POST['testing']) in both if statements. With only two buttons in the radio group, this may hardly seem worthwhile, but I’ve used the same technique in all multiple-choice elements, and it certainly makes things easier when you have six items in a group, as is the case with the check boxes and multiple-choice list.

2. Then we retrieve by $_POST['testing']

2. Check Boxes : Check boxes are similar to radio button groups, except that they permit multiple selections. This affects how you name a check box group and extract the selected values.
Here we have 2 things we have to remember

1. Check box creates an array.you need to set a default value before attempting to build the body of the email. This time, rather than a string, it needs to be presented as an array like this:
// set default values for variables that might not exist
$subscribe = isset($subscribe) ? $subscribe : 'Nothing selected';
$interests = isset($interests) ? $interests : array('None selected');

2.To extract the values of the check box array, you can use a foreach loop or the implode() function. This oddly named function joins array elements. It takes two arguments: a string to be used as a separator and the array. So, implode(', ', $interests) joins the elements of $interests as a comma-separated string.

<fieldset id="interests">
<h2>Interests in Japan</h2>
<div>
<p>
<input type="checkbox" name="interests[]" value="Anime/manga" id="anime"
<?php
$OK = isset($_POST['interests']) ? true : false;
if ($OK && isset($missing) && in_array('Anime/manga',
$_POST['interests'])) { ?>
checked="checked"
<?php } ?>
/>
<label for="anime">Anime/manga</label>
</p>
<p>
<input type="checkbox" name="interests[]" value="Arts & crafts"
id="art"
<?php
if ($OK && isset($missing) && in_array('Arts & crafts', $_POST['interests'])) { ?>
checked="checked"
<?php } ?>
/>
<label for="art">Arts & crafts</label>
</p>
</div>
</fieldset>

The really important thing to note about this code is the empty pair of square brackets following the name attribute of each check box. This tells PHP to treat interests as an array. If you omit the brackets, $_POST['interests'] contains the value of only the first check box selected; all others are ignored.


OR Simply you can read the Check box value by $_POST['interests']

One thing need to be checked is whether the checkbox are checked or not by:
As with radio buttons, if no check box is selected, the $_POST['interests'] element
is not even created. So the code for the first check box contains the following:
$OK = isset($_POST['interests']) ? true : false;

3.drop-down option menu( SELECT TAG ): Drop-down option menus created with the <select> tag are similar to radio button groups in that they normally allow the user to pick only one option from several. Where they differ is one item is always selected in a drop-down menu, even if it’s only the first item inviting the user to select one of the others. As a result, this means that the $_POST array always contains an element referring to a menu, whereas a radio button group is ignored unless a default value is present.

The following code shows the first two items from the drop-down menu

the PHP code wraps the attribute that indicates which item has been chosen. Although this attribute is called checked in radio buttons and check boxes, it’s called selected in <select> menus and lists. It’s important to use the correct attribute to redisplay the selection if the form is submitted with required items missing. When the page first loads, the $_POST array contains no elements, so you can select the first <option> by testing for !$_POST. Once the form is submitted, the $_POST array always contains an element from a drop-down menu, so you don’t need to test for its existence.

<p>
<label for="select">How did you hear of Japan Journey?</label>
<select name="howhear" id="howhear">
<option value="No reply"
<?php
if (!$_POST || $_POST['howhear'] == 'No reply') { ?>
selected="selected"
<?php } ?>
>Select one</option>
<option value="foED"
<?php
if (isset($missing) && $_POST['howhear'] == 'foED') { ?>
selected="selected"
<?php } ?>
>friends of ED</option>
</select>
</p>

Because there is always an element in the $_POST array for a drop-down menu, it
doesn’t require any special handling in the code that builds the body of the email.

Multiple-choice list(SELECT TAG WITH OPTION SELECTED MULTIPLE)

Multiple-choice lists are similar to check boxes: they allow the user to choose zero or more
items, so the result is stored in an array. If no items are selected, the $_POST array contains no reference to the list, so you need to take that into consideration both in the form and when processing the message.

<p>
<label for="select">What characteristics do you associate with
Japan?</label>
<select name="characteristics[]" size="6" multiple="multiple"
id="characteristics">
<option value="Dynamic"
<?php
$OK = isset($_POST['characteristics']) ? true : false;
if ($OK && isset($missing) && in_array('Dynamic',
$_POST['characteristics'])) { ?>
selected="selected"
<?php } ?>
>Dynamic</option>
<option value="Honest"
<?php
if ($OK && isset($missing) && in_array('Honest',
$_POST['characteristics'])) { ?>
selected="selected"
<?php } ?>
>Honest</option>

</select>
</p>

In the code that processes the message, set a default value for a multiple-choice list
in the same way as for an array of check boxes.

$interests = isset($interests) ? $interests : array('None selected');
$characteristics = isset($characteristics) ? $characteristics : array('None selected');

When building the body of the message, use a foreach loop to iterate through the
subarray, or use implode() to create a comma-separated string like this:
$message .= 'Characteristics associated with Japan: '.implode(', ',$characteristics);


Redirecting to another page

header('Location: http://www.example.com/thanks.php');

When using the header() function, you must be very careful that no output is sent to the
browser before PHP attempts to call it. If, when testing your page, you see an error message
warning you that headers have already been sent, check there are no new lines or other whitespace ahead of the opening PHP tag. Also check any include files for whitespace
and new lines before the opening PHP tag and after the closing one. The error is frequently
triggered by a single new line after the closing tag of an include file.

Leia Mais…

Monday, February 16, 2009

Mail Function in PHP

The PHP mail() function takes up to five arguments, all of them strings, as follows:

1. The address(es) of the recipient(s)
2. The subject line
3. The message body
4. A list of other email headers
5. Additional parameters

1. The first three arguments are required. Email addresses in the first argument can be in
either of the following formats:

'user@example.com'
'Some Guy '

To send to more than one address, use a comma-separated string like this:
'user@example.com, another@example.com, Some Guy '

2. The second argument is a string containing the subject line.

3. The third argument is the message body, which must be presented as a single
string, regardless of how long it is.

4. Most people are unlikely to need the fifth argument, although some hosting
companies now make it a requirement. It ensures that the email is sent by a
trusted user, and it normally consists of -f followed (without a space) by your
own email address, all enclosed in quotes. Check your hosting company’s instructions to see whether this is required and the exact format it should take.

The importance of mail() Function:

program. It passes the address, subject line, message, and any additional email headers to the web server’s mail transport agent (MTA). PHP’s responsibility ends there. It has no way of knowing if the email is delivered to its intended destination.
Note: Email doesn’t always arrive when testing mail() in a local testing environment.
Normally, this has nothing to do with your configuration, but with your service
provider’s security policies. If email fails to arrive, upload the script to your remote server and test it there.

Removing unwanted backslashes from form input:

Eliminating magic quotes

Make sure magic quotes function is not disables.If your magic quotes is off then our single quotes and special characters may provide an error

Like '(apostaphis), spaces etc

Even if your Magic Quotes are off. You can enable them by using the following function.

if (function_exists('nukeMagicQuotes')) {
nukeMagicQuotes();
}
?

Code for sending mail is:

if (array_key_exists('send', $_POST)) {
$to = 'me@example.com'; // use your own email address
$subject = 'Feedback from Japan Journey site';
// process the $_POST variables
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// build the message
$message = "Name: $name\n\n";
$message .= "Email: $email\n\n";
$message .= "Comments: $comments";
// limit line length to 70 characters
$message = wordwrap($message, 70);
// send it
$mailSent = mail($to, $subject, $message);
}

Note:
1. This entire section of code is wrapped in an if statement, which uses the function
array_key_exists(). here send name attribute of the form’s submit button

2. array_key_exists() is a foolproof way of checking that a form has been submitted.When the page first loads, there’s no way that the submit button can have been clicked, so its name isn’t present in the $_POST array. As a result, array_key_exists('send', $_POST) equates to false, and everything inside the if statement is ignored. However, as soon as the button is clicked, the page reloads, array_key_exists('send',$_POST) equates to true, and the email script is processed

Description of the above code:

The code that does the processing consists of five stages. The first two lines assign
your email address to $to and the subject line of the email to $subject. The next section labeled “process the $_POST variables” reassigns $_POST['name'], _POST['email'], and $_POST['comments'] to ordinary variables. This makes them easier to handle when you subject them to security checks or style the email later. Next, you build the body of the email message, which must consist of a single string. By using double quotes, you can embed the variables in the string and use \n to insert new line characters. Once the message body is complete, it’s passed to the wordwrap() function,which takes two arguments: a string and an integer that sets the maximum length of each line. Although most mail systems will accept longer lines, it’s recommended to limit each line to70 characters.

After the message has been built and formatted, the recipient’s address, the subject
line, and the body of the message are passed to the mail() function. The function
returns a Boolean value indicating whether it succeeded in passing the email to the
MTA. So, it’s useful to capture that value as $mailSent. You can then use $mailSent
to redirect the user to another page or change the contents of the current one.

Simply you can include the code after your mail() function

<?php
if ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message.
Please try later.<?php
}
elseif ($_POST && $mailSent) {
?>

An important note before sending a mail is check whether the required fields are empty or not.

// process the $_POST variables
foreach ($_POST as $key => $value) {
// assign to temporary variable and strip whitespace if not an array
$temp = is_array($value) ? $value : trim($value);
// if empty and required, add to $missing array
if (empty($temp) && in_array($key, $required)) {
array_push($missing, $key);
}
// otherwise, assign to a variable of the same name as $key
elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
// build the message
<p><strong>Your message has been sent. Thank you for your feedback.
</strong></p>
<?php } ?>

Leia Mais…

Sunday, February 15, 2009

Sending email in PHP

The PHP mail() function takes up to five arguments, all of them strings, as follows:

1. The address(es) of the recipient(s)
2. The subject line
3. The message body
4. A list of other email headers
5. Additional parameters

1. The first three arguments are required. Email addresses in the first argument can be in
either of the following formats:

'user@example.com'
'Some Guy '

To send to more than one address, use a comma-separated string like this:
'user@example.com, another@example.com, Some Guy '

2. The second argument is a string containing the subject line.

3. The third argument is the message body, which must be presented as a single
string, regardless of how long it is.

4. Most people are unlikely to need the fifth argument, although some hosting
companies now make it a requirement. It ensures that the email is sent by a
trusted user, and it normally consists of -f followed (without a space) by your
own email address, all enclosed in quotes. Check your hosting company’s instructions to see whether this is required and the exact format it should take.

The importance of mail() Function:

program. It passes the address, subject line, message, and any additional email headers to the web server’s mail transport agent (MTA). PHP’s responsibility ends there. It has no way of knowing if the email is delivered to its intended destination.
Note: Email doesn’t always arrive when testing mail() in a local testing environment.
Normally, this has nothing to do with your configuration, but with your service
provider’s security policies. If email fails to arrive, upload the script to your remote server and test it there.

Removing unwanted backslashes from form input:

Eliminating magic quotes

Make sure magic quotes function is not disables.If your magic quotes is off then our single quotes and special characters may provide an error

Like '(apostaphis), spaces etc

Even if your Magic Quotes are off. You can enable them by using the following function.

if (function_exists('nukeMagicQuotes')) {
nukeMagicQuotes();
}
?

Code for sending mail is:

if (array_key_exists('send', $_POST)) {
$to = 'me@example.com'; // use your own email address
$subject = 'Feedback from Japan Journey site';
// process the $_POST variables
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// build the message
$message = "Name: $name\n\n";
$message .= "Email: $email\n\n";
$message .= "Comments: $comments";
// limit line length to 70 characters
$message = wordwrap($message, 70);
// send it
$mailSent = mail($to, $subject, $message);
}

Note:
1. This entire section of code is wrapped in an if statement, which uses the function
array_key_exists(). here send name attribute of the form’s submit button

2. array_key_exists() is a foolproof way of checking that a form has been submitted.When the page first loads, there’s no way that the submit button can have been clicked, so its name isn’t present in the $_POST array. As a result, array_key_exists('send', $_POST) equates to false, and everything inside the if statement is ignored. However, as soon as the button is clicked, the page reloads, array_key_exists('send',$_POST) equates to true, and the email script is processed

Description of the above code:

The code that does the processing consists of five stages. The first two lines assign
your email address to $to and the subject line of the email to $subject. The next section labeled “process the $_POST variables” reassigns $_POST['name'], _POST['email'], and $_POST['comments'] to ordinary variables. This makes them easier to handle when you subject them to security checks or style the email later. Next, you build the body of the email message, which must consist of a single string. By using double quotes, you can embed the variables in the string and use \n to insert new line characters. Once the message body is complete, it’s passed to the wordwrap() function,which takes two arguments: a string and an integer that sets the maximum length of each line. Although most mail systems will accept longer lines, it’s recommended to limit each line to70 characters.

After the message has been built and formatted, the recipient’s address, the subject
line, and the body of the message are passed to the mail() function. The function
returns a Boolean value indicating whether it succeeded in passing the email to the
MTA. So, it’s useful to capture that value as $mailSent. You can then use $mailSent
to redirect the user to another page or change the contents of the current one.

Simply you can include the code after your mail() function

<?php
if ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message.
Please try later.<?php
}
elseif ($_POST && $mailSent) {
?>

An important note before sending a mail is check whether the required fields are empty or not.

// process the $_POST variables
foreach ($_POST as $key => $value) {
// assign to temporary variable and strip whitespace if not an array
$temp = is_array($value) ? $value : trim($value);
// if empty and required, add to $missing array
if (empty($temp) && in_array($key, $required)) {
array_push($missing, $key);
}
// otherwise, assign to a variable of the same name as $key
elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
// build the message

Your message has been sent. Thank you for your feedback.


Leia Mais…

Thursday, February 12, 2009

Keeping safe with PHP superglobals

While I’m on the subject of security, it’s worth explaining the background to the PHP
superglobal arrays, which include $_POST and $_GET. The $_POST array contains data sent
using the post method. So it should come as no surprise that data sent by the get method
is in the $_GET array.

Before the release of PHP 4.2.0 in April 2002, you didn’t need to worry about using special
arrays to access data submitted from a form. If the name of the form element was email,
all that was necessary was to stick a dollar sign on the front, like this: $email. Bingo, you had instant access to the data. It was incredibly convenient. Unfortunately, it also left a gaping security hole. All that an attacker needed to do was view the source of your web page and pass values to your script through a query string.

When the loophole was closed, millions of PHP scripts stopped working. Inexperienced
web developers were up in arms, and harassed hosting companies changed a setting called
register_globals in php.ini to restore a little peace to their lives. You will find lots of
“advice” on the Internet to turn register_globals on in php.ini, because it will make
your life easier. This is completely misguided. Turning on register_globals is foolish for

the following reasons:
1. It’s totally insecure.
2. There is no way to override the setting for individual scripts. If your hosting company
turns register_globals off, any scripts that rely on it will break.
3. The register_globals setting has been removed completely from PHP 6. Scripts
that rely on register_globals won’t work, period.

It’s very easy to write scripts that don’t rely on register_globals, so it’s not the major
burden that some people imply. It just requires putting the name of the form element in quotes between square brackets after $_POST or $_GET, depending on the form’s method attribute.

So email becomes $_POST['email'] if sent by the post method, and $_GET['email'] if
sent by the get method. That’s all there is to it. Although the post method is more secure than get, you shouldn’t assume that it’s 100% safe. For secure transmission, you need to use encryption or the Secure SocketsLayer (SSL).

You may come across scripts that use $_REQUEST, which avoids the need to distinguish
between $_POST or $_GET. It’s less secure. Always use $_POST or $_GET instead.
Old scripts may use $HTTP_POST_VARS or $HTTP_GET_VARS, which have exactly the same
meaning as $_POST and $_GET. The longer versions have been removed from PHP 6. Use
$_POST and $_GET instead.

Leia Mais…

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…