This article summarizes various common problems in PHP learning, with more than two thousand lines of code, all of which are very practical skills. Share it with everyone for your reference. The details are as follows:
//Syntax error (syntax error) During the syntax analysis phase, the source code has not been executed, so there will be no output. /* [Naming rules] */ It is recommended that constant names of class constants be in all uppercase letters, and words should be separated by underscores // MIN_WIDTH It is recommended that variable names be separated by underscores // $var_name It is recommended to use camel case naming method for function names // varName It is recommended to use all uppercase letters for delimiters // <<<DING, <<<'DING' It is recommended that the file name be all lowercase, with underscores and numbers // func_name.php It is recommended that private attribute names and method names be underlined // private $_name _func It is recommended to add I_ // interface I_Name to the interface name. /* Language structure */ array(), echo(), empty(), eval(), exit(), isset(), list(), print(), unset() echo, print can omit the parentheses. /* Predefined constants */ PATH_SEPARATOR //Path separator (semicolon for Windows, colon for Unix-like) DIRECTORY_SEPARATOR //Directory separator PHP_EOL //The newline character of the current system PHP_VERSION //PHP version number PHP_OS //PHP service operating system PHP_SAPI //Used to determine whether to use the command line or the browser to execute, if PHP_SAPI=='cli' means it is executed under the command line PHP_INT_MAX INT maximum value, the value is 2147483647 on 32-bit platform PHP_INT_SIZE INT word length, the value is 4 (4 bytes) on 32-bit platform M_PI //Pi value M_E //natural number //PHP running environment detection function php_sapi_name() //Returns a lowercase string of PHP and WEB server interface type The return value of this function is consistent with the constant PHP_SAPI! Interface type: SAPI (the Server API, SAPI) Possible values: aolserver, apache, apache2filter, apache2handler, caudium, cgi, cgi-fcgi, cli, continuity, embed, isapi, litespeed milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, webjames /* Capitalization issue */ - Class name, method name, attribute name, function name: case-insensitive - Variable names, constant names, element subscripts: case sensitive /* Variable identifier */ Variable variable $i = 3; $k = 'i'; echo $$k; //Output 3 Variable function function func() {echo 'hello!';} $i = 'func'; $i(); //Output hello Variable subscript $i = '1234'; $k = 3; echo $i[$k]; //output 4 Variable class name class CLS{public $k = 'hello';} $i = 'CLS'; $j = new $i; echo $j->k; Variable attributes class CLS{public $k = 'hello';} $i = 'k'; $j = new CLS; echo $j->$i; Variable method class CLS{public function k(){echo 'hello';}} $i='k'; $j=new CLS; $j->$i(); /* Variable variables */ * Used for business logic judgment to obtain certain specific information $var_name = "class_name"; $$var_name = "PHP0913"; // $class_name = "PHP0913";$class_name has been stored in memory var_dump($class_name); // var_dump($$var_name); /* variable function */ get_defined_vars //Returns an array composed of all defined variables (including environment variables, server variables and user-defined variables) /* unset() */ * unset() only deletes the current variable name and reference, its value is not deleted * In reference transfer, if a variable and its reference are deleted, other variables and references will exist, and the value will still exist. echo "<br />"; $v3 = 'value'; $v4 = &$v3; unset($v4); var_dump($v3, $v4); /* The maximum validity period of the variable */ * The execution cycle of the current script. When the script execution ends, the variable disappears. /* Predefined variables/super global variables */ $GLOBALS $_COOKIE $_ENV $_FILES $_GET $_POST $_REQUEST $_SERVER $_SESSION /* Constant definition */ define(constant name, constant value, [case-sensitive parameter]) //true means insensitive/false means case-sensitive const constant name = constant value // new, recommended Constant names can use special characters constant($name) // Get the constant name //Example: echo constant('-_-'); /* Constant related functions */ defined get_defined_constants /* Predefined constants */ __FILE__ Absolute path to the file __LINE__ The current line number in the file __DIR__ The directory where the file is located __FUNCTION__ function name __CLASS__ The name of the class __METHOD__ method name of the class __NAMESPACE__ The name of the current namespace /* Integer type */ The integer occupies 4 bytes, with a total of 4*8=32 bits. The maximum value is 2147483647 and the minimum value is -2147483648. The absolute value of the minimum value is 1 greater than the maximum value. The highest value represents positive and negative, 1 represents negative, 0 represents positive /* Base conversion function */ Only decimal and other bases can be converted, and there are only six types. When converting, the parameter should be a string (that is, it cannot contain octal "0" or hexadecimal "0x") dec bin oct hex hexdec() converts hexadecimal to decimal. You can also write hex2dec() dechex() converts decimal to hexadecimal. You can also write dec2hex() bindec() converts binary to decimal. You can also write bin2dec() decbin() converts decimal to binary. You can also write dex2bin() octdec() converts octal to decimal. You can also write oct2dec() decoct() converts decimal to octal. You can also write dec2oct() /* Floating point number */ Floating point numbers cannot be compared! ! ! Almost all decimals, when saved, are approximate rather than exact! Maximum value: +/- 1.8E308 The longest decimal place that PHP can save: 14 digits /* single quoted string */ In single-quoted strings, only backslashes and single quotes can be escaped. /* double quoted string */ Parse the string only once! ! ! eval executes a string as PHP code Curly braces wrap variables to determine variable name boundaries.For example: "aaa{$bbb}ccc" ASCII code can be converted into characters in double quotes "x61" -> a // There is no need for 0 in the string, only 0x is leading in the integer type "x49x54x43x41x53x54" -> ITCAST Convert ASCII to character function chr() Convert characters to ASCII function ord() #Double quote escape list n new line r Enter t horizontal tab character \ backslash $ dollar mark v vertical tab e Escape f page change "double quotes" [0-7]{1,3} matches the regular expression sequence and is a character expressed in octal notation. x[0-9A-Fa-f]{1,2} matches this regular expression sequence and is a character expressed in hexadecimal form /* delimiter */ herodoc - functions the same as double quotes and can be parsed $str = <<<AAA String content AAA; nowdoc - functions the same as single quotes, cannot be parsed Only have single quotes at the beginning $str = <<<'AAA' String content AAA; /* Usage of strings */ You can use a string as a collection of characters, each of which can be accessed independently. Only applicable to single-byte characters (letters, numbers, half-width punctuation marks), not available for Chinese, etc. $str = "abcd"; echo $str[3]; // d echo $str{0}; // a /* [Type operation function] */ //Get/set type gettype($var) //Get the data type of the variable settype($var, $type) //Set the data type of the variable //type judgment is_int is_float is_null is_string is_resource is_array is_bool is_object is_numeric detects whether a variable is a number or a numeric string //Convert to the specified data type boolval floatval intval strval //Force type (int) (float) (string) (bool) (array) (object) (unset) //Convert to NULL (binary) conversion and b prefix conversion //Convert to binary var_dump prints information about variables. Displays structural information about one or more expressions, including the expression's type and value. Arrays will recursively expand values, showing their structure through indentation. var_export($var [,bool $return]) //Output or return the string representation of a variable $return: If true, the result after variable execution is returned print_r prints human-readable information about variables empty checks whether a variable is empty isset detects whether a variable exists /* [Process Control] */ //Alternative syntax for if statement if (conditional judgment): statement block; elseif (conditional judgment): statement block; else : statement block; endif; //Alternative syntax for flow control Commonly used when embedding HTML Replace { with : , } with endif; etc. endif endwhile endfor endforeach endswitch /* 【switch】 */ switch (condition) { case status value 1: statement block; [break;] case status value 2: statement block; [break;] case status value 3: case status value 4: statement block; [break;] default: statement block; [break;] } switch is a state branch, a special loop Calculate the status value first, and then compare it with the judgment number. break exit process /* [for loop] */ for (conditional initialization expression; conditional judgment expression; conditional change expression) { Loop body } Assuming that the loop body is executed N times, then The conditional initialization expression is executed once The conditional judgment expression is executed N+1 times The conditional change expression is executed N times Notice: 1. The loop variable can continue to be used after the for statement ends, and its value is the value of the first failure. 2. Loop variables can be used within the for loop body 3. Any conditional expression can be omitted, but the semicolon cannot be omitted. a. When the conditional initialization expression is omitted, the loop variable is assigned null, and when it is judged with the condition, Perform type conversion and then compare. Initialization can also be done outside the for statement. b. When the conditional judgment expression is omitted, it means that the loop is true and enters an infinite loop. c. When the conditional change expression is omitted, it can be completed within the loop body 4. Each expression can be composed of multiple statements, and each statement is separated by commas. If the conditional judgment expression consists of multiple statements, they will all be executed, but only the last statement will be used as the judgment condition. 5. for can only traverse numeric index subscript arrays Array length function: count() 6. Statements that can be initialized should be placed within conditional initialization expressions, which can save a lot of execution times. /* 【goto】5.3+ version */ Used to jump to a specified location in the program The target location can be marked with the target name followed by a colon. Goto in PHP has certain restrictions and can only jump within the same file and scope. That is to say, you cannot jump out of a function or class method, nor can you jump into another function. You also cannot jump into any loops or switch structures. Common usage is to break out of a loop or switch, which can replace multiple levels of break. You can jump out of the loop (switch), but you cannot jump in from outside. Functions or class methods cannot be used either outward or inward.goto a; echo 'Foo'; a: echo 'Bar'; /* [File loading] */ require/include/require_once/include_once File loading only loads and executes the code in the target file, regardless of the type of file being loaded. File loading belongs to the execution phase. When statements such as require are executed, the code of the file is loaded. Compile and execute, then return to the require statement position and continue executing the following statements 【Notice】 At the beginning of loading, exit PHP mode first; Then load the target file code and execute the code; When finished, enter PHP mode again. require: The processing fails, an E_COMPILE_ERROR error is generated, and the script is terminated. include: The processing fails, an E_WARNING error is generated, and the script continues execution. #It is not recommended to use require_once/include_once /* [relative path] */ Which script is currently requested by the browser, the current position belongs to which script. ./file and file both represent the file file in the current directory file situation (when nested loading files): If the file is not found in the current directory, continue searching in the directory where the code file is located. If the file is found in the current directory, it will not be searched in the directory where the code file is located or loaded. __DIR__ The directory where the script file is located __FILE__ script file path include_path loads the file search directory set_include_path() sets include_path, there can be multiple, using string as parameter The path set by this function is only valid for the current file. This setting is only effective for finding file paths that are not directly written. Setting a new include_path will overwrite the original one get_include_path() Gets the current include_path setting item, no parameters Path separator, semicolon under Windows, colon under Linux Use the predefined constant PATH_SEPARATOR to get the current separator If you write the file name directly: 1. Set by include_path 2. Current directory 3. Directory of the file where the code is located If the file name is preceded by a path, it will be searched directly based on the path, and include_path will be ignored directly. /* 【return】 */ Return is combined with require to return the contents of the file. Return is written in the loaded file. return can terminate the execution of the script as a normal script statement return can return the corresponding value of the function /* [Terminate and delay script execution] */ die / exit terminate return is to terminate the execution of the script. die and exit immediately terminate script execution die("So far"); The string within this function can be output sleep() delay (unit: seconds) The default delay is up to 30 seconds, and the PHP configuration can modify max_execution_time Example: sleep(12); usleep() delays execution by the specified number of microseconds time_sleep_until causes the script to sleep until the specified time /* [Function] */ 1. The function is declared at compile time, so it must be defined first and then called. There is no sequential relationship between definition and call! 2. Files are just carriers of code, and programs are executed in memory! 3. If the function definition is in the file that needs to be loaded, the file needs to be loaded first, otherwise the call will error! 4. The definition of the function can appear in other code segments, and the function will not be executed during the compilation phase. It will only be defined when it is executed! Only when defined independently will it be compiled in memory! If it appears in the body of other functions, it will be defined and take effect only when the outer function is called! 5. Function names are not case sensitive 6. Duplicate names are not allowed, including system functions. 7. [Variable function] The function name can be replaced by other variables $func_name = "sayHello"; $func_name(); //Call the sayHello() function at this time Note: Variables can only be used when calling, not when defining! 8. Variables can be used as function names to call functions, and array element values can also be used! 9. Formal parameter parameter, actual parameter argument You can pass null for the parameter, indicating that the formal parameter does not want to pass a value Formal parameters can be passed by value or by reference.To pass parameters by reference, you should add the & symbol before the formal parameters when defining the function. At this time, the actual parameters of the calling function must be variables. How do you choose which delivery method to use? a. Is it necessary to ensure the integrity of the original data? b. Is it necessary to increase efficiency? c. Passing big data references can save memory 10. Parameter default values a. The default value of a function parameter must be a determined value, not a variable! You can use a constant as a parameter default value as long as the constant is defined before the call b. A function can have multiple default values. It is recommended that parameters with default values be placed at the end of the parameter list. In this way, when calling a function, parameters with default values will not be assigned, otherwise an error will occur. c. Default parameters can be non-scalar types, such as arrays and null d. Any default parameters must be placed to the right of any non-default parameters 11. Number of parameters a. The number of formal parameters is more than the number of real parameters. Report warning level errors, replaced by NULL b. More actual parameters than formal parameters Do not report errors and assign values to formal parameters in sequence. c. Uncertain number of parameters 1) Not a single formal parameter is defined, there are always more actual parameters than formal parameters. 2) [Variable number of parameters] func_get_args() gets the values of all the actual parameters when the current function is called, and returns an array composed of all the actual parameter values. func_get_arg() gets the value of an actual parameter, identified by the index value, e.g: func_get_arg(0) func_num_args() gets the number of all arguments 12. 【return】return value a. The function has only one return value. You can get similar results by returning an array, but you can have multiple return statements. b. The return statement immediately terminates the function and returns control to the line of code that called the function. c. Can return any type including arrays and objects d. The return of a function can also be divided into value transfer and reference transfer (only a variable can be returned) 1) The default is value passing method 2) Reference transfer method: - When defining a function, adding & before the function name indicates that the function can return a reference - When calling a function, add & before the function name to obtain the reference returned by the function. At this time, modifying the return value outside the function will modify the value of the return variable within the function. - If the function needs to return a reference, it needs to return a variable. - To return a reference from a function, you must use the reference operator & both when declaring the function and assigning the return value to a variable. function &returns_reference(){return $someref;} $newref =& returns_reference(); 3) The role of returning references /* [Variable scope] */ a. Global variables and local variables 1) There is no overlap between scopes, that is, variables in different scopes are not accessible to each other. 2) Global scope - the area outside the function 3) Local scope - the area within a function, each function is an independent scope b. Super global variables can be used both globally and locally. Only those that come with the system can be used. They are all array variables. $GLOBALS $_COOKIE $_ENV $_FILES $_GET $_POST $_REQUEST $_SERVER $_SESSION c. $GLOBALS 1) There cannot be super-global variables, but there can be super-global data! 2) Put the required data into the array of super global variables, but use $GLOBALS uniformly 3) $GLOBALS feature - Each global variable corresponds to an element in $GLOBALS! Whenever a global is added, an element with the same name is automatically added to $GLOBALS! In the same way, whenever an element is added, a global variable will also be added, usually within a function. - Any modifications made will also be mapped to another one, including updates and deletions To access global variables within a function, just use $GLOBALS - Global variables that have appeared can be obtained through the $GLOBALS array 4) In the PHP life cycle, the so-called global variables defined outside the function body cannot be directly obtained inside the function. 4) global keyword (not recommended) Declare a local variable as a 'reference' to a global variable of the same name! Equivalent to constant reference passing global $var; // $var = &$GLOBALS['var']; Unlike $GLOBALS! ! ! global creates an alias variable in the function that points to a variable external to the function, rather than a real variable external to the function. $GLOBALS is indeed called an external variable, and will always be consistent inside and outside the function. The role of global is to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require. d. 1) Scope only applies to variables, not to constants 2) The scope of variables defined in the loaded file depends on the location where it is loaded. If it is loaded outside the function, it is global, and if it is loaded inside the function, it is local! /* [Variable life cycle] */ 1. When the script ends, the global variables disappear 2. When the function is executed, the local variables disappear 3. Static variables static keyword Static variables only exist in the local function scope, but their values are not lost when program execution leaves this scope. Static variables are initialized only once, other local variables are reassigned each time they are called. The life cycle of static variables declared statically will continue forever./* [Iteration and recursion] */ Iteration is more efficient than recursion! Iteration is an idea (algorithm), and its structure and use are like loops! Recursion is an idea (algorithm) that splits large problems into small problems and solves small problems one by one to solve the big problem The solutions to big and small problems are required to be consistent! The structure and syntax of recursion are reflected in the function in the figure. The function body calls the function itself! Recursive exit: When the problem can be solved, there is no need to recurse /* [Anonymous function/closure function] */ Anonymous functions, also called closures, allow the temporary creation of a function without a specified name. 1. When defining an anonymous function, there is no need to add a function name. 2. PHP manages anonymous functions as an object. 3. Anonymous functions should be stored in variables. 4. Anonymous functions are implemented through the Closure class 5. You can use functions as parameters and return values of functions 6. When declaring a function, you can use use($param) to pass variables outside the function into the function, and use variable references to implement closures. 7. You can use variables to reference functions $func = function ($e) { echo $e; }; //At the end, it needs to end with a semicolon, just like variable assignment var_dump($func); //Use anonymous function $func('ITCAST'); //Function call This is not a variadic function, but an object. Closure closure class //use syntax Anonymous functions favor the concept of values, which may appear anywhere. use can make an anonymous function use variables in its outer scope. Not global! The difference between use and global: use uses variables from its outer scope function out() { $v = "in out"; $func = function () use (& $v) { var_dump($v); } } Use is similar to the automatic passing of parameters, and also supports the passing of values and references. //effect Often called as a 'temporary function' (a function that is only called somewhere) For example: There is an array_map() function in PHP. Its function is to call a certain function for each element in a function. Operation result (array) = array_map (operation function, operation array); $result_arr = array_map(function ($v) {return $v3}, $arr); //closure usage example function closureCreater() { $x = 1; return function($fun = null) use(&$x) {//Pass value by reference echo "<br />" . $x++; $fun and $fun(); }; } $x = "hello world"; $test = closureCreater(); $test(); $test(function(){ echo "closure test one"; }); $test(function(){ echo "closure test two"; }); $test(function() use($x){ echo "<br />".$x;}); //Save the function as an array element $x = 'outer param.'; $arr = array(); $arr[] = function($str)use($x){ return $str.$x; }; echo $arr[0]('test fun in arr,'); /* [Array] */ Associative array: keys and values are related, and the keys represent the logical meaning of the values. Index array: The key and value are not related, and the key represents the position of the value. Usually subscripts start from 0 and are incremented by elements count($var [,$mode]) //Count the number of array elements $mode is optional. When set to 1 or true, recursive statistics will be performed. $var is not an array, returns 1; $var is not initialized or equal to null or an empty array, returns 0 //Use of key names Integer numeric keys do not need to be quoted ($arr[1]) String numeric keys do not need to be quoted ($arr = array('1'=>'abc'); $arr[1]) Associative array, string keys need to be quoted ($arr = array('a'=>'aaa'); $arr['a']) Associative array, parse variables in double quotes, no quotes required ($arr = array('a'=>'aaa'); "$arr[a]") /* [Pointer] */ current/pos returns the value of the array element currently pointed to by the internal pointer without moving the pointer. key returns the key name of the current cell in the array without moving the pointer next moves the internal pointer in the array forward one position and returns the value of the current cell after the move. Move first, then get value. prev rewinds the internal pointer of the array by one bit and returns the value of the current unit after the move. First move it and then take the value. end points the internal pointer of the array to the last element and returns the value of the last element reset points the internal pointer of the array to the first element and returns the value of the first array element each returns the current key/value pair in the array and moves the array pointer forward one step. What is returned is an array of length 4 consisting of keys and values. The subscript 0 and key represent the key, and the subscript 1 and value represent the value. After executing each(), the array pointer will stay at the next cell in the array Or stay at the last cell when the end of the array is reached. If you want to use each to iterate through the array again, you must use reset(). 1. The above pointer operation functions, except key(), return false if the pointer is moved out of the array. When key() is moved out, it returns null. 2. If the pointer is illegal, next/prev operations cannot be performed, but reset/end operations can be performed. 3. current/next/prev will also return false if it encounters an empty unit (0 or ""). But each will not! list assigns the values in the array to some variables. list() is a language structure, not a function Can only be used with numerically indexed arrays and assumes numerical indexing starts at 0 /* Can be used to exchange the values of multiple variables */ list($a, $b) = array($b, $a); Example: list($drink, , $power) = array('coffee', 'brown', 'caffeine'); 1. When the array is copied, its pointer position will also be copied. Special case: If the array pointer is illegal, the copied array pointer will be reset, but the original array pointer will remain unchanged.[Pointer problem] Whoever writes first will open up a new value space. It has nothing to do with who the variable (array variable) value is passed to. The array function current() is defined as a write operation, so problems will occur. What foreach traverses is a copy of the array, and when it is written, a new value space will be opened. That is, the pointer problem only occurs when the foreach loop body writes to the original array. If the pointer is illegal when opening new space, the pointer will be initialized. 2. If there is a problem with the pointer position, initializing it with reset() can solve the problem. /* [Traverse the array] */ * Find the element first, then get the key and value foreach foreach (array_expression as [$key =>] & $value) When foreach starts executing, the pointer inside the array will automatically point to the first element. After obtaining the element information, move the pointer and then execute the loop body 1. The loop structure of foreach itself, break and continue are suitable for foreach 2. foreach supports alternative syntax for loops. 3. $value is a variable that stores the element value. Modifying it will not change the element value of the array. 4. $value supports reference copy of element value, just add & before $value 5. $key does not support passing by reference 6. What foreach traverses is a copy of the original array, and the operation on the array in the loop body is to operate on the original array. That is, the operation of the loop body on the array takes effect on the original array, but does not take effect on the traversal. First copy an array for traversal while...list...each while (list($key, $val) = mysql_fetch_row($result)) = each($arr) { echo "$key => $valn"; } /* [Array function] */ //statistical calculation count Counts the number of cells in an array or the number of attributes in an object array_count_values counts the number of occurrences of all values in the array array_product calculates the product of all values in an array array_sum calculates the sum of all values in an array range creates an array containing cells in the specified range //Get the contents of the array array_chunk splits an array into multiple array array_chunk(array $input, int $size[, bool $preserve_keys]) array_filter uses callback function to filter cells in array array_slice takes a segment from an array array array_slice($arr, $offset [,$len [,$preserve_keys]]) array_keys returns all key names in the array array array_keys(array $input[, mixed $search_value[, bool $strict]] ) If the optional parameter search_value is specified, only the key name of the value is returned. Otherwise, all keys in the input array will be returned. array_values returns all values in the array, numerically indexed array_merge merges one or more arrays The values in one array are appended to the previous array. If the input array has the same string key name, the value after the key name will overwrite the previous value. If the array contains numeric key names, subsequent values will not overwrite the original values, but will be appended to them. If only an array is given and the array is numerically indexed, the key names are re-indexed consecutively. array_merge_recursive merges one or more arrays recursively //search in_array checks whether a value exists in an array bool in_array(mixed $needle, array $haystack[, bool $strict]) array_key_exists checks whether the given key name or index exists in the array isset() will not return TRUE for NULL values in the array, but array_key_exists() will array_search searches the array for a given value and returns the corresponding key if successful array_combine creates an array, using the values of one array as its keys and the values of another array as its values. Returns FALSE if the number of elements in the two arrays is different or if the arrays are empty. array_rand randomly takes one or more units from the array and returns the key name or an array composed of key names. The subscripts are naturally sorted. array_fill fills an array with the given values array_fill($start, $num, $value) array_flip swaps keys and values in an array array_pad pads an array to the specified length with values array_reverse returns an array with the cells in reverse order array_unique removes duplicate values from an array array_splice removes part of an array and replaces it with other values implode concatenates the array element values into a string using a certain string explode($delimiter, $str [,$limit]) //Use one string to split another string $delimiter cannot be the empty string "" array_map applies the callback function to the unit of the given array. It can only process element values and can process multiple arrays. If the callback parameter is set to null, multiple arrays are merged into a multi-dimensional array. array_walk applies user functions to each member in the array. It can only process one array. Both keys and values can be processed. It has the same function as foreach. bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) //Stack: last in first out Pushing and popping the stack will reallocate the index subscript array_push pushes one or more elements to the end of the array (push) array_pop pops the last unit of the array (pops the stack). After using this function, the array pointer will be reset (reset()). //queue: first in first out Queue functions reassign index subscripts array_unshift inserts one or more cells at the beginning of the array array_shift moves the element at the beginning of the array out of the array. Using this function will reset (reset()) the array pointer.//sort function sort Sort an array rsort sorts an array in reverse order asort sorts an array and maintains index relationships arsort sorts an array in reverse order and maintains index relationships ksort sorts an array by key krsort sorts the array in reverse order by key name usort sorts the values in an array using a user-defined comparison function uksort sorts the keys in an array using a user-defined comparison function uasort uses a user-defined comparison function to sort values in an array and maintain index association natsort sorts an array using the "natural sorting" algorithm natcasesort uses the "natural sort" algorithm to sort an array in a case-insensitive manner array_multisort Sort multiple arrays or multidimensional arrays shuffle shuffle the array Pass parameters by reference and return a bool value. Reassign the index key name and delete the original key name //Difference set array_udiff_assoc calculates the difference set of arrays with index checking, and uses callback functions to compare data array_udiff_uassoc calculates the difference set of the array with index checking, and uses the callback function to compare the data and index array_udiff uses callback functions to compare data to calculate the difference of arrays array_diff_assoc calculates the difference of an array with index checking array_diff_key uses key name comparison to calculate the difference of an array array_diff_uassoc computes the difference of an array using a user-supplied callback function that performs index checking array_diff_ukey uses the callback function to compare key names and calculate the difference set of the array array_diff calculates the difference of an array //Intersection array_intersect_assoc calculates the intersection of arrays with index checking array_intersect_key calculates the intersection of arrays using key name comparison array_intersect_uassoc calculates the intersection of arrays with index checking, and uses the callback function to compare the indexes array_intersect_ukey uses callback functions to compare key names to calculate the intersection of arrays array_intersect calculates the intersection of arrays array_key_exists uses a callback function to compare key names to calculate the intersection of arrays array_uintersect_assoc calculates the intersection of arrays with index checking and compares data with callback functions array_uintersect calculates the intersection of arrays and uses callback functions to compare data extract($arr [,$type [,$prefix]]) imports variables from the array into the current symbol table (accepts the combined array $arr as a parameter and uses the key name as the variable name and the value as the variable value) compact($var [,...]) creates an array including variable names and their values (the variable names become the keys and the contents of the variables become the values of the keys) /* [pseudotype] */ mixed indicates that a parameter can accept multiple (but not necessarily all) different types. number indicates that a parameter can be integer or float. callback callback function void void as a return type means that the return value of the function is useless. void as parameter list means the function does not accept any parameters. /* [Database operation] */ #Connection authentication mysql_connect connects and authenticates the database #Send SQL statements and receive execution results mysql_query sends SQL statements Only a resource identifier is returned if the select, show, explain, and describe statements are successfully executed, and true is returned if other statements are successfully executed. Returns false if execution fails. #Processing results mysql_fetch_assoc fetches a row from the result set as an associative array Only one item is retrieved at a time, similar to each Result set record pointer mysql_fetch_row fetches a row from the result set as an enumerated array mysql_fetch_array fetches a row from the result set as an associative array, a numeric array, or both array mysql_fetch_array ( resource $result [, int $ result_type ] ) Optional parameter result_type optional values are: MYSQL_ASSOC, MYSQL_NUM and MYSQL_BOTH (default) mysql_free_result releases result memory #Close link mysql_close closes the connection /* [Classes and Objects] */ # Members: Class members: class constants, static properties, static methods Object members: non-static properties, non-static methods # Classes cannot contain anything else! ! ! # Class names, method names, and attribute names are not case-sensitive # $this represents this object, self represents this class, parent represents the parent class # Both classes and functions can be compiled in advance (only when used as the outermost layer) # The definition of a class must be within a single PHP block and cannot be split by multiple PHP tags //Constructor - A class with a constructor will first call this method every time a new object is created void __construct([ mixed $args [, $... ]] ) - When the parameters required by the constructor are instantiated by new, add parameter values to the class. - Constructors can also be called manually. - Before version 5.3.3, methods with the same name as the class name were supported as constructors. - When there is a conflict between the two, __construct takes precedence. // Destruction method - A destructor is executed when all references to an object are removed or when the object is explicitly destroyed. void __destruct(void) # Function: Release the resources occupied by the object # Timing of calling - All resources are released at the end of the script, including objects - When deleting objects manually - When the variable holding the object is assigned a new value (any value, including null) - Also called when exit() is used to terminate the script. // Static members (static keyword) - Declaring class members or methods as static allows direct access without instantiating the class. - Static members (properties or methods) belong to classes, so they cannot be accessed through $this or ->.- Static members are shared by all objects and belong to the class. - Static members are called with classes, and non-static members are called with objects. # Static properties - Static properties cannot be accessed by objects through the -> operator. - Static properties can only be initialized to a character value or a constant, and expressions cannot be used. So you can initialize a static property to an integer or an array, but it cannot point to another variable or function return value, nor to an object. # static method - Since static methods do not require an object to be called, the pseudo variable $this is not available in static methods. - Calling a non-static method using the :: method will result in an E_STRICT level error. // Access parsing operator (::) - Can be used to access static members, methods and constants, and can also be used to override members and methods in a class. - When accessing these static members, methods and constants from outside the class, the class name must be used. - The two special keywords self and parent are used to access members or methods inside a class. //Access analysis - Object members are specified internally through $this and externally through the object name. Both are accessed with ->. No need to add $ when accessing properties. Object name->Property name Object name->Method name() $this->Property name $this->Method name() - Class members are specified internally through self or parent and externally through the class name. They are all accessed using ::, and $ is required when accessing attributes. Class name::$Attribute name Class name::Method name() self::$Attribute name self::Method name() - Special: Class members can also be accessed through objects. (not recommended) Object name::$class attribute name $this::$class attribute name Object name::$class method name() $this::class method name() # To access object members, use ->, to access class members, use:: - Methods, whether static or non-static, can be accessed through a class or object. - Static properties are accessed through classes and static methods are accessed through objects. - $this can only be used when using an object to call non-static methods! - Static methods cannot use $this. - Classes can call object methods, but note that there cannot be $this inside the method. - Non-static methods can call static properties or static methods, but not vice versa. // class constant - The value of a constant will always remain the same. - There is no need to use the $ symbol when defining and using constants. - The value of a constant must be a fixed value and cannot be the result of a variable, class attribute, or other operation (such as a function call). # Definition: const constant name = constant value; - No need to add access modification qualifiers such as public - Class constants belong to the class and are accessed using class name::class constant or self::class constant // Automatically load objects - Automatically call the __autoload function when trying to use a class that has not been defined yet - Automatically load the used class name file (find the file with the corresponding name based on the class name, so the class name must be consistent with the class file name) - Every file that needs to load a class needs to have the __autoload function - Write the __autoload function into a separate file, and then require the function file for each file that needs to use the class. - The __autoload parameter is the class name function __autoload($class_name) { require_once $_SERVER["DOCUMENT_ROOT"] . "/class/$class_name.php"; } // $_SERVER["DOCUMENT_ROOT"] The document root directory where the currently running script is located - You can use the class name to deduce the file name where the class is located! - If there are multiple autoloading functions in a project, define a common function that can complete the loading, and use spl_autoload_register to register the function before the function. # spl_autoload_register - Register __autoload() function bool spl_autoload_register ([ callback $autoload_function ] ) - You can register multiple automatic loading functions, and the one registered first will be executed first. - Once the autoload function is registered, __autoload becomes invalid. - When registering a function, the parameter is the function name (note the quotation marks); when registering a method, the parameter is an array # When the method of registering a class or object is an automatic loading method, the parameter must be an array: spl_autoload_register(array(__CLASS__, '__autoload')); __CLASS__ represents the current class name. If $this is available for the object, see the manual for details. // Serialization (serialization) # Data transmission is all string type # Except resource types, all can be serialized # When serialization stores data, it will store the data itself and the data type. Function: 1. When transmitting data over the network; 2. When placing arrays or objects on disk # serialization serialize produces a storable representation of a value string serialize (mixed $value) - Returns a string, which contains a byte stream representing value and can be stored anywhere. - Facilitates storing or passing values in PHP without losing their type and structure. # Deserialize unserialize creates PHP values from stored representations mixed unserialize ( string $str [, string $callback ] ) - Operate on a single serialized variable, converting it back to a PHP value. # File read and write operations - file_put_contents writes a string to a file int file_put_contents($file, $data [,$flags]) $flags: FILE_USE_INCLUDE_PATH (overwrite), FILE_APPEND (append) - file_get_contents reads the entire file into a string string file_get_contents($file [, bool $use_include_path [,int $offset [,int $maxlen]]]) #Object serialization - Only data inside the object, i.e. non-static properties, can be serialized.# The class needs to be loaded before deserializing the object, and the automatic loading mechanism can also be triggered. __sleep serializes the properties to be serialized. - Commit uncommitted data, or similar cleanup operations, to partially serialize objects. - Returns an array containing the names of all variables in the object that should be serialized __wakeup When deserializing, prepare the resources required by the object in advance - Re-establish the database connection, or perform other initialization operations public function __sleep() { return array('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); } //Object inheritance class subclass name extends parent class {} If an object is an object of a subclass, it is also an object of the parent class. Single inheritance: A class can only inherit one parent class, and cannot inherit multiple classes at the same time. But a parent class can be inherited by multiple subclasses. instanceof determines whether an object is an object of a certain type Object name instanceof class name // access control public public (accessible to the inheritance chain, this class, and the outside) protected protected (only inheritance chain, this class can access) private private (accessible only to this class) Judgment based on member definition location and access location. # Compatibility issues - When declaring attributes, the var keyword declares public permissions by default - When declaring a method, omit the access modifier and default to public permissions // override $this represents this object, and whoever calls it represents that object. - During inheritance, if the subclass member name conflicts with the parent class member name, the subclass member will overwrite the parent class member. - Both properties and methods can be overridden by subclasses. - When the methods or attributes of the parent class no longer meet the needs of the subclass, they need to be rewritten. - It may also be rewritten due to irregular naming. Private properties cannot be overridden, and each private property is logged. While recording the attribute name, the class will also be recorded. If a built-in function is overridden, the parent class method can be called. For example, calling the parent class constructor parent::__construct() # Rewrite restrictions Access restrictions: Access control for members of a subclass must be equal to or weaker than that of the parent class. Method parameter restrictions: The number of parameters must be the same, but the parameter names can be different. # $this determines the principle $this is the object that calls the method and represents the execution environment object of the method. - Object call -Transmission of environment. If the value of $this cannot be determined during the current call (static call), the object environment of the static call will be passed to the called method. $this does not always represent this object, but is determined by the execution environment of the method. # final If a method in the parent class is declared final, the child class cannot override (override) the method. If a class is declared final, it cannot be inherited. But classes with the final keyword can still be instantiated! #Abstract class Keywords: abstract Abstract classes cannot be instantiated directly. You must first inherit the abstract class and then instantiate the subclass. An abstract class must contain at least one abstract method. Non-abstract classes cannot contain abstract methods. If a class method is declared abstract, it cannot contain concrete functional implementations. Abstract methods cannot contain braces and method bodies. When inheriting an abstract class, the subclass must implement all abstract methods in the abstract class. That is, the subclass must override all abstract methods in the abstract parent class. In addition, the visibility of these methods must be the same (or more relaxed) as in the abstract class. That is, if an abstract method in an abstract class is declared protected, then the method implemented in the subclass should be declared protected or public, and cannot be defined as private. - Ordinary methods in subclasses of abstract classes are executed in the same way as other classes. - Function: 1. Inheritance is an extended class that unifies public operations. 2. Limiting structure (normative). Standardizes the structure of subclasses. //Interface Keywords: interface - The way an object provides to interact with an object is the interface. - You can use interfaces to specify which methods a class must implement, but you do not need to define the specific content of these methods. - Defining an interface through interface is just like defining a standard class, but all methods defined in it are empty. - All properties and methods defined in the interface must be public, and the public keyword can be omitted. - Constants (const) can also be defined in interfaces. Interface constants and class constants are used exactly the same. Can be accessed using ::. Interface name::constant name, implementation class::constant name. They are all fixed values and can be used by subclasses or subinterfaces, but cannot be modified. - The interface cannot define properties! # Define interface interface interface name { Interface content (collection of public method declarations) } #Interface implementation - To implement an interface, you can use the implements operator. - The class must implement all methods defined in the interface, otherwise a fatal error will be reported. - If you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces. - When implementing multiple interfaces, methods in the interfaces cannot have the same name. - Interfaces can also be inherited, by using the extends operator. class class name implements interface name { Implementation of interface methods } # Notice 1. There is an inheritance relationship between classes and abstract classes, and there is an implementation relationship between classes and interfaces. 2. Classes and abstract classes have single inheritance, while classes and interfaces have multiple implementations. 3. Interfaces are not classes and limit the structure of classes. 4. There is multiple inheritance between interfaces.Use the extends keyword. interface I_C extends I_A, I_B {} // static delayed binding self::, represents this class (the class where the current code is located) Always represents this class because it is determined when the class is compiled. That is, when a subclass calls a parent class method, self does not represent the calling subclass. static::, represents this class (the class that calls this method) Used to reference a statically called class within an inheritance scope. The represented class is determined only at runtime. static:: is no longer resolved to the class in which the current method is defined, but is calculated at actual runtime. // Object traversal (iteration) - Objects save data through attributes, so the attributes of the object are traversed. - foreach language structure, obtain attribute name and attribute value. foreach ($obj as $p_name => $p_value) {} # Custom traversal (Iterator) Iterator - an interface for an external iterator or class that can iterate internally over its own Iterator::current — Returns the current element Iterator::key — Returns the key of the current element Iterator::next — move forward to the next element Iterator::rewind — Return to the first element of an iterator Iterator::valid — Check if the current position is valid #Clone of object //The value transfer between objects is [reference] transfer. Clone: new object = clone old object - All reference properties will still be a reference to the original variable. The __clone() method is automatically called when the object is cloned. Note: The construction method corresponds to instantiation (new), and the cloning method corresponds to clone (clone). // singleton mode #三privateonepublic Singleton pattern is used to generate a unique object for a class. The most commonly used place is database connection. After using the singleton pattern to generate an object, the object can be used by many other objects. # Prevent a class from being instantiated multiple times class MySQLDB { private static $instance = null; // Store the class instance in this property // The constructor is declared as private to prevent direct creation of objects private function __construct() {} public static function getInstance() { if(! self::$instance instanceof static) { self::$instance = new static; } return self::$instance; } private function __clone() {} // Prevent users from copying object instances } // magic method __construct constructor __destruct destructor method __clone clone object __sleep serialized object __wakeup deserializes objects __autoload automatically loads when the class is used but not found __toString object is used as a string __invoke when trying to invoke an object as a function # Overload overload Refers to dynamically "creating" class properties and methods Users are free to add additional properties to objects. This feature is overloading. All overloaded methods must be declared public. Overloaded methods are called when a class property or method is called that is undefined or invisible in the current environment. Parameters of overloaded magic methods cannot be passed by reference. # Attribute overloading - Handle inaccessible properties Property overloading can only be done in objects. #Property overloading is not valid for static properties In static methods, these magic methods will not be called. So these methods cannot be declared static. __set when assigning values to inaccessible properties public void __set(string $name, mixed $value) Function: Batch management of private attributes, indirect protection of object structure __get when reading the value of an inaccessible property public mixed __get(string $name) __isset when isset() or empty() is called on an inaccessible property public bool __isset(string $name) __unset when unset() is called on an inaccessible property public void __unset(string $name) # Method overloading - Handle inaccessible methods __call is automatically called when calling an inaccessible non-static method (such as undefined, or invisible) public mixed __call(string $name, array $arguments) __callStatic is automatically called when calling an inaccessible static method (such as undefined, or invisible) public static mixed __callStatic(string $name, array $arguments) # The $name parameter is the name of the method to be called. The $arguments parameter is an array containing the parameters to be passed to the method. //Type constraints Function parameters can be specified as objects or arrays only If it is limited to an object, add the class name before the formal parameter; if it is limited to an array, add array before the formal parameter. Type constraints allow NULL values Type constraints are not only used in class member methods, but can also be used in functions. //Three major features Encapsulation: Hiding the internals is absorption, and only develops interfaces. Inheritance: Members of one object are used by another object. Syntax is reflected in the sharing of codes. Polymorphism: multiple forms.// Classes and Objects·Keywords this represents this object public public (accessible to the inheritance chain, this class, and the outside) protected protected (only inheritance chain, this class can access) private private (accessible only to this class) parent:: represents the parent class self:: represents this class (the class where the current code is located) static:: represents this class (the class that calls this method) static static members (properties, methods), can be used by all objects, and can also be directly used or modified externally. Static methods cannot access non-static members. Final methods cannot be overloaded by subclasses, and classes cannot be inherited (methods, classes) const class constant (property) abstract abstract class interface interface extends class inheritance (sub-interface inheritance interface, other ordinary class inheritance) implements interface implementation (class implementation interface, abstract class implementation excuse) (there can be multiple implementations and inheritances of the interface) Iterator built-in interface (iteration) clone clone instance instance instanceof whether an object belongs to a certain class /* [Class and object related functions] */ class_alias([$original [,$alias]]) gives the class an alias class_exists($class [,$autoload]) checks whether the class is defined interface_exists($interface [,$autoload]) checks whether the interface has been defined method_exists($obj, $method) checks whether the method of the class exists property_exists($class, $property) checks whether the object or class has the property get_declared_classes(void) returns an array consisting of the names of defined classes get_declared_interfaces(void) returns an array containing all declared interfaces get_class([$obj]) returns the class name of the object get_parent_class([$obj]) returns the parent class name of the object or class get_class_methods($class) returns an array consisting of class method names get_object_vars($obj) returns an associative array consisting of object properties get_class_vars($class) returns an array consisting of the default attributes of the class is_a($obj, $class) Returns TRUE if the object belongs to this class or this class is the parent class of this object is_subclass_of($obj, $class) Returns TRUE if this object is a subclass of this class get_object_vars($obj) returns an associative array consisting of object properties //Common classes # PHP Manual -> Predefined classes Closure closure class, the final class of anonymous function objects stdClass standard class, usually used for object classes to save collection data __PHP_Incomplete_Class is an incomplete class. When there is only an object but no class is found, the object is considered to be an object of the class. Exception exception class PDO data object class //magic constant __DIR__ The directory where the file is located __LINE__ The current line number in the file __FILE__ The full path (absolute path) and file name of the file __CLASS__ The name of the class __METHOD__ The method name of the class, including the class name and method name __FUNCTION__ function name, used within a method to only represent the method name // Reflection mechanism Reflection Function: 1. Obtain structure information 2. Agent execution ReflectionClass reports information about a class ReflectionMethod reports information about a method ReflectionClass::export output class structure report # Agent execution Instantiate an object of the ReflectionFunction class $f = new ReflectionFunction('func'); // func is function func($p) $f->invoke('param'); /* Page jump */ // PHP header('Location: url') After header() is executed, the following code will continue to execute, so it is necessary to add die after the statement to end. Unable to give prompt, jump directly //JS method location.href = url // HTML <meta http-equiv="Refresh" content="Value representing time; url=URI to be redirected"> /* [Cookie] */ A cookie is a mechanism that stores data on a remote browser to track and identify users. Cookies are part of the HTTP header, so the setcookie() function must be called before other information is output to the browser, similar to the restrictions on the header() function. You can use the output buffer function to delay the output of the script until all cookies or other HTTP headers have been set as required. //Add setcookie adds a cookie information setcookie($name [,$value [,$expire [,$path [,$domain [,$secure [,$httponly]]]]]]) #Note: There cannot be output before the setcookie() function! Unless ob cache is turned on! # Parameter description $name - the identifying name of the cookie Use $_COOKIE['name'] to counteract the cookie named name $value - cookie value, which can be a numeric value or a string. This value is stored on the client side and should not be used to store sensitive data. Assuming that the value of the $name parameter is 'name', $_COOKIE['name'] can obtain the $value $expire - cookie lifetime (Unix timestamp, seconds) If the value of the $expire parameter is time()+60*60*24*7, you can set the cookie to expire after one week. If this parameter is not set, it will expire immediately after the session. $path - The specified path of the cookie on the server side. When this value is set, only web pages or programs under the specified path in the server can access the cookie. If the parameter value is '/', the cookie is valid within the entire domain. If set to '/foo/', the cookie will be valid in the /foo/ directory and its subdirectories under the domain. The default value is the current directory and its subdirectories where the cookie is set. $domain - Specifies the URL name of the server where this cookie belongs. The default is the URL of the server that created this cookie. If the cookie is to be valid in all subdomains of a domain name such as abc.com, the entry should be set to '.abc.com'.$secure - The security identification constant of the cookie that indicates whether the cookie is only transmitted through a secure HTTPS connection. If this value is set, it means that it can only be transmitted between the client and the server under certain circumstances. When set to true, the cookie is only set on secure connections. The default value is false. // read - When the browser makes a request, it will carry all cookie information under the current domain name to the server. - Any cookie sent from the client will be automatically stored in the $_COOKIE global array. - If you want to set multiple values for a cookie variable, you need to add the [] symbol after the cookie name. That is, multiple pieces of data are saved to the same variable in the form of an array. //Set to $_COOKIE['user']['name']. Note that the name of user[name] does not have quotation marks. setcookie('user[name]', 'shocker'); - $_COOKIE can also be an index array // delete Method 1: Set its value to an empty string setcookie('user[name]', ''); Method 2: Set the target cookie to "expired" status. //Set the cookie's lifetime to expire. The lifetime is the same as the browser and will be deleted when the browser is closed. setcookie('usr[name]', '', time()-1); # Notice: 1. Cookies can only store string data 2. $_COOKIE is only used to receive cookie data, not to set or manage cookie data. Operating on $_COOKIE will not affect cookie data. $_COOKIE will only save the cookie data carried by the browser during the request. 3. Cookie life cycle: Temporary cookies: deleted when the browser is closed Persistent cookies: The $expire parameter is a timestamp, indicating the expiration time. 4. Valid directory Cookies are only valid in specified directories. The default is the current directory and its subdirectories. Cookies for subdirectories are not available in its parent directory or sibling directories. 5. Cookie distinguishes domain names By default, the current domain name and its subdomain names are valid. 6. Obtained through document.cookie in js, the type is string 7. Browsers have no limit on the total number of COOKIEs, but the number of COOKIEs per domain name and the size of each COOKIE are limited, and different browsers have different restrictions. /* 【session】 */ 1. Open the session mechanism session_start() Note: There must be no output before the session_start() function! Unless ob cache is turned on. 2. Operation data Operate on $_SESSION array 3. The browser saves the SessionID, which takes effect for all directories and subdirectories under the current domain name by default. That is, the default path value of the cookie is set to '/' 4. The server saves session data Default saving method: Each session will generate a session data file, the file name is: sess_plus SessionID 5. Session can store any type of data except resources. The data is serialized and then saved to a file. 6. The element subscript of $_SESSION cannot be an integer! Because only element values are serialized. Array subscripts within elements do not have this requirement. 7. Life cycle The browser is closed by default Because the cookie variable SessionID saved by the browser is temporary However, the session data file on the server side does not necessarily disappear (you need to wait for the session's garbage collection mechanism to process it) The life cycle of the PHPSESSID variable in the cookie can be extended. (not recommended) php.ini configuration session.gc_maxlifetime 8. Delete data The $_SESSION variable will still disappear when the script ends. When the session mechanism is turned on, the $_SESSION variable will be created. $_SESSION and the file that saves session data are two spaces. unset($_SESSION['key']) only deletes the element in the array, and will not immediately respond to the file that saves the session data. Wait until the script ends before the $_SESSION data is written to the file. session_destroy() destroys the file that saves session data and does not write content to the file. The $_SESSION variable is not deleted and will not be deleted until unset or the script ends. How to completely delete a session? 3 parts need to be deleted unset($_SESSION); After deleting the $_SESSION variable, the data file has not been changed. If you use unset alone, you need to empty $_SESSION = array() first session_destroy(); setcookie('PHPSESSID', '', time()-1); //The insurance policy is to invalidate its life cycle During the entire script cycle, the data file is only read once and written once. // Rewrite the session storage mechanism #session storage method session.save_handler = user|files|memcache # Problems caused by too many data files can be solved by saving them in the molecular directory session.save_path option in the PHP configuration file, and the data storage directory needs to be created manually. Prepend the level before this configuration option. The principle of distributing subdirectories uses the corresponding letters of the session ID to allocate subdirectories. Subdirectories still need to be created manually. session.save_path = "2; F:/PHPJob/Temp" #Multi-server data sharing issues #Data storage operations: Initialize $open, release resources $close, read $read, write $write, destroy storage media $destroy (this operation is triggered when session_destroy is called), and garbage collection $gc # The length of the session ID is variable. Different setting methods result in session IDs of different lengths. session.hash_function allows the user to specify the hashing algorithm used to generate session IDs. '0' means MD5 (128 bits), '1' means SHA-1 (160 bits). session.hash_bits_per_character allows the user to define how many bits are stored per character when converting binary hash data into a readable format. Possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").The total hash length is 128 bits, and the session ID length is 128/possible values, 4->32, 5->26, 6->22 # Custom data storage operation method # Note: Don’t worry about how PHP serializes, deserializes, gets data and writes data, only do operations related to data storage. session_set_save_handler sets user-defined session data storage function bool session_set_save_handler(callable $open, callable $close, callable $read, callable $write, callable $destroy, callable $gc) Execution order: open, close, read, write, destroy, gc # Set the processor first, then open the session # Commonly used functions session_start starts or resumes the session mechanism session_id gets or sets the current session ID session_destroy destroys all data of the current session (destroy data files) session_name gets or sets the current session name (cookie variable name, default is PHPSESSID) session_save_path gets or sets the current session data file save path session_set_save_handler sets user-defined session data storage function session_unset releases all session variables (clears $_SESSION array elements) session_encode encodes the current session data into a string session_decode interprets strings into session data session_write_close writes session data and closes the session session_register_shutdown closes the session session_set_cookie_params sets session cookie variables and must be used before session_start(). session_set_cookie_params(0,"/webapp/"); //Set session survival time session_get_cookie_params gets the session cookie variables. Returns an array containing cookie information for the current session # Configure php.ini ini_set($varname, $newvalue); //The configuration of this function only takes effect for the current script //Not all php.ini settings can be set by this function ini_get($varname) //Get information about a certain configuration item ini_get_all([str $extension]) //Returns an array of all configuration item information # session extension configuration session.name specifies the session name to use as the name of the cookie. It can only consist of alphanumeric characters and defaults to PHPSESSID. session.save_path defines the parameters passed to the storage handler. If the default files file processor is selected, this value is the path to the created file. The default is /tmp. The optional N parameter determines the directory depth in which session files are distributed. To use the N parameter, these directories must be created before use. There is a small shell script called mod_files.sh in the ext/session directory that can be used to do this. If the N parameter is used and N is greater than 0, automatic garbage collection will not be performed. session.save_handler defines the name of the handler used to store and retrieve data associated with the session. The default is files. If the user defines the memory, the value is changed to user. ini_set('session.save_handler', 'user');//This setting only takes effect for the current script. session.auto_start specifies whether the session module automatically starts a session when a request starts. Default is 0 (do not start). session.gc_probability and session.gc_divisor together define the probability of starting the gc (garbage collection garbage collection) process when each session is initialized. This probability is calculated using gc_probability/gc_divisor. For example 1/100 means there is a 1% probability of starting the gc process in each request. session.gc_divisor defaults to 100. session.gc_probability defaults to 1./* [Image generation and processing] */GD library // Canvas generation # Create new canvas imagecreate creates a new palette-based image resource imagecreate(int $x_size, int $y_size) imagecreatetruecolor creates a new true color image # Create a canvas based on an existing file or URL imagecreatefromgd2 Create a new image from a GD2 file or URL imagecreatefromgd2part Creates an image from a given GD2 file or part of a URL imagecreatefromgd creates a new image from a GD file or URL imagecreatefromgif creates a new image from a file or URL imagecreatefromjpeg creates a new image from a file or URL imagecreatefrompng Create a new image from a file or URL imagecreatefromstring creates an image from an image stream in a string imagecreatefromwbmp Create a new image from a file or URL imagecreatefromxbm creates a new image from a file or URL imagecreatefromxpm creates a new image from a file or URL // color assignment imagecolorallocate assigns a color to an image int imagecolorallocate(resource $image, int $red, int $green, int $blue) imagecolorallocatealpha assigns color + alpha to an image imagecolordeallocate cancels the allocation of image color imagecolortransparent defines a color as transparent imagecolorat gets the color index value of a pixel imagecolorclosest Gets the index value of the color closest to the specified color imagecolorclosestalpha Gets the color closest to the specified color plus transparency imagecolorclosesthwb Gets the black and white index of the hue closest to the given color imagecolorexact gets the index value of the specified color imagecolorexactalpha Gets the index value of the specified color plus transparency imagecolormatch makes the palette version of colors in an image more closely match the true color version imagecolorresolve Gets the index value of the specified color or the closest possible replacement value imagecolorresolvealpha Gets the index value of the specified color + alpha or the closest alternative possible imagecolorset sets the color for the specified palette index imagecolorsforindex gets the color of an index imagecolorstotal Gets the number of colors in the palette of an image // area filling imagefill area filling bool imagefill(resource $image, int $x, int $y, int $color) imagefilledarc draws an elliptical arc and fills it imagefilledellipse draws an ellipse and fills it imagefilledpolygon draws a polygon and fills it imagefilledrectangle draws a rectangle and fills it imagefilltoborder fills the area to the border of the specified color imagesettile sets the texture used for filling // Graphic creation imagearc draws elliptical arc imagechar draws a character horizontally imagecharup draws a character vertically imagedashedline draw a dotted line imageellipse draws an ellipse imageline draws a line segment imagepolygon draws a polygon imagerectangle draws a rectangle imagesetpixel draws a single pixel imagesx gets image width imagesy gets image height //Brush settings imagesetbrush sets the brush image used for drawing lines imagesetstyle sets the style of line drawing imagesethickness sets the width of the line drawing // Graphic copy imagecopy copies part of an image imagecopymerge copies and merges part of an image imagecopymergegray copies and merges part of an image in grayscale imagecopyresampled resamples copy part of the image and resizes it imagecopyresized copies part of the image and resizes it //Character creation imagestring draws a line of string horizontally imagestringup draws a line of string vertically imagepsslantfont tilts a font imagefontheight gets the font height imagefontwidth gets the font width imagettfbbox Get the range of text using TrueType font imageloadfont loads a new font imagepsencodefont changes the character encoding vector in the font imagepsextendfont expands or condenses fonts // Export canvas as image imagegif Output images in GIF format to a browser or file imagepng Outputs images in PNG format to a browser or file imagejpeg Output images in JPEG format to a browser or file imagewbmp Output images in WBMP format to a browser or file Sending "Content-type: image/image format" through header() can cause the PHP script to output the image directly.header("Content-type: image/gif"); imagegif($im); imagegd Output GD images to a browser or file imagegd2 Output GD2 images to a browser or file // Release canvas resources imagedestroy destroy image //Image information image_type_to_extension gets the file suffix of the image type getimagesize gets the image size imagesx gets image width imagesy gets image height imageistruecolor checks whether the image is a true color image imagetypes returns the image types supported by the current PHP version //Image settings imagerotate rotates an image by a given angle imagealphablending sets the color blending mode of the image imageantialias Whether to use the anti-aliasing (antialias) function imagefilter applies a filter to an image imagegammacorrect applies gamma correction to GD images imageinterlace Activate or disable interlacing /* [Thumbnail] [Watermark] */ imagecopyresampled resamples copy part of the image and resizes it bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h ) imagecopymerge copies and merges part of an image bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct ) getimagesize gets the image size