Tuesday, August 28, 2012

Display current date in php


echo date('d-m-Y');

Split a data by comma

$Add_array = split("[,]",$Address);
   for ($i =0; $i < count($Add_array); $i++){  
   echo($Add_array[$i]);
     }

Find an element in array - php code

<?php
$os 
= array("Mac""NT""Irix""Linux");
if (
in_array("Irix"$os)) {
    echo 
"Got Irix";
}
if (
in_array("mac"$os)) {
    echo 
"Got mac";
}
?>
The second condition fails because in_array() is case-sensitive, so the program above will display:
Got Irix
 

Numbers and strings

Numbers and strings

Operators

We have already seen how to use functions, such as sqrt, to manipulate values in PHP. For the most common operations, though, PHP provides symbolic shortcuts for the operations, such as + for adding two values together, or * for multiplying two values. Such symbols are called operators.
PHP includes about 30 operators, though we'll only cover the 10 or so that appear frequently in programs. The most recognizable would be + for addition, - for subtraction or negation, * for multiplication, and / for division. We can use these to enhance our range selection page so that it displays the midpoint in the range:
<p>From the range <?php echo $form_begin; ?>
to <?php echo $form_end; ?> I have selected the random number
<?php echo rand($form_begin, $form_end); ?>.  The midpoint is <?php
    $average = ($form_begin + $form_end) / 2;
    echo $average;
?>.</p>
PHP observes the traditional order of operations: Negation comes first, followed by division and multiplication in left-to-right order, followed by addition and subtraction in left-to-right order. You can use parentheses when you want to indicate a different order of operations; in the above example, we had to use the parentheses; otherwise, PHP would add form_begin to half of $form_end, which wouldn't be the average of the two values.
There is another operator worth mentioning: The remainder operator, represented by the percent sign. When placed between two numbers, the resulting value is whatever remainder results when the first number is divided by the second number; for example, 28 % 9 would yield 1, since 9 goes into 28 three times with a remainder of 1. The remainder operator lies at the same precedence level as multiplication and division in PHP.
Note that one operator that is not on the list: There is no operator for exponentiation. People often expect the caret ('^') to do this; PHP allows you to use a caret to operator on two numbers, but what it does is fairly obscure and rarely very useful. (You don't need to worry about it, but what it does is a bitwise exclusive or, where it computes the number whose binary representation is 1 in each place where the two numbers' binary representations are different.) When you want to raise one number to another power, you can instead use PHP's pow function: The tenth power of 1.5, for example, can be found with pow(1.5, 10).

5.2. Types

As PHP processes a program, it works with a variety of categories of information, each called a type. Thus far, we have glossed over the distinction, but it is an important one.
In fact, PHP works with two different types of numbers: integers and floating-point numbers. Integers are numbers represented in a format that allow no fractional parts (and allow numbers such as 0 or 2 or −158), whereas floating-point numbers are represented in a format that allows fraction parts (such as 3.14159 and 1.5). Whenever a number is written with a decimal point, it is a floating-point number; thus, if you write 1.0, you're talking about the floating-point value 1, which doesn't behave exactly the same as the integer value 1.
For those who have programmed in other languages based on C: PHP's division operator always produces a floating-point result. (Most other C-derived languages ape C's rules for dividing two integers, where the remainder is ignored so the result is still an integer. In PHP, an expression such as 1 / 2 actually yields 0.5 as a beginner would expect.)
Most of the time you don't need to worry about the distinction between floating-point numbers and integers; PHP freely converts integers to floating-point numbers when necessary. One situation where it can appear is with rounding problems, such as with the following statement.
echo 10000000000000000 - 9999999999999999;
This statement outputs 0 on some computers, because those computers can't store integers so big, and so PHP uses floats instead... and it happens that they are both approximated with the same float.
If there's some reason you want to convert between the two, you can use PHP's intval and floatval functions.

5.3. Strings

PHP includes many other types for values that aren't numbers. One of the most important such is the string, which is a value representing a sequence of several characters, such as a word, a sentence, or a nonsensical stream of punctuation.
To refer to a particular string value, you can use a set of quotation marks enclosing the characters you want to include in the string. The following statement makes the variable $sentence refer to a famed novel's opening sentence.
$name = "It was the best of times; it was the worst of times.";
When you enclose a string in quotation marks, the contents of the quotation marks are not interpreted by PHP: It simply places the raw characters into the string. Suppose I type:
$expr = "rand(1, 100)";
PHP does not use the rand function here: It simply creates a string consisting of 12 characters, starting with the letter r and ending with the close-parenthesis character. If we omitted the quotation marks, of course PHP would call the rand function to retrieve a random number between 1 and 100.
One exception (and the only exception) to this rule is variable names: When you include a variable name in a string, PHP will substitute the variable's value in place of the name. Suppose I write this:
echo "The range is $form_begin to $form_end. ";
echo "The midpoint is ($form_begin + $form_end) / 2. ";
echo "The chosen number is rand($form_begin, $form_end). ";
The PHP interpreter would substitute the values of the variables whenever they occur; but it would not attempt to apply the operators or call the functions. What we would see on the Web browser, then, is the following.
The range is 10 to 20. The midpoint is (10 + 20) / 2. The chosen number is rand(10, 20).
Of course, that's probably not what we want. There are several ways of getting around this. One is to first assign a variable to refer to the desired value, and then to use that variable inside the string. But another approach worth knowing about is the catenation operator '.', which you can use to join two values into a string. The following is how we could modify our example.
echo "The range is $form_begin to $form_end. ";
echo "The midpoint is " . (($form_begin + $form_end) / 2) . ". ";
echo "The chosen number is " . rand($form_begin, $form_end) . ". ";
As an example, the final line says to catenate the string The chosen number is with the value generated by rand, which itself should be catenated with the string .. Note the space that has carefully been added inside the first string after is: Without this, the output would omit the space, as in The chosen number is17..
The catenation operator has the same priority level as addition and subtraction. As a result, the following would be incorrect.
echo "The sum is " . $form_begin + $form_end;   // WRONG!
PHP would first catenate The sum is with $form_begin, resulting in a string such as The sum is 20. Then it would attempt to interpret this as a number so that it could add $form_end to it. It would not work as we would expect. For this reason, I recommend developing the habit of using parentheses whenever you try to combine other operators with catenation, even when it is not necessary. The above midpoint example illustrates this: Even though there the parentheses were unnecessary since division occurs at a higher level than catenation, I went ahead and used parentheses anyway.
We've seen that variable names in double quotation marks will be replaced with the variable values. But that brings up a question: What if you don't want this substitution to occur? There are two answers that PHP provides. First, you can prefix the relevant dollar sign with a backslash, as in "\$choice is $choice"; in this example, the first dollar sign won't be treated as part of a variable name, but the second will, so the string will translate to something like $choice is 17. You can do the same backslash trick when you want to a quotation mark to appear inside the string, or when you want a backslash as part of the string.
Backslashes can also be used to insert other characters. Most significantly, '\n' inserts a newline character into a string. Since line breaks aren't automatically inserted between echo statement, a PHP script that echoes a large amount of information would normally create one large line, which can be quite difficult to read for somebody who tries to read the generated HTML source. (Of course, the browser ignores line breaks anyway.) For this reason, I'd be inclined to instead write our earlier example with three echo statements as the following instead.
echo "The range is $form_begin to $form_end.\n";
echo "The midpoint is " . (($form_begin + $form_end) / 2) . ".\n";
echo "The chosen number is " . rand($form_begin, $form_end) . ".\n";
Note the '\n' that follows each period. This leads the generated HTML to include three separate lines rather than one long line. Again, the browser will display the HTML the same when we have spaces instead of newlines, but a user who chooses to read the HTML source will have an easier time with the newlines inserted. (You can also use '\t' to specify a tab character, but this is not as useful.)
Sometimes the number of backslashes can get a bit cumbersome, so PHP provides another way, too: You can enclose the string in single quotation marks. Variable substitution never occurs for a string enclosed in single quotation marks. (I won't use this single-quotation technique, but many PHP programmers use single quotes as a matter of habit.)

Conditional execution

if statements

Suppose we wanted our random number generation program to work even when the user enters the two ends of the range in the opposite order. What we would want is a way to test whether they are inverted, and then to silently swap them back into the proper order before proceeding. We can do this using what is called an if statement. The following solution illustrates how it would work.
<?php import_request_variables("pg""form_"); ?>
<html>
<head>
<title>Generate Random Number</title>
</head>

<body>
<p>From the range <?php
    if($form_begin > $form_end) {
        $old_begin = $form_begin;
        $form_begin = $form_end;
        $form_end = $old_begin;
    }
    echo $form_begin;
?> to <?php
    echo $form_end;
?> I have selected the random number <?php
    echo rand($form_begin, $form_end);
?>.</p>
</body>
</html>
An if statement is always followed by a set of parentheses enclosing some yes/no expression. Following that is a set of braces enclosing a list of statements. PHP will execute these statements only when the answer to the question in the parentheses is yes. After completing these statements, it will continue after the braces. But if the answer is no, PHP will skip over the statements inside the braces (without executing them) and immediately go on to the first statement following the braces.
One thing you should be careful of: An if statement does not involve any semicolons. A typical beginner's mistake is to write something like if($a > $b); {, with a semicolon inserted between the close parenthesis and the opening brace. Unfortunately, PHP allows this but interprets it very differently from what you will intend: If you insert a semicolon there, PHP will think you mean that the body of the if statement is the statement consisting of only a semicolon — a statement with nothing in it. The end result is that if $a exceeds $b, the computer will perform this empty statement (doing nothing) and then proceed into the braces; but if $a does not exceed $b, the computer will skip over the empty statement and proceed into the braces anyway.
In the above example, the three assignment statements in the braces end up swapping the values associated with $form_begin and $form_end: We first assigning $old_begin to refer to the original value of $form_begin; then we assign $form_begin to the original value of $form_end; and finally we assign $form_end to the value of $old_begin, which is the original value of $form_begin.

6.2. Booleans and conditions

The portion in parentheses is supposed to be a yes/no value. PHP has a special type for such values called the boolean. (This is the fourth type we've seen, on top of integers, floating-point values, and strings.) There are only two different boolean values, written TRUE and FALSE.
In fact, the expression in parentheses doesn't need to be a boolean. If it isn't, then PHP will first convert it to TRUE or FALSE to see whether to execute what in the braces. The rule it uses is that every integer, floating-point value, and string value is equivalent to TRUE except for the following, which are FALSE:
  • the integer 0
  • the floating-point value 0.0
  • the string with nothing in it ("")
  • the string containing just the 0 digit ("0")
Generally speaking, I recommend avoiding any dependence on these rules; instead, you would use an assignment operator to compare values.
PHP provides a number of operators for comparing values:
<less than
>greater than
<=less than or equal (i.e., at most)
>=greater than or equal (i.e., at least)
==equal
!=not equal
The usage of the exclamation point '!' for the word not is a bit odd, but it's not hard to grow accustomed to it.
Note, though, that the way to check whether two things are equal is to use two equals signs. PHP does this because a single equals sign is already being used in PHP to represent assigning a value to a number.
In fact, the single equals sign is actually an operator, too, whose value is whatever is assigned. This can lead to weird behavior. Suppose you write the following.
if($form_begin = $form_end) {                        // WRONG!
    echo "Error: The range doesn't contain any numbers.";
}
In the parentheses, we use a single equals sign, and so PHP takes this to mean that we actually wish to change $form_begin so that its value is the same as $form_end's value. Moreover, the value of the expression in the parentheses is this assigned value, which PHP will interprets as TRUE unless $form_end happened to be the empty string or the string 0. So in fact the program will probably execute what is in the braces, reporting the error. And then of course it will go on and do whatever follows the braces… but now $form_begin and $form_end will represent the same value.
Needless to say, this is a fairly big error in our program. Beginning PHP programmers are almost guaranteed to encounter it, and it can be hard to see if you don't know about this distinction: A single equals means to change a variable; a double equals means to compare two values to see whether they are equal.
With experience, you can avoid the problem by following one simple rule: Inside parentheses on an if, you should never use a single equals sign. And in assignment statements, ou should always use a single equals sign.

6.3. else and elseif clauses

Sometimes you want one thing to happen in one case but a very different thing to happen in other cases. For these, PHP provides an option of including an else clause following the body of an if.
if($form_begin != $form_end) {
    $choice = rand($form_begin, $form_end);
    echo "I have selected $choice from the range.";
else {
    echo "The range includes only one choice: $form_begin.";
}
It also sometimes happens that there are several cases. For these, you can include an elseif clause, optionally followed by an else clause. An elseif clause contains an additional condition in parentheses, followed by the set of statements to execute in that case if the condition turns out to be true.
if($form_begin < $form_end) {
    $choice = rand($form_begin, $form_end);
    echo "I have selected $choice from the range.";
elseif($form_begin > $form_end) {
    $choice = rand($form_end, $form_begin);
    echo "I have selected $choice from the inverted range.";
else {
    echo "The range includes only one choice: $form_begin.";
}
You can have have any number of elseif clauses in the same if statement; but the else clause, if there is one, must come last among them.
In executing an if statement with elseif clauses, PHP will consider each clause's condition in sequence, until it finds one that is true; then it will skip over all other clauses. Looked at another way: The computer will check an elseif clause only when the initial if condition and any preceding elseif conditions all turn out to fail. The body of the else will be executed only when the if and all elseif conditions fail.
The following illustrates this. Note that if $grade were 85, it would display only that a B was received (even though later elseif clauses also seemingly apply), since PHP doesn't consider later elseif clauses in the same statement once it finds one that applies.
if($grade >= 90) {
    echo "You aced the course.";
elseif($grade >= 80) {
    echo "You received a B.";
elseif($grade >= 70) {
    echo "You received a C.";
else {
    echo "You failed.";
}

6.4. A note on indentation

You've probably noticed that the above examples are very systematic about how they are indented. In fact, PHP doesn't care about indentation, and you could just as easily place the entire program on the same line.
if($grade>=90){echo "You aced the course.";}elseif($grade>=80){echo
"You received a B.";}elseif($grade>=70){echo"You received a C.";}else
{echo "You failed.";}
However, code written in this way is very difficult to repair when there is a problem with it, and for those who haven't just typed it, it is fairly difficult to read. For these two reasons, you should follow a similar convention, where inside each set of braces, you indent each line`a bit further than where the if statement starts, so that it's easy to see where the body is.
You'll also notice that I'm very systematic about how I place the braces: An opening brace is usually put off at the end of a line, and the corresponding closing brace is placed at the start of the line where it appears, indented just as far as the initial if. This convention isn't quite as strong as the convention about indentation, but arranging the braces in some sort of system is very well-established among programmers — and the particular technique that I'm illustrating is the most popular system that experienced programmers use. You should follow some well-established system of indenting code and dealing with braces.

More about forms

More about forms

Transmission methods

HTTP, the transmission protocol used for the Web, actually defines two methods for sending form information to a Web server, called POST and GET. In Web forms, we've consistently used the POST method by including method="post" in the form tag. This is the recommended way for transmitting form data.
The distinction between the two is this: With the GET transmission method, the information from the form is encoded into the URL that is sent to the Web server. This technique has the shortcoming that the URL will become unmanageably long for moderately long forms. The HTTP designers thus quickly found that a better design would be to have Web browsers send the form data after sending the URL to the Web server.
The GET method, though, is still sometimes useful, particularly when you want to be able to access a PHP script through the use of a Web link rather than through completing a form. It's easiest to describe this through an example based on our forum site: When we list the name of each post's user, we might want to allow the user to click on the name to view the full information about that person. To do this, we'd want to generate the following HTML.
<p>By: <a href="user.php?userid=sherlock">Sherlock Holmes</a></p>
The GET method uses a question mark to separate the name of the script from the form data; following the question mark are field names and their associated values, separated by an equals sign. If there are multiple fields, each field/value pair is separated by an ampersand ('&').
Thus, when the user clicks on the link, the browser will send the URL to the Web server, which will invoke the user.php script as if the user had filled out a form typing sherlock into the userid field. The user.php script that we saw earlier will work as it has already been written.
(In fact, the values sent via the GET and POST methods are accessible separately by PHP. But in invoking import_request_variables, we've consistently passed "pg" as the first parameter. The p says to import the POST values, and the g says to import the GET values. So for our purposes, both sets of values are imported together.)

10.2. Input elements

We've already seen the input element, and in particular we've used the text and submit values for its type attribute, in order to create text fields and buttons. But we often want to create other types of input elements. In this section we'll look at some of the other possible values for type.

10.2.1. Hidden fields

One important value for type is hidden. Given this, a Web browser will not display anything about that input element on the screen. This may sound useless at first, since the user won't be able to interact with it, but it is actually one of the more useful options. It is used in situations where the HTML composer wants to send information into a script without showing it to the user.
The hidden type is really only useful when it is associated with a value attribute in addition to the name attribute. Whatever is in this value attribute will be sent to the PHP script without giving the user a chance to see or modify it.
Of course, the hidden type shouldn't be used when you have information that the user shouldn't ever see. While the element won't be rendered inside an HTML browser, the user who chooses to read the raw HTML source code will be able to see everything that appears.

10.2.2. Password fields

Another useful type is password. This works exactly like a text field, but it directly the Web browser to not display whatever the user types in the text field. Most Web browsers choose to display asterisks ('*') for each character the user types.
The password field doesn't provide any security beyond preventing getting the information by somebody looking over the user's shoulder. Of course, somebody looking over the user's keyboard might be able to figure out the information by watching the user's fingers.

10.2.3. Checkboxes

A checkbox is a box that can be checked or unchecked to represent a yes/no value. The checkbox's value is sent to the PHP script only when it is checked. If the checkbox is not checked, then the browser won't send any information about it, and so the import_request_variables function won't create a variable.
This brings up a question: How in a PHP script can we identify whether a variable exists or not? The answer lies in the isset function, which returns a Boolean value. Thus, you can write if(isset($form_box)) to test whether the checkbox named box was checked.
An input element representing a checkbox should always contain a value attribute so that the Web browser will know what value to send when the checkbox is checked. This value attribute does not affect whether the checkbox is checked: That is done by setting the checked attribute to checked; checkboxes ar unchecked when no checked attribute is mentioned.
Another issue that comes with checkboxes is that people normally expect that you can click anywhere on the label associated with the checkbox to toggle its value. However, the HTML we have seen thus far provides no way of indicating what the label is, so the Web browser cannot provide this user interface.
HTML provides a way of indicating the label through its label element. To use it, you enclose the input element along with its associated label within the same tag. (For cases where this is impossible because the label appears separately from the input element, you can use the for attribute whose value matches the name attribute of the matching input element.)
<label><input type="checkbox" name="box" value="on" checked="checked" />
  Do you understand checkboxes?</label>
Not all Web browsers honor the label tag, but it doesn't hurt to include it for those Web browsers that do honor it.
Incidentally, you can use the label tag for other elements, such as those with a type of text or password, but the case for doing this is less compelling than for checkboxes or radio buttons.
Not all Web browsers honor the label tag, but it doesn't hurt to include it for those Web browsers that do honor it.

10.2.4. Radio buttons

Radio buttons present several options to the user, from which the user may select one. Most interfaces display a circle next to each option, filling in the circle that is currently selected.
Creating a set of radio buttons in HTML is a matter of creating several input elements all with the type attribute of radio and the identical name attribute.
<label><input type="radio" name="station" value="fm899" />
  FM 89.9 KQED</label>
<br /><label><input type="radio" name="station" value="fm917" checked="checked" />
  FM 91.7 KUAR</label>

10.3. Other form elements

10.3.1. Text areas

HTML specifies some form elements that are created through tags other than the input tag. One in the text area, typically a large text field with many rows: The way to create one of these is through a textarea element.
The textarea element has three official attributes that are typically used. The name attribute works just as for the input element: It identifies the name associated with the text area's contents when the form is submitted to the Web server. There are also the rows and the cols attributes, which provide guidance to the Web browser about how tall and how wide to make the text area; but the browser should provide scrollbars when the text becomes taller or wider than the area that is displayed on the screen.
Unlike the input element, which should not contain any text within it, the textarea element can. Whatever appears within the element should appear as the initial value within the textarea (as you would do using the value attribute for an input element corresponding to a text field).
In fact, we should have used the textarea element in the Web form for allowing a user to post information to our forum Web site. The following allows users to use multiple words.
<form method="post" action="post.php">
<p>Name: <input type="text" name="user" />
<br />Password: <input type="password" name="passwd" />
<br />Subject: <input type="text" name="subj" />
<br /><textarea name="body" rows="8" cols="80">Type your post here.</textarea>
<br /><input type="submit" value="Post" />
</p></form>
Name:
Password:
Subject:

10.3.2. Lists

A final thing you might want is to present a list of options from which the user might choose. This can be done using the select element, within which is nested an option elements for each option to appear. The select element has a name attribute giving the name for the browser to use when identifying the selection when the form is submitted. The option element has a value attribute for specifying what value to send when that option is selected; and it has a selected attribute which allows the HTML to specify which option is initially selected.
Language: <select name="language">
<option value="php" selected="selected">PHP</option>
<option value="perl">Perl</option>
<option value="python">Python</option>
</select>
HTML does not specify whether the browser should do this using a drop-down menu or a list, but most use drop-down menus.
Language:
There are two options available for configuring the select element's appearance: The size attribute configures how many rows to use if it is displayed as a list box, and the multiple attribute, when set to multiple, tells the browser to allow the user to select multiple options. Most browsers wil display the select element as a list box when either is indicated. The below select element is defined identically to the above example, except that size="3" has been added into the select tag.
Language:

Input validation

Input validation

The preg_match function

Users submitting information to a Web site don't always behave quite as you would like. Usually, they make an idle mistake, such as misformatting what they send (perhaps neglecting to include the area code in a telephone number). But there are also inevitably some who try to abuse popular Web sites. For both sets of users, it is important for a PHP script to verify that what they send is correct. This process is called input validation.
One of the most useful tools for input validation is PHP's preg_match function. It isn't an easy function to learn, but it can be a powerful way to check whether something the user types fits into the format your Web site requires. Below is an example PHP fragment for confirming that a ZIP code submitted by the user is indeed a 5-digit number. (This would not work for people from countries other than the U.S.)
if(preg_match("/^[0-9]{5}$/", $form_zipcode)) {
    echo "The ZIP code must be a 5-digit number.";
}
The preg_match function takes two parameters. The first, called the pattern, describes the potential inputs. It is a string starting and ending with a slash ('/'), surrounding a regular expression. Right now, the particular regular expression appearing above (^[0-9]{5}$) will look nonsensical, but we'll study regular expressions later in this chapter. The second parameter is the string against which preg_match should compare the pattern. The function returns true or false depending on whether they match.

12.2. Regular expressions

A regular expression is a common way of describing a large set of possible strings. It can be seen as a miniature language, although it is expressed in a condensed form.

12.2.1. Matching subsequences

The simplest form of regular expression is as a sequence of letters or digits; in this case, preg_match will return 1 if that sequence appears anywhere in the string to be matched. For example, the pattern amb will match amble or Cambridge, but not Amber (since it is case-sensitive) or aplomb (since the letters amb must be adjacent).
But there are a number of special symbols one can use. One is the set of brackets '[' and ']', which indicates a choice among several characters. If we want to allow the a to be capitalized in the above example, then we could use [Aa]mb as our pattern. You can also indicate a range of characters inside the brackets using a hyphen; thus a[a-z]b will match any string containing an a followed by a lower-case letter followed by a b, as in arbor and rhubarb.
It is also sometimes useful to allow any character to appear in a particular spot in a regular expression. A period '.' will match any single character.

12.2.2. Matching the full string

Most often with user input, you'll want to match the entire string, not search for a particular substring. To say that the pattern must match starting at the string's beginning, you start the pattern with a caret ('^'). And to say that the pattern must match ending at the string's end, you terminate the pattern with a dollar sign ('$'). Most often, you would use both of these. For example, to confirm that a state code submitted by the user contains two capital letters, you could use the pattern ^[A-Z][A-Z]$.

12.2.3. Repetitions

You can use a set of braces ('{' and '}') to specify that something appear a particular number of times within a regular expression. You would place the braces directly after the pattern that should be repeated that number of times, and the number would appear within the braces. Another way to write our two-letter state code pattern is as ^[A-Z]{2}$. We also saw earlier that we can match 5-digit ZIP codes using the pattern ^[0-9]{5}$.
A set of braces can also contain two numbers inside, specifying that the number of repetitions of the preceding pattern must be between those two numbers. The set of numbers between 1000 and 99999, for example, may be described with ^[1-9][0-9]{2,4}$.
You can use a set of parentheses to specify an order of operations. This can be useful when you want a pattern of potentially several characters to repeat multiple times. We can extend our ZIP code pattern to allow either a 5-digit or 9-digit ZIP code using ^[0-9]{5}(-[0-9]{4}){0,1}$. Here, we've used parentheses to enclose the final dash and four digits, saying that this portion is allowed to occur either 0 or 1 times.
There is a shorthand for saying 0 or 1 times: You can use a question mark ('?') in place of {0,1}. Similarly, you can use an asterisk ('*') to indicate that the preceding pattern can repeat any number of times (including the possibility that it may not appear at all); and you can use a plus sign ('+') to indicate that the preceding pattern must appear at least once. If I wanted to describe the set of strings describing integers, I could use the regular expression ^-?[0-9]+$: It says that the string may begin with a negative sign, but that it must contain at least one digit.

12.2.4. Summary

Finally, you'll occasionally want a regular expression to mention one of the characters that have a special meaning within a regular expression. You can remove its special meaning to preg_match by preceding it with a backslash. Unfortunately, backslashes within strings also have a special meaning to PHP, so you should really precede it by two backslashes, so that preg_match will receive one of them. For instance, a regular expression one could use for describing e-mail addresses is ^[a-z]+@[a-z]+(\.[a-z]+)+$. This says that there must be one or more letters before the '@' sign, followed by one or more letters, followed by one or more instances of a period followed by one or more letters. The period must be preceded by a backslash, because otherwise preg_match will allow any character in place of the period. (This regular expression is deficient because some institutions use periods in e-mail addresses, and some domain names contain hyphens.)
The above description isn't a complete description of the options available with regular expressions, but it is adequate for most purposes. Below is a summary of all of the special characters we have seen.
()grouping
[]range of characters
.any character
{}copies of the preceding pattern
?zero or one of the preceding pattern
*any number of the preceding pattern (including zero)
+at least one of the preceding pattern
^start of string
$end of string
\treat next character literally instead of as a special symbol

Arrays Basics

Arrays

Basics

An array in PHP is a powerful structure for a script to remember a conglomeration of data. You should think of an as a collection of associations between keys and their corresponding values. For example: I might want to have an array that associates people's names with their addresses. We might choose the address to be the key, and the name to be the value associated with each key. Thus, associated with the key 221B I would find the value Sherlock Holmes. (If you happen to have seen the array notion in a different programming language, forget what you learned: PHP's notion of array is rather unusual.)
An array is referenced using a single variable, such as $residents. To retrieve the value associated with a key, place the value into brackets following the variable name. Thus, given echo $residents["221B"]; PHP will echo Sherlock Holmes.
We place a value into the array using this same bracket notation, but now on the left sign of an assignment statement. Thus, it would be legal to write $residents["220A"] = "Watson";. If $residents wasn't yet referring to anything, this would create an array. If the key 220A didn't already exist in the array, the key would be inserted with Watson as the associated value. And if there were already a value associated with 220A, that person would be evicted in favor of Watson.
In fact, PHP automatically constructs some built-in variables referring to arrays. The $_POST variable is one major example: When a browser sends a POST request to a PHP script, PHP sets $_POST to be an array whose keys correspond to the names of the input controls, and whose values are the values sent by the browser for each input control. In fact, we've been avoiding $_POST by using the import_request_variables function; this function conveniently creates variables corresponding to each array entry.
In our above example, the keys and values are both strings. But the keys and values can be of any type, and indeed they can mix types. In an example below using the explode function, we'll see an array where it happens that the keys are all integers, and the values are all strings.

13.2. Example

Arrays show up in several of PHP's library functions. One such is explode, which splits a string into several pieces. It takes two parameters: The first is a string describing what separates the pieces into which it is to be divided, and the second is the string that should be divided. The function returns an array, with the keys being the integers 0, 1, 2,…, with the first piece associated with 0, the second piece associated with 1, and so on.
For example, suppose we have a Web form where the user types a telephone number in the form 501-340-1300 and for some reason we want to extract the area code and exchange from the telephone number. The following PHP code accomplishes this.
$phone_parts = explode("-", $form_phone);
$area_code = $phone_parts[0];
$exchange = $phone_parts[1];

13.3. Array presence

Sometimes we'll want to determine whether an array has any value associated with a particular key. We can do this using isset. For example, if I have a PHP script that is supposed to be invoked from a form with a field named userid, and I want to verify that the PHP script was indeed sent a value for userid, I can write the following.
if(isset($_POST["userid"])) {
    echo "<html><head><title>Error</title></head><body>\n";
    echo "<h1>Error</h1><p>Sorry, you must enter your user ID.</p>\n";
    echo "</body></html>\n";
    exit;
}
(The above example also uses the PHP function exit, which terminates the execution of the current script. In this case, we wouldn't want it to continue because we have already sent the HTML response reporting the problem with the POST request.)
If for some reason you want to delete a key and its associated value from an array, you can use unset, as in unset($residents["221B"]);.
Both isset and unset can also be applied in contexts that have nothing to do with arrays. For example, if we were still using the import_request_variables function, then we could also have written if(isset($form_userid)) { to see whether the browser has sent us any information from of the form's userid blank.
(Though they look like functions, technically isset and unset are part of the base PHP language rather than part of its function library. This is a technical detail, though. You are free to think of them as functions, if you like.)

Sessions Problem and solution

Sessions

Problem and solution

Classical server-side Web programs suffer from a large limitation: A Web server handles each Web request individually, without the context of other requests coming from the same user. This is a major limitation in situations such as sites that require users to log in and others where the user builds a shopping cart of desired items to buy. Such problems require that a server-side script remember what happened with previous requests, which can become a fairly complicated process as a Web server interleaves servicing requests from a variety of users.
PHP addresses this problem with the notion of a session. Using sessions with PHP in their basic form is quite simple: It is simply a matter of calling the session_start function before sending any HTML code to the client. PHP will create an array called $_SESSION corresponding to this user; anything placed in this array will be associated with the session, and will be recalled into the array when the same user later requests a script that also calls session_start.
This is all deceptively easy to use. As we'll see later in this chapter, PHP does quite a bit behind the scenes to allow sessions to work well.

14.2. Putting it together: A page counter

Before we go further, though, let's look at a simple example involving sessions: We'll look at a PHP script that counts how many times a user has loaded the page in question. Not very useful, yes, but it does illustrate all of the concepts essential to using sessions profitably.
  1 <?php
  2      session_start();
  3  
  4      if(isset($_SESSION["count"])) {
  5          $accesses = $_SESSION["count"] + 1;
  6      } else {
  7          $accesses = 1;
  8      }
  9  
 10      $_SESSION["count"] = $accesses;
 11  
?>
 12 <html>
 13 <head>
 14 <title>Access counter</title>
 15 </head>
 16 
 17 <body>
 18 <h1>Access counter</h1>
 19 
 20 <p>You have accessed this page <?php echo $accesses; ?> times today.</p>
 21 
 22 <p>[<a href="counter.php">Reload</a>]</p>
 23 </body>
 24 </html>
In line 2, we begin the session by invoking the session_start function. Remember, this must occur before any HTML code is sent to the Web browser (for reasons explains later). Even a blank line before the <?php will qualify as sending information to the browser, and it will then be too late to use session_start.
The session_start function creates the $_SESSION array, which contains any values saved into the session by previous accesses to the Web site. In this example, our Web site has just one page, but in general, the values may have been saved by different pages within the same site. However, it may be that no pages in the site have saved any values in the Web site — in which case the $_SESSION variable would be empty.
The purpose of line 4 is to check whether a count has been stored into $_SESSION previously. If it has, then in line 5 we retrieve that value, and we add 1 since the user has now loaded the page one more time. If not, then we simply note that the user has loaded the page just this once.
Line 10 saves the new count back into $_SESSION. Note that we use the same string in the parentheses as we used in lines 4 and 5, so that those lines will be able to retrieve the saved value when the page is loaded again.

14.3. Forum example using sessions

Now let's look at an example applying sessions. In particular, we want to modify our forum site so that the user must first log in to view any posts. We'll also modify the posting process so that the user doesn't need to retype the user ID and password with each new posting.
To enable this, we first must create a Web form for logging into the forum, a file that we name login.html.
<html>
<head><title>Log in</title></head>
<body>
<h1>Log in to forum</h1>

<form method="post" action="view.php">
<p>User ID: <input type="text" name="userid" /></p>
<p>Password: <input type="password" name="passwd" /></p>
<p><input type="submit" value="Log In" /></p>
</form>
</body>
</html>
Then we will modify the view.php script from Section 8.2 to identify when the user is trying to log in. The important part is the portion at the beginning: We first call session_start. We use the userid key in the $_SESSION array to store the user ID logged into the session; if this isn't set, then the user hasn't logged in.
<?php
    session_start();

    $db = mysql_connect("localhost:/export/mysql/mysql.sock");
    mysql_select_db("forum", $db);

    // To tell whether the user is coming here from the login form, we
    // check whether the $_POST array has passwd and userid keys. If so,
    // then we will attempt to verify that the user ID/password
    // combination is correct through a database query.
    if(isset($_POST["passwd"]) && isset($_POST["userid"])) {
        $userid = $_POST["userid"];
        $passwd = $_POST["passwd"];

        $sql = "SELECT userid"
            . " FROM Users"
            . " WHERE userid = '$userid' AND passwd = '$passwd'";
        $rows = mysql_query($sql, $db);
        if(!$rows) {
            // If the query fails, either because the SQL is incorrect
            // or because the userid/password combination isn't in the
            // database, then we will store an error message in a place
            // that we can access later, and we will unset the session
            // key userid, just in case the user is trying to log in
            // as somebody else.
            $error = "Password lookup error: " . mysql_error();
            unset($_SESSION["userid"]);
        } elseif(mysql_num_rows($rows) == 0) {
            $error = "Password not accepted.";
            unset($_SESSION["userid"]);
        } else {
            // We got a valid login: Remember this for later.
            $_SESSION["userid"] = $userid;
        }
    } elseif(!isset($_SESSION["userid"])) {
        // If the user hasn't logged in previously and isn't coming from the
        // login form, then we want to reject the user's request.
        $error = "You must first log in.";
    }

    // The above sets $error if there is some problem that should
    // prevent listing the posts. In this case, we should show the error
    // message to the user and exit so the posts aren't listed.
    if(isset($error)) {
        echo "<html>\n";
        echo "<head><title>Cannot Access Forum</title></head>\n";
        echo "<body>\n";
        echo "<h1>Cannot Access Forum</h1>\n";
        echo "<p>Error encountered trying access form: $error.</p>\n";
        echo "</body>\n";
        echo "</html>\n";
        exit;
    }
?>
<html>
<head>
<title>Current Posts</title>
</head>

<body>
<h1>Current Posts</h1>

<?php
    $sql = "SELECT subject, body, userid, name"
        . " FROM Posts, Users"
        . " WHERE poster = userid"
        . " ORDER BY postdate";
    $rows = mysql_query($sql, $db);
    if(!$rows) {
        echo "<p>SQL error: " . mysql_error() . "</p>\n";
    } elseif(mysql_num_rows($rows) == 0) {
        echo "<p>There are not yet any posts.</p>\n";
    } else {
        for($row = 0; $row < mysql_num_rows($rows); $row++) {
            $subj = mysql_result($rows, $row, 0);
            $body = mysql_result($rows, $row, 1);
            $id = mysql_result($rows, $row, 2);
            $name = mysql_result($rows, $row, 3);

            echo "<h2>$subj</h2>\n";
            echo "<p>By: <a href=\"user.php?userid=$id\">$name</a></p>\n";
            echo "<p>$body</p>\n";
        }
    }
?>

<h2>Post new message</h2>
<form method="post" action="post.php">
<p>Subject: <input type="text" name="subj" />
<br />Body: <input type="text" name="body" />
<br /><input type="submit" value="Post" />
</p></form>

</body>
</html>
?>
Of course, we'd also want to modify post.php so that it looks up the user ID from the $_SESSION rather than try to read the user ID from the form.
<?php
    session_start();

    if(!isset($_SESSION["userid"])) {
        $message = "You must first log in to post messages.";
    } else if(!isset($_POST["subj"]) || $_POST["subj"] == "") {
        $message = "The post's subject is missing.";
    } else if(!isset($_POST["body"]) || $_POST["body"] == "") {
        $message = "The post's title is missing.";
    } else {
        $userid = $_SESSION["userid"];
        $subj = $_POST["subj"];
        $body = $_POST["body"];
        $db = mysql_connect("localhost:/export/mysql/mysql.sock");
        mysql_select_db("forum", $db);
        $sql = "INSERT INTO Posts (poster, postdate, subject, body)"
            . " VALUES ('$userid', CURRENT_DATE(), '$subj', '$body')";
        $rows = mysql_query($sql, $db);
        if(!$rows) {
            $message = "Insert error: " . mysql_error();
        } else {
            $message = "The post was successfully inserted.";
        }
    }
?>
<html>
<head>
<title>Post requested</title>
</head>

<body>
<h1>Post requested</h1>

<p><?php echo $message; ?></p>

<p>[<a href="view.php">List Posts</a>]</p>
</body>
</html>

Database fundamentals

Database fundamentals

One of the most common applications of PHP is to provide a Web interface for accessing a database. The database may hold information about user postings for a forum, account and order information for a vendor, or raw data for a statistics site.
Because databases are so common, there are a special category of programs written specifically for managing databases, called database management systems (more often referenced by their abbreviation DBMS). Typical users don't often know that they're dealing with DBMSs, so the names of specific products aren't widely known. Some of the more popular commercial DBMS packages are Oracle and Microsoft SQL Server, but there are also two prominent open-source DBMS packages, MySQL and PostgreSQL.
We'll use MySQL here, since it is easily available and used quite frequently for Web pages in conjunction with PHP. In fact, PHP's interfaces for interacting with the different DBMSs are all quite similar, so if you wanted to use another, it wouldn't take much to learn.
Most DBMSs represent a database as a set of tables, each of which has a relatively fixed set of columns, and a more dynamic set of rows. A row represents a single entity, and a column represents an attribute of an entity. The simplest thing is to look at an example: Suppose we are managing a Web forum using a database. One thing we might want would be a table listing all participants in the forum. Each participant would have a distinctive user ID, a password, a real name, an e-mail address, and the year the participant joined the forum; each of these attributes will be a column in our table.
Users table
userid passwd name email year_joined
sherlock pipe Sherlock Holmes 221b@bakerst.uk 1878
marple knitting Miss Marple marple@trenton.uk 1923
nancy magnifier Nancy Drew nancy@trenton.us 1958
Of course, the forum database will contain other tables, too. One table it will certainly have would list all posts made in the forum. The following table describes the columns that we will have in this table.
Columns in the Posts table
posterthe ID of the person posting the message, corresponding to the userid field of Users
postdatethe date and time that the message was posted
subjectthe subject of the message, as entered by the poster
bodythe body of the message, as entered by the poster

7.2. Simple SQL retrieval

We will want to ask the DBMS to retrieve information for us. There is a language designed specifically for this, called SQL (an acronym for Structured Query Language). SQL is so widely popular that it is closely identified with high-quality DBMSs — which is why so many of the popular DBMSs, including MySQL, incorporate the name SQL into their name.
SQL is a language for composing queries for a database. It is not a full-fledged programming language, but it is powerful enough to represent all of the typical operations on a database. PHP scripts send requests to the database using SQL, so we need to learn some of its fundamentals.
For now, we'll look only at the simplest version of the most important SQL command: the SELECT query. A simple SELECT query is composed of three separate clauses: a SELECT clause listing the names of the columns whose values we want to see, a FROM clause saying which table we want to access, and a WHERE clause indicating which rows we want to retrieve from that table.
For example, suppose we wanted to look up Sherlock Holmes' password and e-mail address. The SQL query we would want to send to the DBMS is the following.
SELECT passwd, email
FROM Users
WHERE name = 'Sherlock Holmes'
Note that the WHERE clause is a condition. In this case, we want to compare the name of each row to the string Sherlock Holmes (in SQL, strings are enclosed in single quotes). When we find a row that matches, we want the DBMS to send back the columns named in the SELECT clause.
The WHERE clause can include several conditions joined by AND and/or OR.
SELECT name
FROM Users
WHERE year_joined > 1900 AND year_joined < 1970
If the table held the three people listed above, this SQL query would result in two values: Miss Marple and Nancy Drew.

7.3. PHP database functions

PHP provides access to MySQL databases via a number of functions. We'll find six of them particularly useful. They are listed below in the order they will typically be used.
$db = mysql_connect($dbms_location)
Connects to the DBMS whose address is identified by the parameter, which should be a string. The exact string will depend on where exactly the DBMS is located; an example string is localhost:/export/mysql/mysql.sock. The function returns a value that can later be used to refer to the DBMS connection.
mysql_select_db($db_name, $db)
Selects which database managed by the DBMS that this PHP connection will reference. The DBMS will have a name for each database, and the name should be passed as a string for the first parameter. The second parameter should be a reference to the DBMS connection as returned by mysql_connect.
$result = mysql_query($sql, $db)
Sends a query to the DBMS. The SQL code should be located in the string passed as the first parameter; the second parameter should be a reference to the DBMS connection as returned by mysql_connect. The function mysql_query returns a value that allows access to whatever the results were of the query; if the query failed — as for example would happen if there were an error in the given SQL — this return value would be FALSE.
mysql_error()
If the last executed query failed for some reason, mysql_error returns a string that describes this error. I recommend that you always make sure your PHP code somehow echoes the result of mysql_error when a query fails, so that you have a way to debug your script.
mysql_num_rows($result)
Returns the number of rows found by the SQL query whose results are encapsulated in the parameter. Of course, this could be 0 if there were no rows that resulted from the query.
mysql_result($result, $row, $col)
Returns a string holding the information found in row $row and column $col in the results that are encapsulated by the $result parameter. Both rows and columns are numbered starting from 0: That is, the first row is numbered 0, the second row 1, and so on, and similarly the first column is numbered 0.

7.4. Example database access

Let's look at an example where these functions turn out to be useful. Suppose we want to write a script that allows a user of our Web site to view the information about a particular participant. The Web site user would see a form such as the following.
User ID:
This form can be generated by the following HTML code.
<form method="post" action="user.php">
<p><b>User ID:</b> <input type="text" name="userid" /></p>
<p><input type="submit" value="Search" /></p>
</form>
The file user.php would be the following.
<?php
    import_request_variables("pg""form_");

    $db = mysql_connect("localhost:/export/mysql/mysql.sock");
    mysql_select_db("forum", $db);
    $sql = "SELECT name, email"
        . " FROM Users"
        . " WHERE userid = '$form_userid'";
    $rows = mysql_query($sql, $db);
    if(!$rows) {
        $error = "SQL error: " . mysql_error();
    } elseif(mysql_num_rows($rows) == 0) {
        $error = "No such user name found";
    } else {
        $error = FALSE;
        $user_name = mysql_result($rows, 0, 0);
        $user_email = mysql_result($rows, 0, 1);
    }
?>
<html>
<head>
<title>User information</title>
</head>

<body>
<?php
    if($error) {
        echo "<h1>Error accessing user information</h1>\n";
        echo "<p>$error</p>\n";
    } else {
        echo "<h1>Information about $form_userid</h1>\n";
        echo "<p>User ID: <tt>$form_userid</tt></p>\n";
        echo "<p>Real name: $user_name</p>\n";
        echo "<p>E-mail address: <tt>$user_email</tt></p>\n";
    }
?>
</body>
</html>
Notice in particular the SQL generation within the PHP code. This program first constructs a string containing the SQL code, referenced by a variable $sql. Because this string is fairly long, and because it is easier to read with each clause on a separate line, the PHP splits the generation of this string across three different lines using the catenation operator. (Notice how there are not semicolons at the end of the first two lines: This is what leads PHP to consider all three lines as part of the same statement, as a semicolon marks the end of the current statement.) Whatever name the user typed in the text field is inserted into the SQL string in the appropriate place.
After executing the query via mysql_query, this program first checks whether there is an error, then it verifies that a result was found using mysql_num_rows; and if there is a result, then it dumps the result into some variables. The PHP closes the connection and then proceeds to echo information about the result back to the user.
Notice that mysql_result in our example retrieves row 0 and column 0 from the result to retrieve the first column of the first row. This numbering scheme isn't the intuitive approach, but it's the way that PHP tends to number things.
We'll see more examples of database access in succeeding chapters, but you'll see that they all use the same template for communicating with the database.

Random number generation

<html>
<head><title>Random number</title></head>
<body>
<p>I have chosen <?php
    echo rand(1, 100);
?></p>
</body>
</html>

Loading a Drop Down List Using jQuery

Loading a Drop Down List Using jQuery

in jQuery
To load a drop down list (or a simple list) from a database, there are different ways. One is to embed PHP code in the HTML code, that loops through the rows in the database and adds <option> </option> tags.
<select name='mylist' id='mylist' size='1'>
<?php
while($rec = mysql_fetch_assoc($result))
{
    echo "<option>".$rec['name']."</option>";
}
?>
</select>
A better alternative is to dynamically load the list using Ajax.

There are several advantages:
  • In the earlier method, the generated HTML page can become too big making it too long to load the page. When we load the list dynamically, the page loads first and the list loads later. The user gets response faster.
  • If there are more than one lists with the same options (like, 'country' or 'state' lists), The same options are duplicated in all the lists, making a big HTML page that takes too long to load. With a dynamically loaded list, the same options could be loaded in all the lists at the same time.
And with jQuery, it is quite easy to load a list through Ajax. Here is how.

The jQuery Code

We can use the getJSON() function to load the list data. Here is the code:
function loadlist(selobj,url,nameattr)
{
    $(selobj).empty();
    $.getJSON(url,{},function(data)
    {
        $.each(data, function(i,obj)
        {
            $(selobj).append(
                 $('<option></option>')
                        .val(obj[nameattr])
                        .html(obj[nameattr]));
        });
    });
}
The function can be called like this:
loadlist($('select#country1').get(0),/*the 'select' object*/
 'get-list.php?getlist=country',/*the url of the server-side script*/
 'country'/*The name of the field in the returned list*/
 );
The first parameter to the loadlist() function is the 'select' object in the HTML page. Notice how the ID of the select list is used in the sample code to get the select object. Second parameter is the URL of the server side script. You can pass extra parameters to the server side script. It would be a good idea to have a single script to fetch all the lists- just change the parameters to fetch a different list.
The server-side script must return a valid JSON array of objects.
A sample valid JSON return string would be like this:
[{"ccode":"AF","country":"Afghanistan"},
{"ccode":"AL","country":"Albania"},
{"ccode":"DZ","country":"Algeria"},
{"ccode":"AS","country":"American Samoa"},
{"ccode":"AD","country":"Andorra"},
{"ccode":"AO","country":"Angola"},
{"ccode":"AI","country":"Anguilla"},
{"ccode":"AQ","country":"Antarctica"},
{"ccode":"AG","country":"Antigua and Barbuda"},
{"ccode":"AR","country":"Argentina"},
{"ccode":"AM","country":"Armenia"},
{"ccode":"AW","country":"Aruba"},
{"ccode":"AU","country":"Australia"},
{"ccode":"AT","country":"Austria"}]
Notice the 'country' field in the JSON object. The third parameter of loadlist() function is the name of the field to be used as the list item name in the list.(in this example the 'country' field)
Here is a sample server-side 'list-fetcher' code in PHP:

The PHP code

On the server side, all that we have to do is to fetch the list from the Database, format it in JSON and pass it back.
Here is the code:
if(!empty($_GET['getlist']))
{
    $list = $_GET['getlist'];
    $qry='';
    switch($list)
    {
        case 'country':
        {
            $qry = "select country from countries";
            break;
        }
    }
    /*
    Note: Why not send  the table name itself as the 'getlist'
    param (avoiding the switch above)?
    Because it is dangerous! that will enable anyone browse your database!
    */
    if(empty($qry)){ echo "invalid params! "; exit; }
    $dbconn = mysql_connect('localhost','pmj','p')
            or die("DB login failed!");
    mysql_select_db('testdb', $dbconn)
            or die("Database does not exist! ".mysql_error($dbconn));
    $result = mysql_query($qry,$dbconn)
            or die("Query $qry failed! ".mysql_error($dbconn));
    $rows = array();
    while($rec = mysql_fetch_assoc($result))
    {
        $rows[] = $rec;
    }
    mysql_free_result($result);
    mysql_close($dbconn);
    echo json_encode($rows);
}
(Note: you can get the handy SQL code to create a country list here: Country list formatted for MySQL import)
See the Demo
Download the code

Labels

AJAX (1) Answers (1) Apache (1) Array (16) bug (1) C (1) C++ (1) Calendar (1) Class (1) Commands (1) Cookies (2) Database (2) Date (7) Days (1) explode (1) File Upload (1) FILES (1) firewall (1) fix (1) Functions (26) GET (1) GMT (1) JavaScript (2) localhost (1) Mail (1) Menu (1) MYSQL (13) PERL (1) PHP (36) php.ini (1) POST (1) preg_match (1) Questions (1) Script (1) SMS (2) Solution (1) String (1) Time (5) Time Zone (1) Vista (1) Wamp Server (1) windows 7 (2) XML (1)

Popular Posts

Popular Posts