Example Learning PHP Voting program

Source: Internet
Author: User
Tags file size flock flock lock functions header install php net variable
Program | vote to learn PHP, of course, you have to install PHP, so if you are the first time to learn, please read the online college article:



PHP4.03 installation under Linux

Installation of PHP4.04 under Win98

Installation of PHP4.04 under English Win2000

If you cannot find the installer, please download it below:

Php4.04beta WIN32 installation program


PHP4.03 source Program


PHP3.0.16 WIN32 installation program


PHP3.0.16 source Program

This is the "Example learning php form processing," the successor, please see the PHP processing form is not clear friends first read the previous ———— example learning php form processing.

After you learn the previous form processing, is not confident to do a little program it? OK, let's start by doing something really useful! A PHP voting procedure that can be applied. In this article you will learn the use of cookie technology, PHP array operations and file processing. How is it? Are you ready, everyone? Let ' s go!

Before we start the specific programming, let's take a look at a few important concepts and functions that need to be used here:

First of all, cookies, we need to use him to prevent the same machine from repeating the ballot.

So what is a cookie? If your English is good enough and you want to eat a piece of original cookie, come here and taste it first, or you'll only have to eat to hide the heat. (not good to eat don't beat me Yo,:-)))

Cookie literals are cookies in the American language, and of course we're not going to eat them now, in this cookie refers to an ASCII file with a lot of restrictions. It is sent by the server to the user to record some information about the user during the browsing process. The file size of cookies is limited to 4K. Cookies are used for a lot of things, such as the number of sites you've visited that have recorded how many times you've been there, and that's mostly cookies. Here we use him to record whether the visitor has voted.

In PHP we can use the Setcookie function very conveniently with the Cookie,cookie is actually part of the header in the HTTP protocol. Therefore, the Setcookie function must be invoked before any other information is exported to the browser. The simple point is to use this function before the < Html> logo ... The following is an example of the usage of Setcookie, the PHP4 Chinese manual from the Star Prodigal, and we can also refer to our specific usage in the program.

Setcookie

Send Cookie information to the browser.

Syntax: int Setcookie (string name, string value, int expire, string path, string domain, int secure);

return value: Integer

Type of function: Network system

Content Description

This function sends a small message string to the browser following the header header. Using this function, the cookie is actually counted as part of the header before sending out the HTML data. The parameters of this function can be omitted except for the first name. The parameter name indicates the name of the cookie, the value of the cookie, which is an empty string that cancels the data for the cookie in the browser, expire the valid time for the cookie, and the path is the relevant route for the cookie; DOMA In the Web site that represents the cookie, and secure is valid when the HTTPS is securely transmitted.

The format of the expire time is as follows:

Wdy, dd-mon-yyyy HH:MM:SS GMT

GMT for Greenwich Mean Time

Usage examples

The Setcookie () and header () examples provided by dante@mpath.com (27-may-1999).

< PHP
$status = 0;
if (Isset ($myTstCky) && ($myTstCky = = "Chocchip")) $status = 1;
if (!isset ($CCHK)) {
Setcookie ("Mytstcky", "chocchip");
Header ("Location: $PHP _self?" Cchk=1 ");
Exit
}
?>
< html>
< head>< Title>cookie check</title>< body bgcolor= "#FFFFFF" text= "#000000" >
Cookie Check Status:
< PHP
printf (' < font color= ' #%s ">%s</font>< br>; ')
$status? "00FF00": "FF0000",
$status? "passed!": "failed!");
?>
</body>



What do you think? Do you know something about the use of cookies? Hide here to tell you a little tip about the expire date, if you want to let the cookie's expire date be the third day from the current count. Then you can use the time () function, which returns a current in seconds (note yo!). This time is included in the year and the day, is not very strange? ), then if you want to set the expire date as the third day, then time () +60*60*24*3.

The PHP array is very simple to use, everyone just notice its default starting subscript is like C language from scratch, of course, you can also set its subscript, as follows:

$descArray =array (
1=> "English: Source code, program download",
2=> "English: Php dynamic",
3=> "English: News Group, Bulletin Board",
4=> "English: Teaching Class",
5=> "Chinese: Source code, program download",
6=> "Chinese: Newsgroups, bulletin boards",
7=> "Chinese: Teaching class");



When used $descArray [1]= English: Source code, program download. What's more, you can still ...

$MyArray 2 = Array ("
=> Array ("Zi", "ugly", "Yin", "Mao"),
"Zodiac" => Array ("Rat", "ox", "Tiger", "Rabbit"),
"Digital" => Array (1, 2, 3, 4));



When used, $myarray2["Earthly Branches"][0]= "Zi"; What do you think? is not very human ah,:

Finally, we look at the file processing PHP, PHP for the file processing function has about dozens of, in our section, the use of which the five functions fopen (); Fclose (); Flock (); fexists (); fwrite (); I would like to focus on the flock (), the other people go to their own manual.

Why focus on flock ()? Because this is a very important function for network programming, for example, two people vote at the same time and choose option A, assuming they open the data file at the same time, when A's vote is 2, then both processes add 1 to the original, then one writes the data, and the other writes the Write, What do you think will happen then? How much is a vote? The correct result should be 4, but in fact it would be 3. Why is that? This is because of the characteristics of the network's many people, so we must first use the flock () function to lock the file, and then open the file to allow other processes to operate, so as to prevent the occurrence of the above type of error. The following is a description of the usage of the flock function.

Flock Lock the file.

Syntax: Boolean flock (int fp, int operation);

Return Value: Boolean value

Types of functions: File access

Content Description This function is used to lock the file so that other journeys cannot be accessed. The incoming parameter FP is the index of the file. The value of the parameter operation is one of the following numbers:

1, indicating that the set lock file can allow other travel to read;

2, that only the itinerary can be written into the file;

3, the means of reading and writing are locked;

4, do not lock blocks (block).

This function is similar in both UNIX and Windows family lock effects. Successful execution returns a true value or returns a value of false.



Well, the basic things have been learned, let us carry out the actual combat it! Let's start with this example program. Then you can try it on your own platform first. Believe this will get a little perceptual knowledge.

In this application a total of three file vote.php,config.php,http://www.163design.net/p/b/1.gif and a file to save data (the name of the file can be set freely, Here we set it to Sum.txt, where vote.php is the main program file, and config.php is used to set up some information that needs to be modified frequently.

config.php file

<?

Title variable sets the title tag in this HTML file, which appears in the browser title bar
$title = type of reader questionnaire;

Set up the survey content. Here we use an array, and note that the "" number is used to enclose the content.
$option = Array ("Student", "worker", "peasant", "intellectual", "capitalist", "rogue");

Set the results of the survey to which file to save
$countfile = "Sum.txt";

Set the time when the same machine can vote again
$limitdate = time () +60*60*24*365;

?>

vote.php file

/* First put the configuration information, here I briefly explain the difference between require and include, require is usually placed in the front of the PHP program, PHP programs in the implementation, will first read into the Require designated file, make it a part of the PHP program page. A commonly used function can also be introduced into a Web page in this way. Include is typically placed in the processing section of the Process Control. The PHP Program page reads the included file when it is read. This way you can simplify the process of executing your program. */

<? Require "config.php";? >

/* The following section is a cookie, its expire time is set in the above config.php, and you may have found that there are two if comparison statements, the first is to detect whether there is a cookie set, The second is to prevent people from sending cookies without a voting procedure. */
<?
if (Isset ($vote) && $vote = = "Ready") $status = 1;
else $status = 0;
if ($ready = = "true")
{
Setcookie ("Vote", "Ready", $limitdate);
}
?>

< html>
< head>
< title><? echo $title?></title>
< meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

< body bgcolor= "#FFFFFF" >

Read out the original ballot results and assign them to the variable $result
<?
if (file_exists ($countfile)) {
$result = file ($countfile);
}
?>

/* The following is the main program with switch to do three branches, Case 1, view the results, Case 2, submit the choice; case 3, generate the form * *
<?
Switch ($elect) {


/* View the results, the actual is the above with the file () function read out the variables shown.
Case "View Results":
echo "< table border= ' 0 ' >";
For ($i =0 $i < count ($result); $i + +) {
echo "< tr>". < td> ". $option [$i]." </td> ";
echo "< td>". < img src= ' http://www.163design.net/p/b/1.gif ' width= ';
echo "$result [$i]*10";
echo "' height= ' 8 ' > </td>";
echo "< td>". ". $result [$i]." </td></tr> ";
}
echo "</table>";
Break


/* The selection results are written to the file, note to use flock to lock the file! Although this question is not particularly prominent in the voting procedure.
Case "Submit":
if ($status = = 1) {
echo "You've already voted."
}elseif ($sugest = = 0) {
echo "You Havn ' t choice";
}else{
if ($fp =fopen ($countfile, "w")) {
if (Flock ($FP, 3)) {
For ($i =0 $i < count ($option); $i + +) {
if ($sugest = = $i + 1) {
$result [$i]= $result [$i]+1;
}else $result [$i]= $result [$i] + 0;
echo $option [$i]. " ". $result [$i]." < br> ";
Fwrite ($fp, $result [$i]. " ");
}
}else "Vote failed";
}else echo "Vote failed";
Fclose ($FP);
}
Break

/* Display the voting form * * *
Default
echo "< form action= ' vote.php ' method= ' post ' name= ' Form1 ' >";
$sum = count ($option);
for ($i =0; $i < $sum; $i + +) {
echo "< input type= ' radio ' name= ' sugest ' value=";
echo $i +1;
if ($i ==0) echo "CHECKED";
echo ">". $option [$i]. " < br> ";
}
echo "< input type= ' hidden ' name= ' ready ' value= ' true ' > ';
echo "< br>";
echo "< input type= ' submit ' name = ' elect ' value= ' submitted ' > ';
echo "< input type= ' submit ' name= ' elect ' value= ' view results ' >";
echo "</form>";
}
?>
</p>
</body>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.