Home >
Backend Development >
PHP Tutorial >
Function description of the main functions of the PHP guestbook module (code can be implemented)_PHP tutorial
Function description of the main functions of the PHP guestbook module (code can be implemented)_PHP tutorial
WBOY
Release: 2016-07-21 15:03:01
Original
945 people have browsed it
1. Sensitive word processing 1. Filtering sensitive words preg_match() function is used to search for all content matching a given regular expression in a string , returns True if it exists, otherwise returns False. Syntax: int preg_match(string pattern,string subject[,array matches[,int flags]]) preg_match( )The function parameter description is as follows: pattern:Necessary parameters, the regular expression that needs to be matched subject:Necessary parameters, the input string matches: Optional parameters. An array that outputs search results. For example, $out[0] will contain results that match the entire pattern, $out[1] will contain results that match the first captured subpattern in parentheses, and so on flags:Optional parameter. Tag: PREG_OFFSET_CAPTURE, for each matching result page that appears, its associated string offset is returned at the same time, available after PHP 4.3.0.
The specific implementation method is as follows: First, use the file() function to read the sensitive words stored in the sub-text file (each sensitive word is a separate line), and add the total Stored in the array $file_word. Then, use a for loop statement to automatically read array elements (sensitive words), and directly use regular expressions to check whether the message information submitted by the user contains sensitive words.
When the user posts a message and submits Li Yan's message, the message will be compared with the sensitive words stored in the array. If the message contains sensitive words, a prompt message will pop up. Otherwise, the message will pop up. Published successfully. The key code to implement sensitive word filtering is as follows:
Copy code The code is as follows:
if (is_file("./filterwords.txt ")){ //Determine whether the given file name is a normal file $filter_word = file("filterwords.txt"); //Read the entire file into an array $str=$_POST ['content']; for($i=0;$i if(preg_match("/" .trim($filter_word[$i])."/i",$str)){ //Apply regular expressions to determine whether the message message passed contains sensitive words echo "<script> alert(' The message contains sensitive words! ');history.back(-1);</script>"; exit; } } }
file() function array file (string filename [, int use_include_path [, resource context]]) The same as readfile(), except that file() returns the file as an array . Each cell in the array is a corresponding line in the file, including newlines. If file() fails, it returns FALSE. 2, add sensitive words to the text file The main function of php writing sensitive words to the text file (1) is_writable() function The is_writable() function is used to determine whether a file exists and is writable. If the above conditions are met, it returns True, otherwise it returns False. Syntax: bool is_writable(string filename) parameter filename is used to specify the full path of the file (c:/leaveMessage/filterwords.txt) or relative path (corresponding to the calling file path filterwords.txt), Writable returns true, unwritable returns false Example:
(2)fopen() function fopen() function is used to open a file and return the marked pointer of the file. The file can be local or remote. Syntax: resource fopen(string filename,string mode[,int use_include_path[,resource context]]) Parameters: filename:Required parameters. Used to specify the local or remote address of the file to be opened mode:Required parameters. Use_include_path: optional parameter to specify the mode in which the file is to be opened. If this parameter is set to True, PHP will try to open the file according to each pointer in the include_path standard include path context: optional parameter. Set some options to improve file streaming performance mode file opening mode parameter description: 'r' Open in read-only mode, pointing the file pointer to the file header. 'r+' Open in read-write mode and point the file pointer to the file header. 'w' turns on writing mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it. 'w+' Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. 'a' opens in writing mode and points the file pointer to the end of the file. If the file does not exist, try to create it. 'a+' Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. 'x' creates and opens for writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE, and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag to the underlying open(2) system call. This option is supported by PHP4.3.2 and later versions and can only be used for local files. 'x+' creates and opens it for reading and writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE, and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag to the underlying open(2) system call. This option is supported by PHP 4.3.2 and later, and can only be used for local files.
Example: The fopen() function opens the file in read-only mode
Copy the code The code is as follows:
$fp=fopen("filterwords.txt","r"); ?>
(3) fseek() function fseek() function is used to set the position of the file pointer Syntax: int fseek(resource handle, int offset[,int whence]) Parameters: handle:Required parameters. The file identifier returned after opening a file offset:necessary parameter. Used to set the position of the file pointer whence: can omit parameters. fessk() Description of the whence parameter of the function seek_set: Set the position equal to offset bytes. This value is the default value of this parameter seek_cur:Set the position equal to the current position plus offset bytes seek_end:Set the position equal to the end of the file plus offset bytes Bytes For example, use the fopen() function to open the file "test.txt", then read the 4096-byte content of the file, and finally use the fseek() function to restore the file pointer to its original position.
Copy code The code is as follows:
$fp=fopen("filterwords.txt", "r"); //Open a file in read-only mode $data=fgets($fp,4096); //Read a line of 4096 bytes in the file fseek($fp,0 ); //Make the file pointer point to the 0th byte position ?>
string fgets(int handle[,int length]) from the file pointed to by handle Reads a line and returns a string up to length - 1 bytes long. Stops when a newline character (included in the return value), EOF, or length- 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes. (Considering program execution efficiency, a fixed length value is generally used) (4) fwrite() function fwrite() function is used to write a string into a specified file , and can specify the size of written bytes. Syntax: int fwrite(resource handle,string string[,int length]) Parameter description: handle:Required parameters. File identification pointer string:Required parameters. The string to be written to a file length: can omit parameters. Refers to the length of the written file. If this parameter is omitted, all the contents of the specified string will be written to the file For example: the fwrite() function writes the string "PHP Guestbook" into the filterwords.txt file
(5)fclose() function fclose() function is used to close the file pointed to by the specified file identifier. Syntax: bool fclose(resource handle) The parameter handle is the file identifier returned by the fopen() function or fsockopen() function after successfully opening a file. In the guestbook module, the function introduced above is used to add sensitive words to the text file "filterwords.txt".
Copy code The code is as follows:
if($_POST){ $filename ="../filterwords.txt"; if(is_writable($filename)){ $file=fopen($filename,'r+'); //Open in read-write mode, point the file pointer to the file head. } else{ echo "File".$filename."Not writable"; } //Write the file at the end of the file fseek($file,0,SEEK_END ); //Set the pointer position. The SEEK_END setting position is equal to the end of the file plus offset (here is zero) bytes $word=$_POST[txt_word]; fwrite($file,$word); fwrite($file,"rn"); fclose($file); } ?>
3, read the file Sensitive words
Copy code The code is as follows:
$filename=".. /filterwords.txt"; if(is_readable($filename)){ $arr=file($filename); } else{ echo "File".$filename. "Unreadable"; } while(list($name,$value)=each($arr)){ //Traverse the array $a.="$value".","; } echo " The sensitive words are as follows: ".$a; ?>
(1)is_readable() Determine whether the file exists and is readable. If the above conditions are met, return True Syntax: bool is_readable(string filename), The parameter filename is used to specify the full path of the file (2)void list(mixed...) Like array(), this is not a real function, but a language structure. list() assigns values to a set of variables in one step. list() can only be used on numerically indexed arrays and assumes that numerical indexing starts from 0. For example:
Copy code The code is as follows:
$info = array('coffee', 'brown', 'caffeine'); list($drink, $color, $power ) = $info; print "$drink is $color and $power makes it special.n"; //coffee is brown and caffeine makes it special. list($drink, $color) = $info; print "$drink is $color.n"; //coffee is brown. ?>
(3)array each (array array) Returns the key and value of the current pointer position in the array array and moves the array pointer forward. The key-value pair is returned as an array of four cells, with key names 0, 1, key and value. Cells 0 and key contain the key names of the array cells, and 1 and value contain the data. If the internal pointer goes beyond the end of the array, each() returns FALSE.
each() returns an array as follows [key] => 0 } list() only works on numeric indexes, and the default key starts from zero. Therefore, list($name,$value) assigns the key 0 and the value bob to $name and $value respectively.
4 to achieve full selection and inverse selection of the check box
according to the database The content uses a for loop statement to dynamically create the number of check boxes. The check boxes that are all selected or deselected must be set to name note_id[], and the value of the check box is the ID number of the message message.
Add a checkbox that selects all , as content to select. When the check box is checked, the custom function check_all() function is called to set the check box to be all selected. Select all span> Select all implementation, traverse all check boxes form.elements[i], and then set the checked attribute of each multi-option to True. Implementation of inverse selection, traverse all check boxes form.elements[i], get the checked attribute value of the check box, if it is True, set it to False, otherwise set it to True, which is the opposite setting of the current value.
Copy code
The code is as follows:
2. Guestbook code analysis
1. The problem of intercepting Chinese strings with substr() Function: string substr(string string, int start, int [length]); Parameter description: string: Required, indicating the string to be processed start:Required, indicating starting from the start position of the string string Take, if start is a negative number, then count from the end of the string length: is optional, indicating the length of the string to be taken, if length is a negative number, it means taking the last length length The character Chinese characters occupy two lengths, and English characters and symbols occupy one length. PHP built-in function substr(string str,intstart,[int length]) is used to intercept the specified string length. There is no problem when intercepting English strings, but when intercepting Chinese or mixed Chinese and English strings, there will be a problem that the last character turns into a question mark. The following is a custom Chinese string interception function:
Copy the code The code is as follows:
function str_cut($str,$start,$length){ //Chinese string interception function $str_new=iconv_substr($str,$start,$length,"utf-8"); if($start==0){ if(strlen(utf8_decode($str))>($length+$start)){
$str_new.=".";
} } return $str_new; }
2. The htmlspecialchars() function converts some predefined characters into HTML entities. Functions are designed to prevent illegal operations by users.
For example:
Copy code The code is as follows:
$str='
I added Half layer
Half table row mark http://www.jb51.net">Script Home'; echo htmlspecialchars($str); The output is:
The half layer I added
Half table row mark http://www.jb51.net">Script Home 3,str_replace( ) function uses a string to replace other characters in the string. Syntax: str_replace(find,replace,string,count) Parameter description: find: must. Specifies the value to be found. replace:Required. Specifies the value to replace the find content string: is required. Specifies the string to be searched count:optional. A variable counting the number of substitutions
http://www.bkjia.com/PHPjc/327862.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327862.htmlTechArticle1. Sensitive word processing 1. Filter sensitive words. The preg_match() function is used to search for all the characters matching the given words in the string. The content matched by a certain regular expression, returns True if it exists, otherwise returns Fa...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn