1, Object oriented programming
1. Class and object
1.1. Classes and objects
- Class class name {member}
- $object name = new class name (parameter);
1.2. Class encapsulation
<?php class Person { // The following are the member properties of people, which are encapsulated private members private $name ; // People's names private $sex ; // Human gender private $age ; // People's age //__ The get() method is used to get private properties public function __get( $a ){ if ( isset( $this -> $a) ) //If this variable is not set return $this -> $a; else return (NULL); } //__ The set() method is used to set private properties public function __set($a,$value){ $this -> $a = $value; } } $p1 = new Person(); // The operation of directly assigning values to private attributes will be called automatically__ set() method for assignment $p1 ->name= " Zhang San " ; $p1 ->sex= " male " ; $p1 ->age= 20 ; // Get the value of the private property directly, and it will be called automatically__ The get() method returns the value of the member property echo " full name: " .$p1 ->name; echo "<hr>"; echo " Gender: " .$p1 ->sex; echo "<hr>"; echo " Age: " .$p1 ->age; ?>
2. Construction method and deconstruction method
<?php /*Construction method: * Modifier function__ Construct (parameter list){ * //Initialization operation * } * Deconstruction method: * Modifier function _destruct (parameter list){ * //Cleaning operation * } * */ class Person{ public $name; public function __construct($name){//Construction method $this->name = $name; } public function show(){ echo "Hello, I'm Person Object of class" .$this->name. "<br>"; } function __destruct(){//Deconstruction method echo "Object destroyed"; } } $Sunlight = new Person("Sunlight"); $Sunlight ->show(); ?>
3. Class constants and static members
3.1. Class constant
- cont PI=3.1415926; define a constant
- The variables declared in the class belong to the class itself. When calling, use the range resolver (::) to connect the class name and class constant to access them
<?php class MathTool { const PI=3.1415926; public function show(){ echo MathTool::PI; echo "<hr>"; echo self::PI; } } echo MathTool::PI;//Accessing constants of classes externally echo "<hr>"; $ma = new MathTool(); $ma->show();
3.2. Static method
- Modify with static
- The static method declared in the class belongs to the class itself and will not change with the object. When calling, use the range resolver (::) to connect the class name and static method for access
<?php class Student { //Define the school name of the student of the show method Secretariat public static $schoolName="JXNU"; public static function show(){ echo "My School is : ".self::$schoolName; } } Student::show();
4. Succession
- Class subclass name extends parent class name {/ / class body}
- The parent keyword accesses the parent method. The usage is similar to self here, which is equivalent to super in java
- After the final keyword is modified, the class cannot be inherited and the method cannot be overridden
5. Automatic loading and magic method
-
When the class definition file is not found, the _autoload() function is automatically called. Automatic loading cannot complete the function of loading classes by itself, and the specific loading code should be written as needed.
-
Magic method, which does not need to be called manually, will be executed automatically at a certain time
method | describe |
---|---|
__toString() | Called when an object is output to convert the object to a string |
__sleep() | Object is called before serialization, delaying the execution of the program for a period of time |
__wakeup() | Called when an object is deserialized to restore the serialized object |
__get() __set() | Get and set private variables |
__construct() __destruct() | Tectonics and Deconstruction |
__autoload() | Automatic loading |
6. Abstract classes and interfaces
6.1. Abstract class
- Abstract class definition: abstract class class name () {/ / class member}
- abstract function method name (); no function body
- A class inherits an abstract class and must implement all abstract methods of the abstract class
- Abstract classes cannot be instantiated
6.2. Interface
- interface Animal { public function run(); } Define interface
- implements implementation interface
<?php interface Animal { public function run (); public function shout(); } interface LandAnimal{ public function LiveOnLand(); } //Define the dog class to implement these two interfaces: class Dog implements Animal,LandAnimal{ public function LiveOnLand(){ echo "Dogs live on land<br>"; } public function run(){ echo "The dog is running<br>"; } public function shout() { echo "Woof, woof~~~~<br>"; } } $dog = new Dog(); $dog->LiveOnLand(); $dog->run(); $dog->shout();
Namespace
- Calling classes with duplicate names will cause errors, so you can set a namespace in a php file so that other files will not access the classes in this namespace
- namespace DataCleaner; defining namespaces
- The namespace must be written in the first statement of the program script
- Classes, functions, and constants are all affected by namespaces
- You can use namespaces to access classes from one another
- Here, fully qualified names are used to refer to classes in different php files
2, Error handling and debugging
1. Error type
- 1) Syntax error: the code written by the user does not comply with the syntax specification of PHP. Syntax errors will cause the code to fail during compilation, so the code will not be executed (Parse error)
- 2) Runtime error: the code has been compiled, but some errors (runtime error) caused by unsatisfied conditions will occur during code execution
- 3) Logical error: the programmer is not standardized when writing code, and some logical errors occur, resulting in the normal execution of the code, but can not get the desired results
- Manual trigger error: trigger_error("String", $a) String represents the content of error message and $a represents the specified error category
2. Error handling
- error_reporting() and ini_set()
- die() function
- Understood, do not expand description
3. Exception handling
- try catch handling exception throw throwing exception
- One exception inherits another exception to create a custom exception
<?php //Create a custom Exception class CustomException and inherit Exception class CustomException extends Exception{ //Define error method: public function errorMessage(){ //Define the display format of error messages: $errorMsg = 'Error on line '.$this->getLine(). ' in '.$this->getLine().'<b>'.$this->getMessage(). '<b> is not a valid E-mail address'; return $errorMsg; } } $email="someone@example...com"; try{ //Check whether the email address is legal: if (filter_var($email,FILTER_VALIDATE_EMAIL)===FAlSE){ throw new CustomException($email); } } catch (CustomException $e){ echo $e->errorMessage();//Call the error method and output the error information }
3, File operation
1. Document overview
- File streams: input and output streams
- Input stream: input from data source (file) to php language program. Output stream: input from php language program to data source (file).
- File type: File: normal file type, txt, png, exe
- dir: Directory type. Directory is also a kind of file
- Unknown: unknown type
- The filetype() function gets the file type
- fileexists() determines whether the file exists
1.2. File attributes:
function | function |
---|---|
filesize($filename) | Return file size |
filectime($filename) | Returns the file creation time |
filemtime($filename) | Return file modification time |
fileatime($filename) | Returns the time the file was last accessed |
is_readable($filename) | Determines whether a given file is readable |
is_writable($filename) | Determines whether a given file is writable |
is_executable($filename) | Determine whether a given file is executable |
is_file($filename) | Judge whether the given file is a normal file |
is_dir($filename) | Determine whether the given file is a directory |
stat($filename) | Returns various information about the file |
- You need to provide a $filename as a parameter. This parameter is the string of the file address to obtain the information of the specific file
2. File operation
2.1. Opening and closing files
- foprn($filename, $mode)
- filename can be a local file or a url
- Mode is mode, r is read-only, r + read-write, w write, W + read-write
- A write, the file pointer is at the end of the file, a + read and write, and the file pointer is at the end of the file
- x creates and opens in write mode, the pointer points to the file header, and x + creates and opens in read-write mode
- Close file fclose($filename)
2.2. Reading files
function | describe |
---|---|
fread($handle, $a) | Returns a string of the specified length $a at the location of the $handle pointer |
fgetc($handle) | Returns a character read at the position of the pointer |
fgets($handle, $a) | Returns a line of characters read at the position of the pointer. The length $a can be specified |
file_get_contents( $f) | The preferred method to read all the contents of the file into a string |
file($f) | Read the whole file into an array. Each element in the array is a line in the file, including line breaks |
2.3. Write file
- fwrite($handle, $s, $len)
$handle is the pointer position returned by fopen function, where the string s of len length is inserted, and Len can be omitted - file_put_contents($f, $data, $a)
Write data to file f, and $a=FILE_APPEND represents additional write. This function is equal to fopen+fwrite+fclose
<?php $filename="1.txt"; $content="777777\n"; $handle=fopen($filename,'w'); //fopen open file get file pointer fwrite($handle,$content);//Write data and content fclose($handle);//Close file echo "File write Cheng Kun";//Success is simple
2.4. Other operations
- Copy file: copy($specify file, $target file)
- Rename file: rename($oldname, $newname)
- Deleting a file: unlink($filename) returns true if successful, and false if failed
3. Directory operation
3.1. Resolve directory
- The basename($f, $suffix) function returns the file name in the path. If the $suffix is set, the returned file name will delete the specified suffix
- dirname($path) returns the directory portion of the path
3.2. Traverse directory
- opendir($path) opens a directory and returns a pointer to the directory
- readdir() reads the directory and returns the file name of the next file
- closedir() closes the directory
- rewinddir() rewinds the directory handle
3.3. Creating and deleting directories
- mkdir($pathname) creates a new directory named pathname
- rmdir() is used to delete directories
4. File upload and download
4.1. File upload
- First set a file upload form. The form submission method must be POST, and then add the uploaded attribute enctype = "multipart / form data"
<form enctype="multipart/form-data" ,action="upload.php" ,method="POST"> <input type="hidden" ,name="max_file_size" value="30000" /> Select File:<input type="file" name="userfile" /> <input type="submit" value="Upload file" /> </form>
- Create a folder in the directory where the current script file is located to store the uploaded file, and then realize the file upload function:
<?php //Target file: $destination='uploads/'.$_FILES['userfile']['name']; if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { if (move_uploaded_file($_FILES['userfile']['tmp_name'],$destination)) echo "Upload succeeded"; }
4.2. File download
-
Now set two corresponding headers in the http message to tell the browser not to parse the file directly in the browser, but to open the file by downloading.
Example: //Specify the MIME type of the file: header("Content-type:image/jepg"); //Specify file description: header("Content-Disposition:attachment;filename=girl.jpg");
-
The next step is to download the file
<?php $file_name = "down"; $file_name = "down.zip"; //Download file name $file_dir = "./down/"; //Download file storage directory //Check whether the file exists if (! file_exists ( $file_dir . $file_name )) { header('HTTP/1.1 404 NOT FOUND'); } else { //Open the file in read-only and binary mode $file = fopen ( $file_dir . $file_name, "rb" ); //Tell the browser that this is a file stream format file Header ( "Content-type: application/octet-stream" ); //Unit of measure for the requested range Header ( "Accept-Ranges: bytes" ); //Content length is the byte length that specifies the data contained in the request or response Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) ); //It is used to tell the browser that a file can be downloaded as an attachment. The downloaded file name is $file_name, which is the value of this variable. Header ( "Content-Disposition: attachment; filename=" . $file_name ); //Read the contents of the file and output it directly to the browser echo fread ( $file, filesize ( $file_dir . $file_name ) ); fclose ( $file ); exit (); }
4, HTTP protocol
1.HTTP overview
- HTTP, namely hypertext transfer protocol, is a request / corresponding protocol. After the client establishes a connection with the server, the request sent by the client to the server is called HTTP request, and the response made by the server after receiving the request is called HTTP response.
- First establish a TCP connection and transmit multiple HTTP requests and responses on the TCP connection.
- The server must return the corresponding results according to the order in which the client sends the request, so as to ensure that the client can distinguish the corresponding content of each request.
1.2.HTTP address
- HTTP address = web page address = uniform resource locator = url
- It consists of protocol, hostname, port, path, etc
What is a url:
The website address we enter in the address bar of the browser is called URL (Uniform Resource Locator) . just as every household has a house address, every Web page also has an Internet address. When you enter a URL in the browser's address box or click a hyperlink, the URL determines the address to browse. The browser uses Hypertext Transfer Protocol (HTTP) , extract the Web page code of the site on the Web server and translate it into beautiful Web pages. Therefore, before we understand HTTP, it is necessary to understand the composition of the URL, such as: http://www.baidu.com/china/index.htm . its meaning is as follows:
-
http: / /: stands for hypertext transfer protocol, and informs baidu.com server to display Web pages, usually without input;
-
www: represents a web (World Wide Web) server;
-
baidu.com /: This is the domain name of the server with the web page, or the name of the site server;
-
China /: it is a subdirectory on the server, just like our folder;
-
Index.htm: index.htm is an H search TML file (web page) in the folder
What is the relationship between url and domain name?
The web address is the address to open the web site;
For example: http://zhidao.baidu.com/question/263101382.html?push=core&group=1 This is the website;
The domain name is zhidao.baidu.com, which refers to the section from the front of http: / / to the first / middle.
What is the relationship between domain name and IP address?
IP is the house number address, and domain name is the name of the owner of the house. A house can change its owner, but it cannot change its address. IP address is a digital identification of the host address in the Internet. IP uses this address to transfer information between hosts, and domain name is a method used to solve the problem of address correspondence in the Internet. Domain name is as simple and easy to remember as name and can be widely transmitted Broadcast
For example:
baidu.com
google.com
Correspondence between domain name and IP address
There are two types of correspondence:
1. One on one
The IP address on the Internet is unique. An IP address corresponds to a unique host.
Given a domain name address, you can find a unique corresponding IP address.
2. One to many
A computer provides multiple services, both as a www server and a mail server.
The IP address is still unique, but different domain names can be given according to multiple services provided by the computer.
One IP address corresponds to multiple domain names.
What is DNS?
DNS: Domain Name System
People are used to memorizing domain names, but machines only recognize IP addresses. Domain names and IP addresses correspond one to one. The conversion between them is called domain name resolution. Domain name resolution needs to be completed by a special domain name resolution server, and the whole process is automatic.
DNS vs HOSTS?
The same point: the URL is resolved into an IP address
The HOSTS file is equivalent to a small local DNS server. The computer will first find the IP corresponding to the web address in the local HOSTS file. If it is not found, it will request DNS.
For example, DNS is the yellow page of the city, and HOSTS is your personal communication book.
2.HTTP request
2.1.HTTP request line
- The HTTP request line is located in the first line of the request message, which is the request method, path resource and HTTP protocol version
2.2. Eight HTTP request modes:
2.3.GET mode - If there is a parameter part in the url requested by the browser, the parameter part will be appended to the resource path in the request line in the request message generated by the browser.
- The content after "?" is parameter information. The parameter consists of parameter name and parameter value, which is connected with "=". If there are multiple parameters in the url, the parameters are separated by "&".
- The data transmitted in GET mode cannot exceed 1kb
2.4.POST mode
- When POST is used to transfer data to the server, the content type header will be automatically set to "application / x-www-form-urlencoded", and the content length header will be automatically set to the length of the entity content.
- There is no size limit for POST request transfer data
- POST requests are more secure than GET requests
2.5.HTTP request header
- Deliver additional messages to the server, including the data type, compression method, language that the client can receive, and the URL address of the page to which the requested connection belongs
- Each message header is composed of a header field and a value. The header field and value are separated by colon ":" and space ". After each request message header, a carriage return line feed symbol is used to mark the end.
- Header field names are not case sensitive. It is customary to capitalize the first letter of a word
Message header | explain |
---|---|
Accept | Acceptable response content types. |
Accept-Charset | Acceptable character set |
Accept-Encoding | Encoding of acceptable response content. |
Accept-Language | List of acceptable response content languages. |
Accept-Datetime | Acceptable response content version expressed in time |
Authorization | It is used to represent the authentication information of authentication resources in HTTP protocol |
Cache-Control | Used to specify whether to use the caching mechanism in the current request / reply. |
Connection | The type of connection that the client (browser) wants to use first |
Cookie | An HTTP protocol Cookie previously set by the server via set Cookie (see below) |
Content-Length | The length of the request body in octal |
Content-MD5 | The binary MD5 hash value (digital signature) of the content of the request body, the result of Base64 encoding |
Content-Type | MIME type of the request body (used in POST and PUT requests) |
Date | Date and time when the message was sent (in the format of "HTTP date" defined in RFC 7231) |
Expect | Indicates that the client requires the server to do specific behavior |
From | The email address of the user who initiated this request |
Host | Indicates the domain name of the server and the port number on which the server listens. If the requested port is the standard port (80) of the corresponding service, the port number can be omitted. |
If-Match | The corresponding operation is only performed when the entity provided by the client matches the corresponding entity on the server. It is mainly used in methods such as PUT. A resource is updated only when it has not been modified since the user last updated it. |
Max-Forwards | Limit the number of times the message can be forwarded by the proxy and gateway. |
Origin | Initiate a request for cross domain resource sharing (the request requires the server to add an access control allow origin header to the response, indicating the source allowed by access control). |
Pragma | Related to the specific implementation, these fields may be generated at any time in the request / response chain. |
Proxy-Authorization | Authentication information used to authenticate to the agent. |
Range | Indicates that a part of an entity is requested, and the byte offset starts with 0. |
Referer | Represents the previous page visited by the browser. It can be considered that the link to the previous page brings the browser to the current page. Referer is actually the word referer, but it was misspelled when RFC made the standard, and then referer was used wrongly. |
TE | Encoding method of the transmission expected to be accepted by the browser: the value in the transfer encoding of the response protocol header (you can also use "trackers" to represent the blocking method during data transmission) can be used to indicate that the browser wants to receive some additional fields after the last block with size 0. |
User-Agent | The identity string of the browser |
Upgrade | The server is required to upgrade to a higher version of the protocol. |
Via | Tell the server which agents sent the request. |
Warning | A general warning indicating that there may be an error in the entity content body. |
3.HTTP response
3.1.HTTP response status line
- Three parts: HTTP protocol version, status code and status description information
- The response code is used to represent various processing results and states of the server to the client request
- A three digit decimal number represents the status category in 5
Status code | effect |
---|---|
1xx | After receiving the request successfully, the client is required to continue to submit the next request to complete the whole processing process |
2xx | The entire request was successfully received and the entire process has been completed |
3xx | If the request is not completed, the client needs to further refine the request |
4xx | The client's request has an error |
5xx | Server error |
- 302: indicates that the requested resource temporarily responds to the request from a different URL, but the requester should continue to use the original location for future requests.
- For example, when requesting redirection, the temporary URL should be the resource pointed to by the Location header field of the response.
3.2.HTTP response header
- The first line is the response status line, and the rest is the response header, which contains a large amount of additional response information.
- It includes the service program name, the authentication method required by the requested resource, the last modification time of the resource requested by the client, the redirection address and other information
Response header | explain |
---|---|
Access-Control-Allow-Origin | Specify which sites can share source resources across domains |
Accept-Patch | Specifies the document patch format supported by the server |
Accept-Ranges | Content range supported by the server |
Age | The time, in seconds, that the response object exists in the proxy cache |
Allow | Effective actions for specific resources; |
Cache-Control | Notify all caching mechanisms from the server to the client, indicating whether they can cache this object and the cache validity time. The unit is seconds |
Connection | Options expected for this connection |
Content-Disposition | For the description of a known MIME type resource, the browser can determine the action to return the resource according to the response header, such as downloading or opening it. |
Content-Encoding | The encoding type used by the response resource. |
Content-Language | The language used to respond to the content |
Content-Length | The length of the response message body, expressed in octal bytes |
Content-Location | A candidate location for the returned data |
Content-MD5 | The binary MD5 hash value of the response content, encoded in Base64 |
Content-Range | If it is a response partial message, it indicates which part of the complete message it belongs to |
Content-Type | MIME type of the current content |
Date | The date and time when this message was sent (in the format of "HTTP date" defined in RFC 7231) |
ETag | An identifier, usually a message hash, for a particular version of a resource |
Expires | Specify a date / time beyond which the response will be considered expired |
Last-Modified | The last modification date of the requested object (in the format of "hypertext transfer protocol date" defined in RFC 7231) |
Link | Used to represent a type relationship with another resource, which is defined in RFC 5988 |
Location | Used when redirecting or when a new resource is created. |
P3P | P3P policy related settings |
Pragma | Related to the specific implementation, these response headers may have different effects at different times in the request / response chain |
Proxy-Authenticate | Require authentication information when accessing the agent. |
Public-Key-Pins | It is used to prevent intermediate attacks and declare the certificate hash value of transport layer security protocol in website authentication |
Refresh | Used for redirection, or when a new resource is created. By default, the redirection is refreshed after 5 seconds. |
Retry-After | If an entity is temporarily unavailable, this protocol header is used to tell the client to retry later. Its value can be a specific time period (in seconds) or a hypertext transfer protocol date. |
Server | Name of the server |
Set-Cookie | Set HTTP cookie |
Status | The response header field of the general gateway interface is used to describe the response status of the current HTTP connection. |
Trailer Trailer | The user describes the coding information of block coding in transmission |
Transfer-Encoding | An encoded form that represents the entity transmitted to the user. Including: chunked, compress, deflate, gzip and identity. |
Upgrade | The client is required to upgrade to another higher version of the protocol. |
Vary | Inform the downstream proxy server how to match the subsequent request protocol header to determine whether the cached response content can be used instead of requesting new content from the original server. |
Via | Tell the client of the proxy server how the current response is sent. |
Warning | General warning that there may be an error in the entity content body. |
WWW-Authenticate | Represents the authentication mode that should be used when requesting to obtain this entity. |
5, PHP interacts with Web page elements
1.PHP execution process
- 1.HTTP request: after the client browser enters the url address, it will send an HTTP request to the specified server. The request will be accompanied by some relevant information, such as message header.
- 2.Apache server processing: if the request is for static resources such as HTML, CSS, pictures and other files, Apache will directly obtain these files in the server directory. If a PHP file is requested, Apache will hand it over to the PHP module for processing, and the PHP module will return the processed results to Apache in HTML.
- 3. Return HTTP response data: the server sends the static resources obtained through Apache to the browser through HTTP response.
- 4. Parse by browser.
2.Web forms
2.1. Form composition (button, text box...)
2.2. Get form data
- When submitting, the submission method is usually specified through the method attribute.
- POST: global array $POST [] to get the value of form elements
- GET: global array $GET [] to GET the value of the form element
2.3. Form security verification
- Identify and process user input data
- strip_tags() function and htmlentities() function filter form data
- strip_tags() removes HTML and PHP tags from the string
- htmlentities() converts HTML and PHP tags in a string into characters and outputs them as text
2.4. Form data validation
- isset() function to detect whether the variable is set and non NULL. If the specified variable exists and is not NULL, it returns TRUE; otherwise, it returns FALSE
- empty() function, which detects whether the variable has a null value, including an empty string, 0, null or false. If yes, it returns TRUE
- is_ The numeric() function must be a number or a numeric string, otherwise FALSE is returned
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>I am your daddy</title> <style> .error {color: #FF0000;} </style> </head> <body> <?php // Define variables and set them to null by default $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "A name is required"; } else { $name = test_input($_POST["name"]); // Check if the name contains only letters and spaces if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and spaces are allowed"; } } if (empty($_POST["email"])) { $emailErr = "Mailbox is required"; } else { $email = test_input($_POST["email"]); // Check whether the mailbox is legal if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Illegal mailbox format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // Check whether the URL address is legal if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Illegal URL Address of"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP Form validation instance</h2> <p><span class="error">* Required fields.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> name: <input type="text" name="name" value="<?php echo $name;?>"> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php echo $emailErr;?></span> <br><br> website: <input type="text" name="website" value="<?php echo $website;?>"> <span class="error"><?php echo $websiteErr;?></span> <br><br> remarks: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> <br><br> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">male <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> <?php echo "<h2>What you entered is:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
3. Super global variable
$_POST
$_GET
$GLOBALS
$_SERVER
$_REQUEST
$_FILES
$_ENV
$_COOKIE
$_SESSION
- The value represented by the name attribute in the form is the value in POST and GET []
- $_ REQUEST saves array variables that pass data to PHP in various ways, which can be obtained$_ POST, $_ GET, $_ Data in COOKIE
After parsing, the new value overwrites the old value with the same name - $_ SERVER saves the page interaction information in the web SERVER, and stores the HTTP request header and web SERVER information
<?php echo $_SERVER['PHP_SELF'];//Output the relative path of the current PHP script file echo "<br>"; echo $_SERVER['SERVER_NAME'];//The name of the Web server echo "<br>"; echo $_SERVER['HTTP_HOST'];//Address of the Web server echo "<br>"; echo $_SERVER['HTTP_REFERER'];//URL address of the previous page linked to the current page echo "<br>"; echo $_SERVER['HTTP_USER_AGENT'];//Client operating system and browser information echo "<br>"; echo $_SERVER['SCRIPT_NAME'];//Output the relative path of the current script file ?>
- $GLOBALS contains a global combined array of all variables. The name of the variable is the key of the array.
<?php $x = 75; $y = 25; function addition() { //Get global variables x and y with $GLOBALS [] $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?>
6, PHP session Technology
- Cookie is a mechanism that stores data in the remote browser to track and identify users. Session is a session technology that stores information in the server
1.Cookie Technology
- Create cookie: setcookie($name, $value)
- Read COOKIE: Super global array$_ COOKIE ["key"]
- Delete Cookie: use setcookie() to set the value value to null
2.Session Technology
2.1. summary
- The web page is also a stateless connection program. The shopping interface always keeps the login state and will not be lost. It should be realized by Session
- When the Web server is running, it creates a Session file for each user's browser. When users access again, they can get information directly from their unique Session file.
- During a Session, the client Session ID is stored in COOKIE and the server Session ID is stored in the Session file.
2.2.Session operation
- Start session: session_start()
- Add data to SESSION: Super global array$_ SESSION ["key"] = value
- Reading data in session: $value =$_ Session [key]
- Delete all data:$_ SESSION=array() assigns an empty array
7, Regular expression
<?php /* 1.Square brackets [] Characters to match in the future are in parentheses. 2.Hyphen- Connection string [A-Za-z]Represents any string that matches the English case from A to z. 3.Dot character Represents a wildcard, representing all characters and numbers ".er"Represents all three character strings ending in ER. For example: ter per @ Er & er 4.Qualifier + *? {} "+": There must be at least one preceding character. Example: "9 +" indicates that the target string contains at least one 9 "*": There are more than one or zero preceding characters. Example: "Y *" indicates that the target string contains 0 or more than one y "?": The preceding character is one or zero. Example: "Y?" Indicates that the target string contains 0 or a y "{}": How many strings are there in front of it. For example: "a{3, 5}" means that the target string contains 3 or 5 a "a{3,}" means that the target string contains at least 3 a ".*": Represents a match to any string. 5.Line locator ^ and$ Determines where the matching string will appear. ^ : The destination string appears at the beginning. Example: ^ xiaoming means that xiaoming can only appear at the beginning of the target string $ : The destination string appears at the end. Example: 8895 $means that 8895 $can only appear at the end of the target string At the same time, use ^ $. For example: "^ [a-z] $" represents the target string, as long as it contains a single string from a to z 6.Exclude character [^] Indicates a logical "no". [^0-9]Example: indicates that the target string contains any string other than 0 to 9 7.Bracket character () Represents a substring. All operations on characters contained in the substring are carried out as a whole. Operators that divide regular expressions into different parts. 8.Select character| Means "or". For example: "com|cn|net" means that the target string contains com or CN or net 9.Escape character backslash\ If used alone, represents an escape character as a special character. If it represents \ itself, the escape character "\" is added before the character, that is "\ \" 10.Regular expression of authentication email email Regular expression of: ^ [a-za-z0-9.]+@ [A-Za-z0-9_]+\. [A-Za-z0-9_.]+$ ^[A-Za-z0-9_.]+ Indicates that there is at least one English case character, number, underscore, period or a combination of these characters at the beginning @ Indicates "@" [A-Za-z0-9_]+ Indicates that there is at least one English case character, number, underscore or a combination of these characters. \. Means "." such as ". com", Because it means "." Itself, escape with "\" [A-Za-z0-9_.]+$ Indicates that there is at least one English case character, number, period, or a combination of these characters up to the end of this string */ $email1 = "qijiyang2018@hotmail.com"; $email2 = "The email is qixiaoshuai_2018@hotmail.com"; $asmail = "The is qixiaoshuai_2018@hotmail"; if (preg_match('/^[A-Za-z0-9_.]+@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+$/',$email1)){ echo "This is an email."."<br/>"; } if (preg_match('/^[A-Za-z0-9_.]+@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+$/',$email2)){ echo "This is a new email."."<br/>"; }else{ echo "This is not an email."."<br/>"; } if (preg_match('/^[A-Za-z0-9_.]+@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+$/',$asmail)){ echo "This is an email."."<br/>"; }else{ echo "This is not an email."."<br/>"; } /* Operation results: This is an email. This is not an email. This is not an email. */
Form validation match
Verification account number starts with a letter, 5-16 bytes are allowed, and alphanumeric underscores are allowed: ^ [a-zA-Z][a-zA-Z0-9_]{4,15}$
Verification account number, which cannot be empty or blank, can only be English letters: ^ \ S + [A-Z, A-Z]$
Verify the account number. There must be no spaces or non numbers: ^ \ d+$
Verify the user password, which starts with a letter and is between 6-18 in length: ^ [a-zA-Z]\w{5,17}$
Verify whether it contains ^% & '; =$\ Equal characters: [^% & '; =? $\ X22]+
Matching Email address: \ w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Match Tencent QQ number: [1-9] [0-9] {4,}
Matching date, can only be 2004-10-22 format: ^ \ d{4}\-\d{1,2}-\d{1,2}$
Matching domestic telephone number: ^ \ D {3} - \ D {8} \ D {4} - \ D {7,8}$
Comment: the matching form is 010-12345678 or 0571-12345678 or 0831-1234567
Matching China Postal Code: ^ [1-9] \ d{5} (?)! (d)$
Matching ID card: \ D {14} (\ D {4}) (\ D {3} [XX]) | \ D {1})
Commentary: China's ID card is 15 or 18
Cannot be empty and more than twenty bytes: ^ [\ s|\S]{20,}$
Character matching
Matches a string of 26 English letters: ^ [A-Za-z]+$
Matches a string of 26 uppercase English letters: ^ [A-Z]+$
Matches a string of 26 lowercase letters: ^ [a-z]+$
Match a string consisting of numbers and 26 English letters: ^ [A-Za-z0-9]+$
Matches a string consisting of numbers, 26 English letters, or underscores: ^ \ w+$
Match blank lines: \ n [\ s|] * \ R
Match anything: [\ s\S]*
Match Chinese characters: [\ x80-\xff] + or [\ xa1-\xff]+
Only Chinese characters can be entered: ^ [\ x80-\xff],{0,}$
Matching double byte characters (including Chinese characters): [^ \ x00-\xff]
Match number
Only numbers can be entered: ^ [0-9]*$
Only n digits can be entered: ^ \ d{n}$
You can only enter at least n digits: ^ \ d{n,}$
Only m-n digits can be entered: ^ \ d{m,n}$
Matching positive integer: ^ [1-9]\d*$
Match negative integer: ^ - [1-9]\d*$
Matching integer: ^ -? [1-9]\d*$
Matching non negative integer (positive integer + 0): ^ [1-9]\d*|0$
Matching non positive integers (negative integers + 0): ^ - [1-9]\d*|0$
Matching positive floating point numbers: ^ [1-9] \ d * \ \d*|0\. \d*[1-9]\d*$
Matching negative floating point numbers: ^ - ([1-9]\d*\.\d*|0\.\d*[1-9]\d *)$
Matching floating point numbers: ^ -? ([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$
Matching non negative floating point number (positive floating point number + 0): ^ [1-9] \ d * \ \d*|0\. \d*[1-9]\d*|0?\. 0+|0$
Matching non positive floating point numbers (negative floating point numbers + 0): ^ (- ([1-9] \ d * \. \ d * |0 \. \ d * [1-9] \ d *) |0? \ 0+|0$
other
Regular expressions that match HTML tags (cannot match nested tags):
<(\S*?)[^>]*>.*?</\1>|<.*? />
Matching URL: [a-zA-z]+://[^\s]*
Matching IP address:
((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)
Match full domain name:
[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?