Understanding Basic OOP Concepts
Before you start creating objects in PHP, it helps to understand
some basic concepts of object – oriented programming. In the following
sections, you explore classes, objects, properties, and methods. These are the
basic building blocks that you can use to create object - oriented applications
in PHP.
Classes
In the real world, objects have characteristics and behaviors. A
car has a color, a weight, a manufacturer, and a gas tank of a certain volume.
Those are its characteristics. A car can accelerate, stop, signal for a turn,
and sound the horn. Those are its behaviors. Those characteristics and
behaviors are common to all
cars. Although different cars may have different colors, all
cars have a color.
With OOP, you can model the general idea of a car — that is,
something with all of those qualities — by using a class . A class is a unit of code that describes the characteristics
and behaviors of something, or of a group of things. A class called Car , for example, would describe the characteristics
and behaviors common to all cars.
Objects
An object is a specific instance of a class. For example,
if you create a Car class, you might then go on
to create an object called myCar that belongs to the Car class. You could then create a second object, yourCar
, also based on the Car class. Think of a class as a blueprint, or
factory, for constructing an object. A class specifies the characteristics that
an object will have, but not necessarily the specific values of those characteristics.
Meanwhile في غضون, an object is constructed using the blueprint provided by a
class, and its characteristics have specific values. For example, the Car class might indicate merely that cars should have
a color, whereas a specific myCar object might be colored red.The distinction between classes and
objects is often confusing to those new to OOP. It helps to think of classes as
something you create as you design your application, whereas objects are
created and used when the application is actually run.
Properties
In OOP terminology, the characteristics of a class or object are
known as its properties . are much like regular variables, in that they
have a name and a value
Some properties allow their value to be changed and others do
not. For example, the Car class might have properties
such as color and weight . Although the color of the car can be changed by
giving it a new paint job, the weight of the car (without cargo or passengers)
is a fixed value.
Methods
The behaviors of a class that is, the actions associated with
the class are known as its Methods are very similar to functions; in fact, you
define methods in PHP using the function statement. some methods act on external data
passed to them as arguments, but an object ’ s method can also access the
properties of the object. For example, an accelerate method of the Car class might check the fuel property to make sure it has enough fuel to move
the car. The method might then update the object's velocity سرعةproperty to reflect the fact that the car has accelerated. The
methods of a class, along with its properties, are collectively known as members of the class.
Creating and Using Properties
Class properties are very similar to variables; for example, an object'
s property can store a single value, an array of values, or even another
object.
Understanding Property Visibility
Before diving into creating properties in PHP, it 's worth
taking a look at an important concept of classes known as visibility . Each property of a class in PHP can have one of three
visibility levels, known as public, private, and protected: Public properties can be accessed by any code, whether that code is inside or
outside the class. If a property is declared public, its value can be read
or changed from anywhere in your script
Private properties of a class can be accessed only by code inside the class. So if
you create a property that' s declared private, only methods inside the same
class can access its contents.
(If you attempt to access the property outside the class, PHP
generates a fatal error.)
Protected class
properties are a bit like private properties in that they can't be accessed by
code outside the class, but there' s one subtle difference: any class
that inherits from the class can also access the properties.Generally
speaking, it' s a good idea to avoid creating public properties wherever
possible. Instead, it' s safer to create private properties, then to create
methods that allow code outside the class to access those properties.
Declaring Properties
class MyClass {
public $property1; // This
is a public property
private $property2; //
This is a private property
protected $property3; //
This is a protected property
}
By the way, you can also initialize properties at the time that
you declare them, much like you can with variables:
class MyClass {
public $widgetsSold = 123;
}
In this case, whenever a new object is created from MyClass , the object ’ s $widgetsSold property defaults to the value 123 .
Accessing Properties
Once you 've created a class property, you can access the
corresponding object's property value from within your calling code by using
the following syntax:
$object-> property;
That is, you write the name of the variable storing the object,
followed by an arrow symbol composed of a hyphen ( - ) and a greater - than symbol (> ), followed
by the property name. (Note that the property name doesn ’ t have a $ symbol before it.)
Here ’ s an example that shows how to define properties then set
and read their values:
<!DOCTYPE html>
<head>
<title> Defining and
Using Object Properties </title>
</head>
<body>
<h1> Defining and
Using Object Properties </h1>
<?php
class Car {
public $color;
public $manufacturer;
}
$beetle = new Car();
$beetle->color =
"red";
$beetle-> manufacturer =
"Volkswagen";
$mustang = new Car();
$mustang-> color =
"green";
$mustang-> manufacturer
= "Ford";
echo " <h2> Some
properties: </h2> ";
echo " <p> The
Beetle’s color is " . $beetle-> color . ". </p>
";
echo " <p> The
Mustang’s manufacturer is " . $mustang-> manufacturer . ".
</p> ";
echo " <h2> The
\$beetle Object: </h2> <pre> ";
print_r($beetle);
echo "
</pre>";
echo " <h2> The
\$mustang Object: </h2> <pre> ";
print_r($mustang);
echo " </pre>
";
?>
</body>
</html>
The script defines a class, Car , with two public properties, $color and $manufacturer . Then it creates a new Car object and assigns it to a variable called $beetle , and sets $beetle' s $color and $manufacturer properties to “red” and “Volkswagen” , respectively. Next the script creates another Car object, assigns it to $mustang , and sets its $color property to “green” and its $manufacturer property to “Ford”. Now that the two objects have been created and
their properties set, the script displays the values of a couple of properties:
the $color property of the $beetle object ( $beetle -> color ) and the $manufacturer property of the $mustang object ( $mustang - >
manufacturer ). Finally, the script uses
print_r() to display the two objects; notice how print_r()
displays an object ’ s
properties in much
the same way as it displays array keys and values.
Static Properties
Using Static Variables to Preserve Values
As
you ’ ve seen, variables that are local to a function don ’ t exist outside the
function. In fact, all variables declared within a function are deleted when
the function exits, and created anew when the function is next called. This is
usually what you want to happen, because it allows you to write nicely self –
contained functions that work independently of each other. However, sometimes
it ’ s useful to create a local variable that has a somewhat longer lifespan. Static variables let you do just this. These types of variables are still local
to a function, in the sense that they can be accessed only within the function
’ s code. However, unlike local variables, which disappear when a function
exits, static variables remember their values from one function call to the
next. To declare a local variable as static, all you need to do is write the
word static before the variable name,
and assign an initial value to the variable:
static $var = 0; You can also create static class properties in
by adding the static keyword just before the
property name:
class MyClass {
public static
$myProperty;
}
Static members of a class are independent of any particular
object derived (copied) from that class. To access a static property, you write the
class name, followed by two colons ( :: ), followed by the property name
(preceded by a $ symbol):
class Car {
public $color;
public
$manufacturer;
static public
$numberSold = 123;
}
Car::$numberSold++;
echo
Car::$numberSold; // Displays “124”
The first time the function
is called, the variable is set to its initial value (zero in this example).
However,
if the variable ’ s value is
changed within the function, the new value is remembered the next time the
function is called. The
value is remembered only as long as the script runs, so the next time you run
the script the variable is
reinitialized.So when might you use static variables? Here ’ s a situation
where a local variable isn ’ t much use:
function nextNumber() {
$counter = 0;
return ++$counter;
}
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
This code outputs the
following:
I’ve
counted to: 1
I’ve
counted to: 1
I’ve
counted to: 1
Each time the nextNumber() function is called, its $counter local variable is re -
created and initialized
to zero. Then it ’ s
incremented to 1 and its value is returned to the calling code. So the function
always
returns 1, no matter how
many times it ’ s called.
However, by making a small
change to turn $counter into a static variable, the script produces the
expected output:
function nextNumber() {
static $counter = 0;
return ++$counter;
}
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
Now the code displays:
I’ve
counted to: 1
I’ve
counted to: 2
I’ve
counted to: 3
Creating Anonymous Functions: PHP lets you create anonymous functions — that
is, functions that have no name. You might want to create anonymous functions
for two reasons:
-To create functions dynamically — You can customize the code
within an anonymous function at the time that you create it. Although you ’ ll
rarely need to do this, it can make your code very flexible in certain specific
situations
-To create short- term, disposable في
المتناول functions — Commonly, you do this when you work
with built – in functions that require you to create a callback or event
handler function to work with. Examples include xml_set_element_handler() , which you meet in Chapter 19 , and array
functions such as array_walk() ,
which lets you apply a function to each value in an array, and usort() , which sorts an array ’ s elements according to
a comparison function that you create yourself
To create an anonymous function, you use create_function()
. This expects two
arguments:
$myFunction =
create_function( ‘$param1, $param2’, ‘function
code here;’ );
Here's a trivial example that creates an anonymous function dynamically
based on the value of a variable:
$mode = “+”;
$processNumbers =
create_function( ‘$a, $b’, “return \$a $mode \$b;” );
echo $processNumbers( 2, 3
); // Displays “5”
This code uses the value of the $mode variable as the operator used to process its two
arguments, $a and $b . For example, if you change $mode to “ * ” , the code displays “ 6 ” instead (2 times 3). In itself this code is
rather pointless, but if you can imagine a more complex function, where its
contents are determined by external factors such as user input, you can see
that it ’ s a potentially powerful feature of PHP. More commonly, you ’ ll use
anonymous functions to create callback functions as required by certain built -
in functions, as shown in the following example.
Sorting Words by Length
This example script takes a block of text and sorts all the
words within the text by the number of
letters in each word, shortest word first. To do this, it uses
anonymous functions, along with PHP’s
built-in usort(), preg_replace(), array_unique(), and preg_split() functions.
Save the script as sort_words_by_length.php
in your document root
folder, then run it in your browser. You should see a page similar to Figure
7-5.
<!DOCTYPE
html>
<html
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head>
<title>Sorting
words in a block of text by length</title>
<link
rel="stylesheet" type="text/css"
href="common.css" />
</head>
<body>
<h1>Sorting
words in a block of text by length</h1>
<?php
$myText =
<<<END_TEXT
But think not that
this famous town has
only harpooneers,
cannibals, and
bumpkins to show her
visitors. Not at
all. Still New
Bedford is a queer place.
Had it not been for
us whalemen, that
tract of land would
this day perhaps
have been in as
howling condition as the
coast of Labrador.
END_TEXT;
echo
"<h2>The text:</h2>";
echo "<div
style=\"width: 30em;\">$myText</div>";
$myText =
preg_replace( "/[\,\.]/", "", $myText );
$words =
array_unique( preg_split( "/[ \n\r\t]+/", $myText ) );
usort($words,
create_function('$a, $b', 'return strlen($a) - strlen($b);' ) );
echo
"<h2>The sorted words:</h2>";
echo "<div
style=\"width: 30em;\">";
foreach ( $words as
$word ) {
echo "$word
";
}
echo
"</div>";
?>
</body>
</html>
Figure 7-
preg_replace ( search_for, replace_with, your_data ,
optional_limit, optional_count )
The limit will default to -1 which is no limit. Remember your_data can be a
string or an array.
<?
$data = "The cat likes to sit on the
fence. He also likes to climb the tree.";
$find ="/the/";
$replace ="a";
//1. replace single word
Echo "$data <br>";
Echo preg_replace ($find, $replace,
$data);
//create arrays
$find2 = array ('/the/', '/cat/');
$replace2 = array ('a', 'dog');
//2. replace with array values
Echo preg_replace ($find2, $replace2,
$data);
//3. Replace just once
Echo preg_replace ($find2, $replace2,
$data, 1);
//4. Keep a count of replacements
$count = 0;
Echo preg_replace ($find2, $replace2,
$data, -1, $count);
Echo "<br>You have made $count replacements";
?>
Preg_Match PHP Function
The Preg_Match PHP function is used to search a
string, and return a 1 or 0. If the search was successful a 1 will be returned,
and if it was not found a 0 will be returned. Although other variables can be
added, it is most simply phrased as: preg_match(search_pattern, your_string).
The search_pattern needs to be a regular expression. If you are unfamiliar with
them this article gives you an overview of the syntax.
<?
$data = "I had a box of cerial for
breakfast today, and then I drank some juice.";
if (preg_match("/juice/",
$data))
{
echo "You had juice.<br>";
}
else
{
echo "You had did not have
juice.<br>";
}
if (preg_match("/eggs/",
$data))
{
echo "You had eggs.<br>";
}
else
{
echo "You had did not have
eggs.<br>";
}
?>
The function Preg_Spilit is used to
take a string, and put it into an array. The string is broken up into different
values in the array based upon your input. It is phrased as
preg_split ( split_pattern, your_data, optional_limit,
optional_flags )
<?php
$str = 'I like goats. You like cats. He likes
dogs.';
$chars = preg_split('//', $str);
print_r($chars);
echo "<p>";
$words= preg_split('/ /', $str);
print_r($words);
echo "<p>";
$sentances= preg_split('/\./', $str, -1
, PREG_SPLIT_NO_EMPTY);
print_r($sentances);
?>
In the code above we preform
three splits. In our first, we split the data by each character. In the second,
we split it with a blank space, thus giving each word (and not each letter) an
array entry. And in our third example we use a '.' period to split the data,
therefor giving each sentence it's own array entry.
Array ( [0] => [1] => I [2] => [3] => l [4]
=> i [5] => k [6] => e [7] => [8] => g [9] => o [10] => a
[11] => t [12] => s [13] => . [14] => [15] => Y [16] => o
[17] => u [18] => [19] => l [20] => i [21] => k [22] => e
[23] => [24] => c [25] => a [26] => t [27] => s [28] => .
[29] => [30] => H [31] => e [32] => [33] => l [34] => i [35]
=> k [36] => e [37] => s [38] => [39] => d [40] => o [41]
=> g [42] => s [43] => . [44] => )
Array ( [0] => I [1] => like [2] => goats. [3]
=> You [4] => like [5] => cats. [6] => He [7] => likes [8] =>
dogs. )
Array ( [0] => I like goats [1] => You like cats [2]
=> He likes dogs )
------------------------output-------------------------
preg_grep ( search_pattern, $your_array, optional_inverse ) The search_pattern needs to be a regular expression. If you
are unfamiliar with them this article
gives you an overview of the syntax.
<?
$data = array(0, 1, 2, 'three', 4, 5, 'six',
7, 8, 'nine', 10);
$mod1 = preg_grep("/4|5|6/",
$data);
$mod2 = preg_grep("/[0-9]/",
$data, PREG_GREP_INVERT);
print_r($mod1);
echo "<br>";
print_r($mod2);
?>
array_unique
Remove duplicate values from an array:
Forms HTML
The form
Element
<form
action="url_to_send_data" method="get/post">
important
attributes in an opening <form> tag, and these are:
method:
This
tells the browser how to send the data in the form when the user clicks the
Submit
button. The options are get and post.
HTTP
GET
The
HTTP GET protocol
attaches data to the actual URL text to pass the data to the destination
specified
in the action attribute. You have probably noticed URLs that resemble the
following:
http://www.on-target-games.com/forms.cgi?id=45677&data=Taarna
The
data appears after the question mark and is in name/value pairs. For example,
the name id
has the
value of 45677, and the name data
has the value of Taarna.
Because the data is
passed in the text of the URL, it is easy to implement — you can pass data
by simply adding
appropriate text to the URL used to call the data handler. However, GET is also
inherently
insecure. Never use GET to send confidential, unencrypted data to a handler because
the data is clearly
visible in most user agents and can be easily sniffed by hackers.
HTTP
POST
The HTTP POST method
passes data encoded in the HTTP data stream. As such, it is not typically
visible to a user
and is therefore a more secure method to pass data, but it can be harder
to implement.
Thankfully, HTML forms and most other Web technologies make passing data via
POST
a trivial task.
Action:
This
attribute tells the browser where
to send the data this will specify
another web page that can read and interpret the data entered.
Attribute
Values
accept
: A comma-separated list of content types that the
handler’s server will accept
acceptcharset
: A comma-separated list of character sets the form
data may be in
enctype:
The content type of the form data
id:
A unique identifier for the form object (replaces
the name attribute)
name:
The name of the form (deprecated, use the id attribute
instead)
target:
Where to open
the handler URL (deprecated)
Field
Labels
The <label> tag
defines textual labels for form fields. It has the following format:
<form name="htmlform" method="post"
action="html_form_send.php">
<table width="400px">
</tr>
<tr>
<td
valign="top">
<label
for="first_name">First Name *</label>
</td>
<td
valign="top">
<input type="text" name="first_name"
maxlength="50" size="30">
</td>
</tr>
<tr>
<td
valign="top"">
<label
for="last_name">Last Name *</label>
</td>
<td
valign="top">
<input type="text"
name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td
valign="top">
<label
for="email">Email Address *</label>
</td>
<td
valign="top">
<input type="text" name="email"
maxlength="80" size="30">
</td>
</tr>
<tr>
<td
valign="top">
<label
for="telephone">Telephone Number</label>
</td>
<td
valign="top">
<input type="text"
name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td
valign="top">
<label
for="comments">Comments *</label>
</td>
<td
valign="top">
<textarea name="comments"
maxlength="1000" cols="25"
rows="6"></textarea>
</td>
</tr>
<tr>
<!--colspan it make merge between cells-->
<td
colspan="2" style="text-align:center">
<input
type="submit" value="Submit">
<a
href="http://www.freecontactform.com/html_form.php">HTML
Form</a>
</td>
</tr>
</table>
</form>
------send email by php---
----definations
-
Isset Determine if a variable is set and is not
NULL
.
-
<?php
if(isset($_POST['email']))
{
// CHANGE THE TWO LINES BELOW
$email_to =
"ymslvr@hotmail.com";
$email_subject = "website html form
submissions";
function died($error) {
// your error code can go here
echo "We are very sorry, but there
were error(s) found with the form you submitted.";
echo "These errors appear
below.<br /><br />";
echo
$error."<br/><br/>";
echo "Please go back and fix these
errors.<br/><br/>";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, problem fill the
form please and submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; //
required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not
required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp =
'/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you
entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you
entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you
entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered
do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad =
array("content-type","bcc:","to:","cc:","href");
return
str_replace($bad,"",$string);
}
$email_message .= "First Name:
".clean_string($first_name)."\n";
$email_message .= "Last Name:
".clean_string($last_name)."\n";
$email_message .= "Email:
".clean_string($email_from)."\n";
$email_message .= "Telephone:
".clean_string($telephone)."\n";
$email_message .= "Comments:
".clean_string($comments)."\n";
// create email headers
$headers =
'From: '.$email_from."\r\n".
'Reply-To:
'.$email_from."\r\n" .
'X-Mailer:
PHP/' . phpversion();
@mail($email_to,
$email_subject, $email_message, $headers);
?>
<!-- place your own success html below
-->
Thank you
for contacting us. We will be in touch with you very soon.
<?php
}
die();
?>
Sending Email
Many Web applications have a need to send email messages. For
example, a contact form script typically processes a form submitted by a
visitor and emails the form information to the Webmaster. Other common
scenarios include “ tell a friend ” functions, as well as member registration and
“ forgotten password ” functions that email information to members.
PHP includes built - in support for creating and sending email
messages, which makes it very easy to send email from within your PHP scripts. To
send an email message in PHP, you use the mail() function. On Unix servers such as Linux and Mac OS
X, PHP uses the operating system ’ s built - in mail transfer agent (MTA) to
send the email. (Common MTAs include sendmail , postfix , and exim .) On non - Unix servers such as Windows, PHP
talks
directly to an SMTP mail server (either on the server or on
another machine).
At a minimum, mail() requires three arguments:
A string containing the recipient’ s email address (or a comma -
separated list of email addresses if sending to multiple recipients)The email
subject line, as a string
The message body, as a string mail() returns true if the mail was accepted for delivery by the mail
server, or false if there was a problem.
(Note that an email message might still eventually bounce, even if the mail
server accepted it for delivery.)
For example, the following code sends a short email entitled “
Hello ”, with a message body of “ Hi Jim,
how are you? ”, to jim@example.com:
mail( “jim@example.com”, “Hello”, “Hi Jim,
how are you?” );
You can also include the recipient ’ s real name in the
recipient string, provided you follow it with the recipient ’ s email address
in angle brackets. For example:
mail( “Jim Smith
< jim@example.com > ”, “Hello”, “Hi Jim,
how are you?” );
To send a multi - line message, pass in a string that contains
newline characters. Here ’ s an example:
$message = “Hi Jim,
How are you?
“;
mail( “Jim Smith
< jim@example.com > ”, “Hello”,
$message );
Lines of text in an email message body should not exceed 70
characters in length. To ensure that your
lines are of the correct length you can use PHP ’ s wordwrap()
function:
$message = wordwrap(
$message, 70 );
The mail function
The mail()
function is the primary
function used to send mail with PHP. This function, which
returns a Boolean, attempts to send one message using the data
within the parentheses. The simplest
use of this function (keeping in mind that this is a dummy address
and should not be used for testing
purposes) is:
<?php
mail(‘receiver@example.com’, ‘A Sample Subject Line’,
“Body of e‑mail\r\nwith lines separated by the newline
character.”);
?>
This is the default and minimum format: address of recipient,
subject line, and body. In this case,
PHP will automatically add a From: me@sendhost line to
each message header.
You can also, as always, use variables instead of hardcoded
values:
<?php
$address = ‘santa@example.com’;
$subject = ‘All I want for Christmas’;
$body = “Is my two front
teeth.\r\nSincerely, Joey”;
$mailsend = mail($address, $subject, $body);
echo $mailsend;
?>
Multiple recipients all go into the address field, with commas
separating them (this feature is not
supported by all MTAs; if you want to be sure, use cc: instead):
<?php
$address1 = ‘receiver@receipthost’;
$address2 = ‘jane@example.com’;
$address3 = ‘john@example.org’;
$all_addresses = “$address1,
$address2, $address3”;
$subject = ‘A Sample Subject Line’;
$body = “Body of e‑mail\r\nwith
lines separated by the
newline character.”;
$mailsend = mail($addresses, $subject, $body);
echo $mailsend;
?>
Remember to ensure
that the multiple addresses are one string, as in the preceding code lines. You
do not want to do this:
<?php
$address1
= ‘receiver@receipthost’;
$address2
= ‘jane@example.com’;
$address3
= ‘john@example.org’;
$subject
= ‘A Sample Subject Line’;
$body
= “Body of e‑mail\r\nwith lines separated by the
newline
character.”;
//
This is wrong, don’t do it!
$mailsend
= mail($address1, $address2, $address3, $subject,
$body);
echo
$mailsend;
?>
Most people would
like more control over the addresses, appearance, and format of their e‑mails.
You can do that by
putting an additional header after the three default headers.
<?php
$address
= ‘receiver@receipthost’;
$subject
= ‘A Sample Subject Line’;
$body
= “Body of e‑mail\r\nwith lines separated by the
newline
character.”;
$extra_header_str
= “From: me@sendhost\n\nbcc:
phb@sendhost\r\nContent-type:
text/plain\r\nX-mailer: PHP/“
.
phpversion();
$mailsend
= mail($address, $subject, $body, $extra_header_str);
echo
$mailsend;
?>
This “additional
header” field is somewhat odd because it crams in several types of information
that
would normally be
given their own fields. Ours is not to wonder why; ours is but to explain the
kinds of things you
might want to put in this field.
■■Your name
■■The To: address
■■Your e‑mail address
■■A reply-to or
bounce-to address
■■X-mailer and
version number
■■MIME version
■■Content-type
■■Charset (which uses
a = to
assign a value and not a : like the other headers)
■■ transfer-encoding
■■Carbon-Copy (cc:) and blind carboncopy (bcc:) recipients
The mail() function returns 1 (TRUE) when PHP
believes it has successfully sent mail.
This has no relationship to any
mail actually being sent or received. There are still an
endless number of things that
can go wrong: bad e‑mail address, SMTP
daemon incorrectly designated
or configured, local Internet
conditions, and so on. Think of 1 as a message meaning no more
than
“PHP has applied the function
to the inputs successfully.”
Sending Mail from a Form
Sending mail from a form is quite likely the single
most popular application of PHP’s mail() function.
It’s a far more functional alternative than HTML’s mailto link tag, which of
course results in
e‑mail being sent
from the client machine’s mail program.
Listing 37-1 is a simple example form of the type
that often sends e‑mail.
Listing 37-1
e‑mail form (titlehelp.html)
<html>
<head>
<title>titlehelp.html</title>
</head>
<body>
<center>
<table width=”550”>
<tr bgcolor= #FF9933><td align=”center”><BR>
<H3>The Thriller <BR>
“What
was the name of that thriller?”<BR>
Form</H3></td></tr>
<tr><td>
Did you once read an unforgettable thriller, but now you can’t
remember the name? Fill out as many of the fields below as you
can, press the button to submit, and we’ll search our sources
and e‑mail you back.
</td></tr></table>
</center>
<FORM METHOD=post ACTION=”titlehelp.php”>
<P>First name: <input type=”text”
size=30 name=”FirstName”>
<P>Last name: <input type=”text”
size=30 name=”LastName”>
<P>Your Email Address: <input type=”text” size=30 name=”Email”>
<P>In approximately what year did the action of the book
occur?
<input type=”text” size=4 name=”Year”>
<P>Can you remember any settings
from the book?
<input type=”text” size=30 name=”Setting”>
<P>The gender of the protagonist(s)
was: <br>
<ul>
<input TYPE=”radio” NAME=”Gender” VALUE=1>Female<br>
<input TYPE=”radio” NAME=”Gender” VALUE=2>Male<br>
<input TYPE=”radio” NAME=”Gender” VALUE=3>One of each<br>
<input TYPE=”radio” NAME=”Gender” VALUE=4>Two males<br>
<input TYPE=”radio” NAME=”Gender” VALUE=5>Two females<br>
</ul>
<P>When the book first came out,
it was: <br>
<ul>
<input TYPE=”radio” NAME=”Status” VALUE=1>A bestseller<br>
<input TYPE=”radio” NAME=”Status” VALUE=2>A critic’s darling<br>
<input TYPE=”radio” NAME=”Status” VALUE=3>Neither<br>
<input TYPE=”radio” NAME=”Status” VALUE=4>I don’t know<br>
</ul>
<P>Please tell us anything else
you can remember about this
title (plot, characters, settings,
cover, movie versions,
etc.):
<br><textarea NAME=”Other” ROWS=6 COLS=50></textarea>
<P><input type=”submit” name=”Submit”>
</body>
</html>
No comments:
Post a Comment