PHP voting program for instance learning

Source: Internet
Author: User
If you have never been familiar with PHP, let's take a look at it first. of course, even if you already know something about PHP, you still need a PHP4 User Manual ,:). In addition, an HTML syntax manual is of course indispensable .......... This article is an example of PHP form processing. if you have never touched php before, please take a look at it first, of course, even if you already know something about PHP, you still need a PHP4 User Manual ,:). In addition, an HTML syntax manual is of course indispensable .......... This article is a successor to "instance learning PHP form processing". if you are not clear about php processing forms, read the previous article ----------- example learning PHP form processing.

After learning about the processing of the previous form, do you want to develop a small program with confidence? Okay. let's start with something really useful! A php voting program that can be applied. In this article, we will learn how to use cookie technology, PHP array operations, and File Processing. How? Are you ready? Let's go!

Before starting a specific program design, let's take a look at several important concepts and functions that need to be used below:

The first is cookie. we need to use it to prevent repeated voting on the same machine.

So what is cookie? If your English is good enough and you want to eat cookies of the original flavor, you can try them first. Otherwise, you will only have to eat and store them for you ..... (Not good. don't flat me ,:))

Cookie originally meant cookies in American languages. of course we don't want to eat them now. here, cookies refer to ASCII files with many restrictions. It is sent to the user by the server to record some information about the user during browsing. The file size of Cookies is limited to 4 K. Cookies are widely used. for example, if some websites you have visited record the number of times you have been there, most of them use cookies. Here we use it to record whether a visitor has voted.

In PHP, we can easily use the setcookie function to use cookies. cookies are actually part of the HTTP header. Therefore, the setcookie function must be called before any other information is output to the browser. Simply put, you mustUse this function before marking ....... The following is an example of setcookie usage. it is from the PHP4 Chinese manual of Starling's eldest brother. you can refer to our specific usage in the program later.

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

Function type: Network System

Description

This function sends a small message string to the browser following the Header. To use this function, before sending HTML data, the cookie is actually a part of the header. Except the first name, this function can be omitted. The parameter name indicates the name of the cookie. The value indicates the value of the cookie. If this parameter is an empty string, information about the cookie in the browser is canceled. The expire parameter indicates the validity period of the cookie; path indicates the relevant path of the cookie. domain indicates the cookie website. secure is valid only during secure https transmission. The format of The expire time is as follows:

Wdy, DD-Mon-yyyy hh: MM: SS GMT

GMT indicates GMT Standard Time

Example

Sample setcookie () and header () provided by dante@mpath.com (27-May-1999.

$ Status = 0;
If (isset ($ myTstCky) & ($ myTstCky = "ChocChip") $ status = 1;
If (! Isset ($ CCHK )){
Setcookie ("myTstCky", "ChocChip ");
Header ("Location: $ PHP_SELF? CCHK = 1 ");
Exit;
}
?>

Cookie Check

Cookie Check Status:
Printf ('% s
;',
$ Status? "00FF00": "FF0000 ",
$ Status? "PASSED! ":" FAILED! ");
?>



How is it? Do you know something about cookie usage? Here is a tip about the expire date. if you want to set the cookie's expire date to the third day from the current day. You can use the time () function, which returns the current time in seconds (note! This time includes year, month, and day. isn't it strange? :)), If you want to set the expire date as the third day, it is time () 60*60*24*3.

The PHP array is very simple to use. you only need to note that the default start subscript starts from scratch like the C language. of course, you can set its own subscript, as shown below:

$ DescArray = array (
1 => "English: source code, program download ",
2 => "English: php dynamics ",
3 => "English: News Group, announcement board ",
4 => "English: Teaching ",
5 => "Chinese: source code, program download ",
6 => "Chinese: news groups, announcement boards ",
7 => "Chinese: teaching ");

$ DescArray [1] = "English: source code, program Download ". What's more, you can also...

$ MyArray2 = array ("
Geographic support "=> array (" sub "," ugly "," Yin "," Mao "),
"Zodiac" => array ("rat", "ox", "Tiger", "Rabbit "),
"Number" => array (1, 2, 3, 4 ));

$ MyArray2 [""] [0] = "sub" when using it; how can this problem be solved? Is it quite humane ,:)

Finally, let's take a look at PHP's file processing. There are dozens of PHP functions for file processing. in our section, five of them are used: fopen (); fclose (); flock (); fexists (); fwrite (); specifically, I would like to focus on flock (); others should check their own manuals.

Why do we need to focus on flock ()? This is A very important function for network programming. for example, two people vote at the same time and select option A. If they open data files at the same time, at this time, A's vote is 2, and then both processes add 1 to the original one, and then write data and the other to finish writing. what will happen to you? What are the votes of? The correct result should be 4, but it will actually be 3. Why? This is because of the characteristics of the multi-person environment of the network. Therefore, before voting, we must use the flock () function to lock the file and open the file to allow other processes to perform operations, this prevents the above errors. The following describes the usage of the flock function.

Flock locks the file.

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

Return value: Boolean value

Category: File Access

Content Description: This function is used to lock files and make other itineraries inaccessible. The input parameter fp is the archive indicator. The operation parameter value is one of the following numbers:

1. it indicates that the locked file can be read by other itineraries;

2. indicates that only the specified itinerary can be written into an archive;

3. read/write locks;

4. do not lock blocks ).

The locking effect of this function in UNIX or Windows is similar. If the execution is successful, the return value is true. Otherwise, the return value is false.

Now, we have learned the basics. let's do it! Let's take a look at this sample program. Then you can try it on your own platform. I believe this will get a bit of perceptual knowledge.

In which vote. php is the main program file, and config. php is used to set some frequently-needed information.

// Config. php file


// The title variable sets the title tag in this html file, that is, the title displayed in the browser title bar.
$ Title = reader type questionnaire;

// Set the survey content. An array is used here. Note that the content is enclosed with the "" number.
$ Option = array ("student", "worker", "farmer", "intellectual", "capitalist", "rogue ");

// Set the file to which the survey result is saved
$ Countfile = "sum.txt ";

// Set the time for the same machine to vote again
$ Limitdate = time () 60*60*24*365;

?>

// Vote. php file

/* First install the configuration information. here I will briefly describe the difference between require and include. require is usually placed at the beginning of the PHP program. before the PHP program is executed, read the file specified by require to make it a part of the PHP web page. This method can also be used to introduce a commonly used function to a webpage. Include is generally placed in the process section of process control. The include file is read on the PHP webpage. This method simplifies the process during program execution. */



/* The following part is the cookie, and its expire time is in the config. php settings, and you may have discovered that there are two if comparison statements. The first one is to check whether there are cookie settings, the second is to avoid sending cookies without a voting program. */
If (isset ($ vote) & $ vote = "Ready") $ status = 1;
Else $ status = 0;
If ($ ready = "true ")
{
Setcookie ("vote", "Ready", $ limitdate );
}
?>



<? Echo $ title?>





// Read the original ballot result and assign it to the variable $ result
If (file_exists ($ countfile )){
$ Result = file ($ countfile );
}
?>

/* The main program uses the switch to create three branches: Case 1, view the result, Case 2, submit the selection, Case 3, generate the form */
Switch ($ elect ){

/* To view the result, display the variables read by the file () function above */
Case "view result ":
Echo"


Echo"



";For ($ I = 0; $ I "." ";Echo" ";Echo" ";}Echo"
". $ Option [$ I].""." Echo "$ result [$ I] * 10 ";
Echo "'height = '8'>
"." ". $ Result [$ I]."
";
Break;

/* Write the selection result to the file. use flock to lock the file! Although this problem is not particularly prominent for the voting program */
Case "submit ":
If ($ status = 1 ){
Echo "you have 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]."
";
Fwrite ($ fp, $ result [$ I]. "\ n ");
}
} Else "failed to vote ";
} Else echo "failed to vote ";
Fclose ($ fp );
}
Break;

/* Display the voting form */
Default:
Echo "";
}
?>





Such a simple php voting application is completed, simply because the program only completed several of the most important features of the voting application, and some details were not handled. For example, after a file fails to be written, how can users disable the cookie function. The specific improvements are left to readers and friends.

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.