1, Basic knowledge
1.strpos() function
① Usage:
The strpos() function looks for the first occurrence of a string in another string. It is case sensitive and binary safe.
② Parameters:
strpos(string,find,start)
String is required. Specifies the string to search.
Find is required. Specifies the string to find.
Start is optional. Specify where to start the search.
③ Return value:
Returns the position of the first occurrence of a string in another string (the beginning position). If the string is not found, FALSE is returned. (the string position starts from 0, not 1.)
④ Correlation function:
stripos() - Finds the first occurrence of a string in another string (case insensitive) strripos() - Finds the last occurrence of a string in another string (case insensitive) strrpos() - Finds the last occurrence of a string in another string (case sensitive)
2.strpos() function
① Usage:
The ltrim() function removes white space characters or other predefined characters to the left of the string.
② Parameters:
ltrim(string,charlist)
String is required. Specifies the string to check.
charlist optional. Specifies which characters to remove from the string. If this parameter is omitted, all of the following characters are removed: "\ 0" - NULL; "\ t" - tab; "\ n" - line feed; "\ x0B" - vertical tab; "\ r" - enter; "" "- space
③ Return value:
Returns a modified string.
④ Correlation function:
rtrim() - Removes white space or other predefined characters to the right of the string trim() - Remove white space characters or other predefined characters on both sides of the string
3.$_SESSION
①$_SESSION
It is used to store information about user sessions or change the settings of user sessions. It stores information about a single user and is available to all pages in the application.
When you operate an application on a computer, open it, make some changes, and then close it, much like a Session. The computer knows who you are, and it knows when you open and close the application. However, because the HTTP address cannot be maintained, the Web server does not know who you are and what you have done.
PHP session solves this problem by storing user information (such as user name, purchased goods, etc.) on the server for subsequent use. However, session information is temporary and will be deleted after the user leaves the website. If you need to store information permanently, you can store the data in the database.
The working mechanism of Session is to create a unique id (UID) for each visitor and store variables based on this UID. The UID is stored in a cookie or transmitted through a URL.
Detailed explanation: https://blog.csdn.net/maomaoyu3211/article/details/84241425
②session_start() function
session_ The start () function registers the user's session with the server and assigns a UID to the user's session. So session_ The start() function must precede the < HTML > tag to store user information in the PHP session:
<?php session_start(); ?> <html> <body> </body> </html>
③ Storing Session variables
Storing and retrieving SESSION variables requires the use of PHP's super global variables$_ SESSION, in the following example, we create a simple page view counter.
<?php //Open session session_start(); //The isset() function detects whether the 'views' variable is set. //If the "views" variable is set, we accumulate the counter. //If "views" does not exist, create the "views" variable and set it to 1: if(isset($_SESSION['views'])) { $_SESSION['views']=$_SESSION['views']+1; }else{ $_SESSION['views']=1; } //Output page views echo "Views:". $_SESSION['views']; ?> <html> <body> </body> </html>
④ Destroy Session
If you want to delete some session data, you can use unset() or session_destroy() function.
The unset() function is used to release the specified session variable:
<?php session_start(); if(isset($_SESSION['views'])) { unset($_SESSION['views']); } ?>
session_destroy() will reset the session and you will lose all stored session data. Call session_ The destroy() function completely destroys the session:
<?php session_destroy(); ?>
4.fopen() function
① Usage:
The fopen() function opens a file or URL.
② Parameters:
fopen(filename,mode,include_path,context)
filename is required. Specify the file or URL to open.
mode is required. Specify the type of access you request to the file / stream. Possible values:
"r" (Open in read-only mode, pointing the file pointer to the file header) "r+" (Open the read-write mode and point the file pointer to the file header) "w" (Open in write mode, clear the contents of the file, and try to create the file if it does not exist) "w+" (Open in read-write mode, clear the contents of the file, and try to create the file if it does not exist) "a" (Open write mode, point the file pointer to the end of the file to write, and try to create the file if it does not exist) "a+" (Open the read-write mode, and save the file contents by writing the file pointer to the end of the file) "x" (Create a new file and open it in write mode. If the file already exists, return FALSE And an error) "x+" (Create a new file and open it in read-write mode. If the file already exists, return FALSE And an error)
include_path is optional. If you still want to include_ If you search for files in path (in php.ini), set this parameter to '1'.
context is optional. Specifies the environment for the file handle. context is a set of options that can modify the behavior of a flow.
③ Return value:
If fopen() fails, it returns FALSE with an error message. You can hide the error output by adding an '@' before the function name.
5.file_exists() function
① Usage:
file_ The exists() function checks whether a file or directory exists.
② Parameters:
file_exists(path)
Path is required. Specify the path to check.
③ Return value:
Returns true if the specified file or directory exists; otherwise, returns false.
<?php echo file_exists("test.txt"); ?> //Output: 1
6.fputs() function
① Usage:
The fputs() function writes to a file (which can be safely used for binary files) and is an alias for the fwrite() function.
② Parameters:
fputs(file,string,length)
File is required. Specifies the open file to write to.
String is required. Specifies the string to write to the file.
length is optional. Specifies the maximum number of bytes to write.
Write the contents of string to the file pointer file. If length is specified, writing will stop after writing length bytes or writing string, depending on the first case.
③ Return value:
Returns the number of characters written. If there is an error, it returns false.
<?php $file = fopen("test.txt","w"); echo fputs($file,"Hello World. Testing!"); fclose($file); ?> //Output: 21
7.$_SERVER
$_ SERVER is one of the predefined variables in PHP and can be used directly. It is an array containing information such as header, path and script locations.
$_ The elements in the SERVER array are created by the Web SERVER, but it is not guaranteed that each SERVER provides all elements. Some servers may ignore some or provide some elements that are not listed here.
$_ Some elements of the SERVER array are shown below.
$_SERVER['PHP_SELF'] The file name of the currently executing script, and document root of For example, at address http://c.biancheng.net/test.php/foo.bar is used in the script$_ SERVER['PHP_SELF '] will get / test php/foo. bar $_SERVER['SERVER_ADDR'] The server on which the script is currently running IP address $_SERVER['SERVER_NAME'] The hostname of the server on which the script is currently running. If the script runs on a virtual host, the name is determined by the value set by that virtual host $_SERVER['SERVER_PROTOCOL'] The name and version of the communication protocol when the page is requested. For example“ HTTP/1.0" $_SERVER['REQUEST_METHOD'] The request method used to access the page. For example“ GET""HEAD""POST""PUT" $_SERVER['DOCUMENT_ROOT'] The root directory of the document where the script is currently running. Defined in server profile $_SERVER['HTTP_ACCEPT_LANGUAGE'] Current request header Accept-Language: The contents of the item, if any. For example“ en" $_SERVER['REMOVE_ADDR'] Users browsing the current page IP Address, note and $_SERVER['SERVER_ADDR'] Differences between $_SERVER['SCRIPT_FILENAME'] The absolute path of the currently executing script $_SERVER['SCRIPT_NAME'] Contains the path of the current script $_SERVER['REQUEST_URI'] URI Used to specify the page to access. For example“ index.html" $_SERVER['PATH_INFO'] Contains the query statement provided by the client, followed by the real script name and( query string)Previous path information (if any). For example, the current script is through URL http://c.biancheng.net/php/path_info.php/some/stuff?foo=bar is accessed, then$_ SERVER['PATH_INFO '] will contain / some / stuff
Print out in browser$_ The code of SERVER array is as follows:
<?php print_r($_SERVER); ?>
The output of the browser is as follows:
Array ( [HTTP_HOST] => localhost [HTTP_CONNECTION] => keep-alive [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,*/*;q=0.8 [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 [HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36 [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.8 [HTTP_COOKIE] => PHPSESSID=e1bbc84e23bf85691e7c5a4ab07ee0de; pgv_pvi=4369311744; pgv_si=s1775918080; CNZZDATA155540=cnzz_eid%3D1811041545- 1463297631-%26ntime%3D1463303031 [PATH] => /usr/bin:/bin:/usr/sbin:/sbin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.4.16 (Unix) PHP/7.0.5 [SERVER_NAME] => localhost [SERVER_ADDR] => ::1 [SERVER_PORT] => 80 [REMOTE_ADDR] => ::1 [DOCUMENT_ROOT] => /Library/WebServer/Documents [REQUEST_SCHEME] => http [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => /Library/WebServer/Documents [SERVER_ADMIN] => you@example.com [SCRIPT_FILENAME] => /Library/WebServer/Documents/book/str.php [REMOTE_PORT] => 59377 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /book/str.php [SCRIPT_NAME] => /book/str.php [PHP_SELF] => /book/str.php [REQUEST_TIME_FLOAT] => 1463828978.149 [REQUEST_TIME] => 1463828978 [argv] => Array ( ) [argc] => 0 )
8.header() function
① Usage:
The header() function sends the original HTTP header to the client, so the header() function must be invoked before any actual output is sent.
② Parameters:
header(string,replace,http_response_code)
String is required. Specifies the header string to send.
Replace is optional. Indicates whether the header replaces the previous header or adds a second header. The default is true (replace) and false (multiple headers of the same type are allowed).
http_response_code optional. Force the HTTP response code to the specified value. (PHP 4 and later are available)
③ For example, users may set options to change the browser's default cache settings. By sending the header above, you can override any of these settings and force the browser not to cache!
<?php // Date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache"); header("Pragma: no-cache"); ?> <html> <body>
9. exit() function
① Usage:
The exit() function outputs a message and exits the current script, which is an alias for the die() function.
② Parameters:
exit(message)
Message is not required. Specifies the message or status number written before exiting the script. The status number is not written to the output.
③ Return value:
nothing
Generally used for error reporting:
<?php $site = "http://www.w3cschool.cc/"; fopen($site,"r") or exit("Unable to connect to $site"); ?>
9. imagecreate() function
① Usage:
imagecreate() returns an image identifier representing a blank image of a specified size.
② Parameters:
resource imagecreate ( int $width , int $height )
Width - the width of the image. Height - image height.
③ Return value:
The image resource identifier is returned on success and FALSE on error.
2, Project realization
1. Working principle
During each connection, the system will temporarily save the IP address of the client and monitor its connection frequency. If the connection frequency is abnormal, the system will treat it as a black IP address and send a verification request in the form of a picture.
2. Start interface
This script is used for preliminary preparation and starting anti_ddos script, including optimization of some front-end pages:
<?php //For the safe output function, if the input parameter value is empty, the string outputs "0". If the value is not empty, if there is 0, remove all the 0 on the left and output value, and if there is no 0, output value function safe_print($value){ $value .= ""; return strlen($value) > 1 && (strpos($value, "0") !== false) ? ltrim($value, "0") : (strlen($value) == 0 ? "0" : $value); } //Open the session and record the session if(!isset($_SESSION)){ session_start(); } if(isset($_SESSION['standby'])){ // to configure $_SESSION['standby'] = $_SESSION['standby']+1; $ad_ddos_query = 5;// The number of requests per second to detect DDOS attacks $ad_check_file = 'check.txt';// Write the current status to this file during monitoring $ad_all_file = 'all_ip.txt';// Temporary documents $ad_black_file = 'black_ip.txt';// This file records the zombie ip $ad_white_file = 'white_ip.txt';// This file records the ip address of the login guest $ad_temp_file = 'ad_temp_file.txt';// Record the ip address of the login visitor $ad_dir = 'anti_ddos/files';// Represents a directory with scripts $ad_num_query = 0;// From $check_ The current number of requests per second from the file $ad_sec_query = 0;// second from a file $check_file seconds $ad_end_defense = 0;// end while protecting the file $check_file termination $ad_sec = date("s");// Current seconds $ad_date = date("is");// current time $ad_defense_time = 100;// ddos # stop monitoring attack detection time (seconds) $config_status = ""; //Open or create a file in read-write mode. The file pointer points to the end of the file for writing (or reading). Return the information of success or failure of creation function Create_File($the_path){ $handle = fopen($the_path, 'a+') or die('Cannot create file: '.$the_path); return "Creating ".$the_path." .... done"; } // Before starting the detection, check whether all files exist (if there is no new file or an error is reported, write the file path to the $config_status string) $config_status .= (!file_exists("{$ad_dir}/{$ad_check_file}")) ? Create_File("{$ad_dir}/{$ad_check_file}") : "ERROR: Creating "."{$ad_dir}/{$ad_check_file}<br>"; $config_status .= (!file_exists("{$ad_dir}/{$ad_temp_file}")) ? Create_File("{$ad_dir}/{$ad_temp_file}") : "ERROR: Creating "."{$ad_dir}/{$ad_temp_file}<br>"; $config_status .= (!file_exists("{$ad_dir}/{$ad_black_file}")) ? Create_File("{$ad_dir}/{$ad_black_file}") : "ERROR: Creating "."{$ad_dir}/{$ad_black_file}<br>"; $config_status .= (!file_exists("{$ad_dir}/{$ad_white_file}")) ? Create_File("{$ad_dir}/{$ad_white_file}") : "ERROR: Creating "."{$ad_dir}/{$ad_white_file}<br>"; $config_status .= (!file_exists("{$ad_dir}/{$ad_all_file}")) ? Create_File("{$ad_dir}/{$ad_all_file}") : "ERROR: Creating "."{$ad_dir}/{$ad_all_file}<br>"; if(!file_exists ("{$ad_dir}/../anti_ddos.php")){ $config_status .= "anti_ddos.php does'nt exist!"; } if (!file_exists("{$ad_dir}/{$ad_check_file}") or !file_exists("{$ad_dir}/{$ad_temp_file}") or !file_exists("{$ad_dir}/{$ad_black_file}") or !file_exists("{$ad_dir}/{$ad_white_file}") or !file_exists("{$ad_dir}/{$ad_all_file}") or !file_exists ("{$ad_dir}/../anti_ddos.php")) { $config_status .= "Some files does'nt exist!"; die($config_status); } // Verify that the session is started require ("{$ad_dir}/{$ad_check_file}");//The file contains check Txt to write the current status to the file during monitoring if ($ad_end_defense and $ad_end_defense> $ad_date) {//The current time is within the attack protection time range require ("{$ad_dir}/../anti_ddos.php");//File contains anti_ddos.php } else { $ad_num_query = ($ad_sec == $ad_sec_query) ? $ad_num_query++ : '1 ';//Current requests per second $ad_file = fopen ("{$ad_dir}/{$ad_check_file}", "w")//Open write mode, clear the contents of the file, and try to create the file if it does not exist $ad_string = ($ad_num_query >= $ad_ddos_query) ? '<?php $ad_end_defense='.safe_print($ad_date + $ad_defense_time).'; ?>' : '<?php $ad_num_query='. safe_print($ad_num_query) .'; $ad_sec_query='. safe_print($ad_sec) .'; ?>'; fputs ($ad_file, $ad_string); fclose ($ad_file); } }else{ $_SESSION['standby'] = 1; $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_ SERVER[HTTP_HOST]$_SERVER[REQUEST_URI] "; / / server hostname localhost,REQUEST_URI specifies the page to visit (PHP file) header("refresh:8,".$actual_link); ?> <style type="text/css"> .loading {display: flex; flex-direction: column; align-items: center; } .loading__msg {font-family: Roboto; font-size: 16px; } .loading__dots {display: flex; flex-direction: row; width: 100%; justify-content: center; margin: 100px 0 30px 0; } .loading__dots__dot {background-color: #44BBA4; width: 20px; height: 20px; border-radius: 50%; margin: 0 5px; color: #587B7F; } .loading__dots__dot:nth-child(1) {animation: bounce 1s 1s infinite; } .loading__dots__dot:nth-child(2) {animation: bounce 1s 1.2s infinite; } .loading__dots__dot:nth-child(3) {animation: bounce 1s 1.4s infinite; } @keyframes bounce {0% {transform: translate(0, 0); } 50% {transform: translate(0, 15px); } 100% {transform: translate(0, 0); } } </style> <div class="loading" style="margin-top: 11%;"> <div class="loading__dots"> <div class="loading__dots__dot"></div> <div class="loading__dots__dot"></div> <div class="loading__dots__dot"></div> </div> <div class="loading__msg"> <center> <b style="font-size: 22px;"> <a target="_blank" style="color: black;">ANTI_DDOS</a> is checking.... </b> <br><br> Hey, don't worry, this is a simple security verification, You'll only see it once;<br> Your web page will be displayed soon! </center></div> </div> <?php exit(); } ?>
3. Verify ip script
This script is mainly used to obtain the user's ip, compare it with the black-and-white list, and add the white list and blacklist (from the temporary list):
<?php //Return the ip address in the blacklist or whitelist file for later comparison function getFromfile_source($type){ $ad_check_file = 'check.txt';// Write the current status to this file during monitoring $ad_all_file = 'all_ip.txt';// Temporary documents $ad_black_file = 'black_ip.txt';// This file records the zombie ip $ad_white_file = 'white_ip.txt';// This file records the ip address of the login guest $ad_temp_file = 'ad_temp_file.txt';// This file records the ip address of the login guest $ad_dir = 'anti_ddos/files';// Represents a directory with scripts //The file() function reads the entire file into an array, and the return value is this array return ($type == "black") ? explode(',', implode(',',file("{$ad_dir}/{$ad_black_file}"))) : ( ($type == "white") ? explode(',', implode(',',file("{$ad_dir}/{$ad_white_file}"))) : explode(',', implode(',',file("{$ad_dir}/{$ad_temp_file}"))) ) ;//The expand () function breaks the string into an array. //The implode() function returns a string composed of array elements } $ad_ip = ""; //If you are working on a local computer, you can add the following conditions //and getenv(" HTTP_CLIENT_IP ") != '127.0.0.1 '/ / user ip //and getenv(" HTTP_X_FORWARDED_FOR") != '127.0.0.1' /* Use in PHP$_ SERVER["REMOTE_ADDR"] to obtain the IP address of the client, but if the client uses a proxy server to access it, it will not be available Is the IP address of the proxy server, not the real client IP address. To obtain the real IP address of the client through the proxy server, you need to use $_SERVER["HTTP_X_FORWARDED_FOR"] To read. */ //Get the user's real ip address and use regular to check whether it is legal $ad_ip = (getenv("HTTP_CLIENT_IP") and preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/", getenv(" HTTP_CLIENT_IP "))) ? getenv("HTTP_CLIENT_IP") : ( (getenv("HTTP_X_FORWARDED_FOR") and preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/", getenv(" HTTP_X_FORWARDED_FOR "))) ? getenv("HTTP_X_FORWARDED_FOR") : getenv("REMOTE_ADDR")); //If the ip address is in the blacklist, exit the php file $ad_source = getFromfile_source('black'); if(in_array($ad_ip, $ad_source)) {die();} $ad_source = getFromfile_source('white'); if(!in_array($ad_ip, $ad_source)) {//If this ip is not on the white list $ad_source = getFromfile_source('temp'); //Gets the ip address in the temp file if(!in_array($ad_ip, $ad_source)) {//This ip is not in temp $_SESSION['nbre_essai']=3; //Three attempts $ad_file = fopen("{$ad_dir}/{$ad_temp_file}", "a+"); $ad_string = $ad_ip.','; fputs($ad_file, "$ad_string");//Put the new IP into temp (IP first access) fclose($ad_file); //??? $array_for_nom = array('maN','bZ','E','S','i','P','u','1','4','Ds','Er','FtGy','A','d','98','z1sW'); $nom_form = $array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)]; $_SESSION['variable_du_form'] = str_shuffle($nom_form).$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)]; include('Verify_your_identity.php');//Contains the authentication front-end file and the user's input interface die(); }elseif(isset($_POST[$_SESSION['variable_du_form']]) AND $_SESSION['nbre_essai']>0){//This ip is in temp and has been tried to be placed in temp before and still has the opportunity to try (second access). If it passes the verification, it will be placed in the white list $secure = isset($_POST['valCAPTCHA']) ? ($_POST['valCAPTCHA']) : '';//Get the verification code entered by the user if ($secure == $_SESSION['securecode']){//The user input (V_y_i) is equal to the system security code and is added to the white list $ad_file = fopen("{$ad_dir}/{$ad_white_file}", "a+"); $ad_string = $ad_ip. ','; fputs($ad_file, "$ad_string"); fclose($ad_file); unset($_SESSION['securecode']); unset($_SESSION['nbre_essai']); }else{//Validation, last time $_SESSION['nbre_essai']--; $array_for_nom = array('maN','bZ','E','S','i','P','u','1','4','Ds','Er','FtGy','A','d','98','z1sW'); $nom_form = $array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)]; $_SESSION['variable_du_form'] = str_shuffle($nom_form).$array_for_nom[rand(0,15)].$array_for_nom[rand(0,15)]; include('Verify_your_identity_LASTCHANCE.php');//Include authentication files die(); } }else {//Three incorrect verification codes are added to the blacklist $ad_file = fopen("{$ad_dir}/{$ad_black_file}", "a+"); $ad_string = $ad_ip.','; fputs($ad_file, "$ad_string"); fclose($ad_file); die(); } } ?>
4. Provide verification code
This code randomly generates garbled code in a fixed sequence and displays a picture verification code at the front end:
<?php if(!isset($_SESSION)){ session_start(); } $largeur = 120; $hauteur = 40; $longueur = 6; $liste = '134679ACEFGHIJLMNPRTUVWXY@%$&';//Verification code library $code = ''; $counter = 0; //Return an image identifier to hide the error message (blank at this time) $image = @imagecreate($largeur, $hauteur) or die('Impossible d\'initializer GD'); //Draw a line on the image to prevent machine identification (verification code) for( $i=0; $i<10; $i++ ){ imageline($image,// The imageline() function draws a line segment between two given points (two lines are drawn here) mt_rand(0,$largeur), mt_rand(0,$hauteur), mt_rand(0,$largeur), mt_rand(0,$hauteur), imagecolorallocate($image, mt_rand(200,255), mt_rand(200,255), mt_rand(200,255)//Segment color. They are the red, green and blue components of the desired color. These parameters are integers from 0 to 255 ) ); } for( $i=0, $x=0; $i<$longueur; $i++ ) { $charactere = substr($liste, rand(0, strlen($liste)-1), 1); $x += 10 + mt_rand(0,10); //imagechar draws the first character of the string in the image specified by image imagechar($image, mt_rand(3,4), $x, mt_rand(4,20), $charactere, imagecolorallocate($image, mt_rand(0,155), mt_rand(0,155), mt_rand(0,155))); $code .= ($charactere); } header('Content-Type: image/jpeg'); imagejpeg($image); imagedestroy($image); $_SESSION['securecode'] = $code; ?>
3, Summary
1. Defense effect
This defense strategy is simple to implement and can be used by attackers to forge a large number of connection requests to attack the server by using some zombies. In this case, if an attack ip fails to pass the verification code detection, it will not be able to access the website page.
2. Existing problems
This defense strategy aims at a single type of attack and cannot deal with multiple attacks. In addition, its efficiency needs to be improved. For example, if a large number of random IPS initiate access to the website at the same time, verifying each ip will also consume a lot of resources.