First, the basic PHP
Base type: Integer, String, Boolean, float, array, object, resource, NULL scalar type: boolean, Integer, Float/double, string composite type : Array, object Special type: resource, NULL Super global variable: $GLOBALS, $_server, $_request, $_post, $_get, $_cookie, $_files, $_env, $_session $_post capable of receiving type: application/x-www-form-urlencoded multipart/form-data php://i Nput read-only stream of raw data for access requests, including $_post supported types and Application/json//php $_post = Json_decode (file_get_conten TS (' Php://input '), true); $_server[' php_self '] returns the file name of the current execution script. $_server[' Gateway_interface ' returns the version of the CGI specification used by the server. $_server[' server_addr ' returns the IP address of the server where the script is currently running. $_server[' server_name ' returns the hostname (such as www.baidu.cn) of the server where the script is currently running. $_server[' Server_software ') returns the server identification string (such as apache/2.2.24). $_server[' Server_protocol ' returns the name and version of the communication protocol when the page is requested (for example, "http/1.0"). $_server[' Request_method ' returns the request method (such as POST) used by the access page. $_server[' Request_time ') returns the timestamp at the start of the request (for example, 1577687494)。 $_server[' query_string ') returns the query string if it is accessed through a query string. $_server[' http_accept ') returns the request header from the current request. $_server[' Http_accept_charset ' returns the Accept_charset header (for example utf-8,iso-8859-1) from the current request $_server[' Http_host '] returns from the current The Host header of the request. $_server[' Http_referer ' returns the full URL of the current page (unreliable because it is not supported by all user agents). $_server[' HTTPS '] whether the script is queried through the secure HTTP protocol. $_server[' REMOTE_ADDR ' returns the IP address of the user who browsed the current page. $_server[' Remote_host '] returns the host name of the user who browsed the current page. $_server[' Remote_port ' returns the port number used to connect to the WEB server on the user's machine. $_server[' script_filename ' returns the absolute path to the current execution script. $_server[' server_admin ') This value indicates the Server_admin parameter in the Apache server configuration file. $_server[' Server_port ') the port used by the WEB server. The default value is "80". $_server[' Server_signature ') returns the server version and the virtual host name. $_server[' path_translated ' The base path of the file system (not the document root) where the current script resides. $_server[' Script_name '] returns the path of the current script. $_server[' Script_uri ' returns the URI of the current page. PHP Global Processing: register_shutdown_function//Register a function that will execute when PHP is aborted set_error_handler//Set user-defined error handling functions (user-level error, Trigger_error) Set_exception_handler//Set user-defined exception handler (user-level exception, throw) s Ession_set_save_handler//Set user custom session Store function Spl_autoload_register//autoloader, different from __auto_load () can only load magic variable once: __line__ The current line number in the file __file__ the full path and file name of the file. If used in the included file, returns the file name that is included. The directory where the __dir__ file resides. If used in the included file, returns the directory where the included files are located. The name of the __FUNCTION__ function when it is defined (case-sensitive). The name of the __class__ class when it is defined. The name of the method in the __method__ class when it is defined. __NAMESPACE__ the name of the current namespace. PHP Magic Method: Object destructor, Deconstruction __construct object destructor __destruct object deconstructed function property overload __set called when assigning a value to an unreachable property Called when __get reads the value of an inaccessible property when calling __isset to a non-accessible property called Isset () or empty () calls __unset to an inaccessible property Unset () calls a method overload when called when an inaccessible method is called in an object __call called when a __callstatic is called in a static context, and the method object sequence is called statically __sleep is called when the object is serialize (), cleans the object, and returns an array containing all the variable names that should be serialized in the object. Called when __wakeup unserialize () is used to pre-prepare the required resources for the object. Object String __tostriThe Ng class returns a string when it is treated as a string. The __invoke object calls the derived class when it attempts to invoke an object in a call to a function __set_state when calling the Var_export () export class, the method is called statically Debuginfo When you call Var_dump () to print a class, if you define the method it will only print the method return value, otherwise print all member settings, exceptions, error handling: Set Ini_set (' Max_execution_time ',-1); The time-out of the script execution Ini_set (' Default_socket_timeout ',-1); The default timeout time based on the socket stream is Ini_set (' Memory_limit ',-1); Set script execution Max memory ini_set (' error_reporting ', E_all | E_STRICT); Error level Ini_set (' display_errors ', ' on '); Turn On Error write-back, open state, if there is an error, then error, there is a false hint Ini_set (' log_errors ', ' on '); Turn On error log, log to error_log specified path Ini_set (' Date.timezone ', ' Asia/shanghai '); Time zone setting error_reporting (7); Error level, with INI configuration set_time_limit (0); Sets the maximum execution time of the script, with the same INI configuration, only affects the time ignore_user_abort () that the script itself executes; Close the browser, the PHP background continues to run functions, Description: Debug_backtrace () generate BackTrace. DeBug_print_backtrace () Print backtrace. Error_get_last () returns the last error that occurred. Error_log () sends an error message to the server error record, file, or remote destination. Error_reporting () specifies which error to report. Restore_error_handler () Restores the previous error handler. Restore_exception_handler () Restores the previous exception handler. Set_error_handler () Sets the user-defined error-handling function. Set_exception_handler () Sets the user-defined exception handling function. Trigger_error () Creates a user-level error message. Alias of User_error () Trigger_error (). Error Type: 1 e_error run-time fatal error. The error cannot be fixed. Terminates the execution of the script. 2 e_warning Run-time non-fatal error. Does not terminate execution of the script. 4 E_parse Compile-time syntax parsing error. Parsing errors are generated only by the parser. 8 E_notice run-time notification. Indicates that the script encountered a situation that might behave as an error, but there may be similar notifications in a script that can run correctly. E_core_error A fatal error occurred during PHP initialization startup. This error is similar to E_error, but is generated by the core of the PHP engine. E_core_warning PHP Initialization Warning (non-fatal error) occurred during startup. Similar to e_warning, but generated by the core of the PHP engine. E_compile_error Fatal compile-time error. Similar to E_error, but generated by the Zend scripting engine. E_compile_warning Compile-time warning (non-fatal error). Similar to e_warning, but generated by the Zend scripting engine. For E_user_errorError messages generated by the user. Similar to E_error, but is generated by the user himself using the PHP function Trigger_error () in the code. E_user_warning user-generated warning message. Similar to e_warning, but is generated by the user himself using the PHP function Trigger_error () in the code. 1024x768 E_user_notice User-generated notification information. Similar to E_notice, but is generated by the user himself using the PHP function Trigger_error () in the code. 2048 e_strict enables PHP to modify code recommendations to ensure the best interoperability and forward compatibility of your code. 4096 E_recoverable_error can be captured by a fatal error. It indicates that a potentially very dangerous error has occurred, but has not yet caused the PHP engine to be in an unstable state. If the error is not captured by the user custom handle (see Set_error_handler ()), it becomes a e_error and the script terminates. 8192 e_deprecated run-time notification. When enabled, warns you about code that might not work correctly in a future release. 16384 e_user_deprecated User-generated warning message. Similar to e_deprecated, but is generated by the user himself using the PHP function Trigger_error () in the code. 32767 E_all e_strict except for all error and warning messages.
Garbage collection Mechanism < 5.2 If the RefCount value is 0,php as garbage, this recovery mechanism is defective and the variable for the ring reference cannot be reclaimed >= 5.3 discovers Refcoun in a zval container T In addition, the description is not garbage found in a zval container refcount in the reduction, if reduced to 0, directly as garbage collection found in a Zval container refcount in the reduction, and did not reduce to 0,php will put the value into the buffer, as there may be garbage suspicion on Like. When the buffer reaches a critical value, PHP automatically calls a method to iterate through each value and cleans up the reference count if it finds garbage: # # PHP4-PHP6 * php variable exists in a variable container called "Zval". * The Zval variable container contains: variable value (value), variable type (type), whether it is a reference collection (IS_REF__GC), number of references (REFCOUNT__GC) * New variable "Is_ref" is set to FALSE by default because there is no custom citation With the build. * Xdebug_debug_zval () displays values for "RefCount" and "Is_ref". * Assigning a variable to another variable will increase the number of references (refcount). Recycling mechanism: < 5.2 If the RefCount value is 0,php as garbage, the recovery mechanism is defective, and the variable for the ring reference cannot be reclaimed >= 5.3 Found in a Zval container refcount in the increase, indicating that not garbage found in a zval container refcount in the reduction, if reduced to 0, directly as garbage collection found in a Zval container refcount in the reduction, and did not reduce to 0,php will put this value in the buffer, as a suspected object that might be garbage. When the buffer reaches a critical value, PHP automatically calls a method to iterate through each value, and if found to be garbage, clean it up: * Use reference counter and synchronization algorithm to process * Put all possible root variable containers in the root buffer and buffer when the root buffer is full All areas within the zone are notThe same variable container performs garbage collection operations. * The reference count is reduced and will be pushed to the garbage collection cycle, by checking which variable containers have a reference count of zero, to find out which part is garbage. * The reference count is reduced to zero, where the variable container is cleared (free).
Second, PHP-FPM
Basic Operation #启动PHP服务/usr/local/php/sbin/php-s 127.0.0.1:8080-T [catalogue] [&] #启动php-fpm/usr/local/php/sbin/php-fpm /usr/local/php/sbin/php-fpm-c/usr/local/php/etc/php.ini-y/usr/local/php/etc/php-fpm.conf #关闭php-fpm kill-in T ' cat/usr/local/php/var/run/php-fpm.pid ' #重启php-fpm kill-usr2 ' cat/usr/local/php/var/run/php-fpm.pid ' working principle PHP The SAPI apache2handler, mode_php fastcgi CLI ISAPI fastcgi provided works: 1. Load FASTC when server starts GI Process Manager 2. The FASTCGI process Manager itself initializes, starts multiple CGI interpreter processes (visible multiple php-cgi) and waits for connection 3 from the server. When a client request arrives at the server, the FASTCGI process manager selects and connects to a CGI interpreter. WEB server sends CGI environment variables and standard input to the FASTCGI child process php-cgi. 4. When the fastcgi child process finishes processing, returns the standard output and error information from the same connection to the server. When the fastcgi child process closes the connection, the request is processed to completion. The fastcgi child process then waits and processes the next connection from the FASTCGI process Manager (running in Web server). Run mode static mode, which allocates a fixed worker process at startup. OnDemand on demand, fork the worker process when a user request is received. Dynamic mode, which allocates a fixed process at startup. As the number of requests increases, the worker process is adjusted in the set floating range. Process Pool Parameters Pm.max_children: Limits the maximum number of processes for PHP-FPM, and static mode assigns the work number by default. Pm.start_servers: The number of start PHP-FPM processes under dynamic mode. Pm.min_spare_servers: The minimum number of PHP-FPM processes in the dynamic idle state. Pm.max_spare_servers: The maximum number of php-fpm processes in the dynamic idle state. Operating principle the master process is responsible for the initialization of CGI, PHP public environments, and event monitoring operations. The worker process is responsible for the processing capabilities of the request. When the worker process processes the request, it is not necessary to initialize the PHP runtime environment again, which is one of the reasons why PHP-FPM performance is excellent. Master:1. CGI initialization phase: Call Fcgi_init () and Sapi_startup () functions separately, register process signals, and initialize sapi_globals global variables. 2. PHP Environment Initialization phase: triggered by Cgi_sapi_module.startup. The Php_cgi_startup function is actually called, and php_cgi_startup internal calls Php_module_startup execution. Php_module_startup main functions: a). Load and parse PHP configuration; b). Load the PHP module and record it into the function symbol table (function_table); c). load the Zend extension; d). Set the Disable function and class library configuration; e). Register the Recovery memory method; 3. PHP-FPM Initialization phase: Executes the fpm_init () function. Responsible for parsing the php-fpm.conf file configuration, getting process-dependent parameters (maximum number of files allowed to open by the process, etc.), initializing the process pool and event model, and so on. 4. PHP-FPM Operation phase:Line Fpm_run () function, the running of the process of the aorta is blocked. This phase is divided into two parts: Fork subprocess and Loop event. The fork sub-process is partially referred to the fpm_children_create_initial function. The Loop event section is handled by the Fpm_event_loop function, which is a dead loop that is responsible for the collection of events. Worker:1. Receive client request: Executes the Fcgi_accept_request function, which internally obtains the client request by calling the Accept function. 2. Process the request phase: first, call Fpm_request_info, Php_request_startup to obtain the request content and register the global variables ($_get, $_post, $_server, $_env, $_files); The Php_fopen_primary_script access script file is then invoked according to the request information, and finally to php_execute_script execution. Php_execute_script internally calls the Zend_execute_scripts method to hand the script to the Zend engine for processing. 3. Request End Stage: Executes the Php_request_shutdown function. This callback register_shutdown_function the registered function and the __destruct () method, sending the response content, freeing the memory, and so on.
Iii. new features of PHP
The problem faced by PHP5 's zvalue: 1. The size of the struct is 24 byte 2. No custom field 3 is reserved. Most of PHP's zval are passed by value, copy the value when writing, but objects and resources, they are always passed by reference, so it has two sets of reference count, one is Zval, the other is the count of obj itself, the structure becomes complex, maintainability reduced by 4. Write-time separation for PHP applications is a replication performance issue 5. Many local variables use heap memory allocation <?php $array = range (1, 100000); function Dummy ($array) {} $i = 0; $start = Microtime (true); while ($i + + <) {dummy ($array); } printf ("Used%ss\n", Microtime (True)-$start); $i = 0; $b = & $array; Notice here, suppose I accidentally referred this array to a variable $start = Microtime (true); while ($i + + <) {dummy ($array); } printf ("Used%ss\n", Microtime (True)-$start); ?> zval Container Change # # # version < 7 Zval variable container {value,--Variable value (16 bytes) type,--Variable type (2 bytes) IS_REF__GC--whether it belongs to the reference set (2 bytes) REFCOUNT__GC--citations (4 bytes)} # # # # # # # # # >= 7 Zval variable Container {value,--Variable value (16 bytes) U1 Union {type_info--type information zend_endian_ Lohi_4--simplified assignment, structure of four-character variable} U2 consortium {var_flags Next--hash collision chain Cache _slot Lineno--line number (AST, object spanning tree slot point) Num_args fe_pos--foreach location Fe_iter_i DX--foreach iterator Index}} specific: For values that can be saved in the Value field of Zval, they are no longer referenced, but are assigned directly at the time of copy, thus eliminating a large number of reference count related operations Zend_endian_lohi_4 function is to simplify the assignment, to ensure that on the big or small end of the machine, the defined fields are stored in the same order, so that when we assign the value, we do not need to assign a value to its fields, but can be uniformly assigned value
Iv. PHP Security Mechanisms
Attack means: SQL injection, XSS, CSRF, DDOS, session fixed attack, session hijacking attack, File Upload vulnerability php Vulnerability: 1. Accuracy bypass defect floor ((0.1+0.7) *10)//= 7 2. Type conversion defect var_dump (' 66hh ' = = 66); True 3. Loose Comparator defect Var_dump (0== "GG"); True Var_dump (0=== "GG"); False Var_dump (1== "GG"); False 4. MD5 Bypass (hash comparison defect) Var_dump (MD5 (' qnkcdzo ') = = MD5 (240610708)); String MD5 Qnkcdzo 0e830400451993494058024219903391 240610708 0e462097431906509019562988736854 AABG7XSS 0e087386482136013740957780965295 Aabc9rqs 0e041022518165728065344349536299 s878926199a 0e5 45993274517709034328855841020 6. SHA1 () and MD5 () cryptographic function Vulnerability Var_dump (SHA1 ($_get[' name ')) = = = SHA1 ($_get[' password '))//Request/?name[]=a&password[]=b 7. String handling function The flaw defect function accepts a non-conforming type, such as an array type, and the function will have an error. Before 5.3, after displaying the warning message of the error, return 0 will be judged to be correct. 8. parse_str function variable coverage defect PARSE_STR function is to parse the string and register as a variable, before registering the variable does not verify the existence of the current variable, so directly overwrite the existing variable. Reference: Http://www.freebuf.com/articles/rookie/161474.html prompt Site safety factor: register_globals = off--Turn off Global registration variable function error_reporting = e_all| E_strict--Configure the alert mode, if there is uninitialized, will be alerted display_errors = on--Do not display the page error message Log_errors = On--Save the error message to the local AL Low_url_include = off--not allowed to load remote PHP files Allow_url_fopen = off--does not allow opening of remote files (affects fopen,file_put_contents) magic_quotes _GPC = on--Filter of Get,post,cookie variable, filter with single quotation mark, double quotation mark, backslash, null character, all escaped with backslash ($_server variable does not filter) magic_quotes_runtime= on--Take out file or database Data filtering Safe_mode = on-restricts function usage permissions and operations directory file permissions. Verify that the user has permission to manipulate files. Disable_functions--disabled function expose_php = off--Hides PHP version information display_startup_errors = off--does not display PHP program on the page Error site attack: 1. Cross-site scripting attacks (Scripting, XSS) Description: An attacker injects malicious code into a Web page, and other users execute code when the page is loaded, an attacker There may be a variety of content including but not limited to higher permissions (such as performing some actions), private web content, conversations, and cookies. For example: <?php echo "welcome you,". $_get[' name ']; A dialog box pops up: Http://localhost/test.php?name=<script>alert (123456) </script> Precautionary method: Use the Htmlspecialchars function to convert special characters to HTML encoding, filtering the output of variables 2. Cross site request forgery attack (forgeries, CSRF) Description: The attacker forges the HTTP request of the target user and then sends the request to a Web site with a CSRF vulnerability, which causes a cross-site request forgery attack after the Web site executes the request. The attacker uses a covert HTTP connection to allow the target user to click on the link without notice, because the user clicks on it, and the legitimate user has legal rights, so the target user can execute a specific HTTP link within the site to achieve the attacker's purpose. For example, when buying a product on a shopping site, use the http://www.shop.com/buy.php?item=watch&num=100 item parameter to determine what item to buy, num parameter determines the quantity to buy, if If an attacker sends a link to a target user in a hidden way, the number of purchases is 100 if the target user accidentally accesses it. Precautions: 1, check the source of the Web page 2, check the built-in hidden variable 3, use post, do not use GET, deal with variables and do not directly use $_request 3. Session fixed attack (session fixation) Description: The attacker pre-set the session ID, allowing legitimate users to use the session ID to access the attacked application, once the user's session ID is successfully fixed, the attacker can This session ID is passed to impersonate the user to access the application. For example: 1. The attacker accesses the website http:///www.bank.com, obtaining his own session ID, such as: sid=123; 2. The attacker sends a link to the target user with his session ID, such as: http :///www.bank.com/? sid=123; 3. The target user clicked http:///www.bank.com/? Sid=123, as usual, enter your username and password to login to the website; 4. Due to the SE of the serverSsion ID does not change, now the attacker clicks Http:///www.bank.com/?SID=123, he has the target user's identity, can do whatever you like. Precautions: 1. Change session ID 2 periodically. Change the name of the session, the default name of Session is PHPSESSID 3. Turn off transparent session ID, Int_set ("Session.use_trans_sid", 0); 4. Only check session ID int_set ("session.use_cookies", 1) from the cookie, or use cookies to store session ID Int_set ( "Session.use_only_cookies", 1);//indicates that only cookies are used to store session ID 5. Use URL to pass hidden parameters $sid = MD5 (Uniqid (rand () ), TRUE); $_session["sid"] = $sid; 4. Session hijacking attack (session hijacking) Description: The attacker uses various means to obtain the session ID of the target user. Once the session ID is obtained, the attacker can use the identity of the target user to log on to the Web site and get the permissions of the target user. How the attacker obtains the target user session ID: A. Brute force: Try various session IDs until they are cracked; B. Calculation: If the session ID is generated in a non-random way, then it is possible to calculate it; C. Stealing: Using network interception, XSS attacks and other methods to obtain a precautionary approach: 1. Periodically change session ID 2. Change the name of the session 3. Turn off transparent session ID 4. Set the HttpOnly. By setting the HttpOnly of the cookie to TRue, which prevents the client script from accessing this cookie, effectively preventing XSS attacks. Reference: PHP Security Web attack: http://www.cnblogs.com/luyucheng/p/6234524.html PHP code security: Http://www.freebuf.com/articles/rookie /161474.html interface Security: Token mechanism, allocation Appkey, Appsecret data validation, Sign+timestamp+token overload protection exception encapsulation
V. The difference between stack memory and heap memory:
程序的内存分配 栈(stack):有编译器自动分配和释放,存放函数的参数、局部变量、临时变量、函数返回地址等; 堆(heap):一般有程序员分配和释放,如果没有手动释放,在程序结束时可能由操作系统自动释放, 稍有不慎会引起内存泄漏。 申请后系统的响应 栈:只要栈的剩余空间大于所申请的空间,系统将为程序提供内存,否则将报异常提示栈溢出。 堆:在记录空闲内存地址的链表中寻找一个空间大于所申请空间的堆结点,然后将该结点从空闲结点链表中删除,并将该结点的空间分配给程序。 申请大小限制 栈:在Windows下,栈是向低地址扩展的数据结构,是一块连续的内存的区域。 如果申请的空间超过栈的剩余空间时,将提示overflow。因此,能从栈获得的空间较小。 堆:堆是向高地址扩展的数据结构,是不连续的内存区域。堆的大小受限于计算机系统中有效的虚拟内存。 由此可见,堆获得的空间比较灵活,也比较大。 分配效率 栈:由系统自动分配,速度较快。但程序员是无法控制的。 堆:由new分配的内存,一般速度比较慢,而且容易产生内存碎片,不过用起来最方便。 存储内容 栈:在栈中,第一个进栈的是主函数下一条指令的地址,然后是函数的各个参数,在大多数编译器中,参数是由右往左入栈,然后是函数中的局部变量。注意,静态变量不入栈。出栈则刚好顺序相反。 堆:一般在堆的头部用一个字节存放堆的大小,具体内容由程序员安排。
Vi.. Performance analysis
XDebug is set in php.ini as follows zend_extension = "D:\xampp\php\ext\php_xdebug.dll" xdebug.collect_includes = 1 xdebug.profiler_enable = 0 Xdebug.profiler_enable_trigger = 1 xdebug.profiler_output_dir = "D:\xampp\tmp" Xdebug.profiler_output_name = "Cachegrind.out.%u.log" is configured to restart Nginx, add Xdebug_profile in ZF2 Project URL to open xdebug log output Reference: Https://avnpc.com/pages/how-to-debug-under-zf2xhprof Install xhprof, modify PHP.ini, echo "extension=xhprof.so" >/etc/ph The P5/fpm/conf.d/xhprof.ini UI lists: Funciton name: function name calls: Number of calls incl. Wall time (MICROSEC): Functions Run (including sub-functions) iwall%: function run time (including child functions) accounted for Excl. Wall time (MICROSEC): function runtime (excluding child functions) ewall%: Function run time (excluding child functions) injection party Formula 1. Direct injection//Open xhprof xhprof_enable (xhprof_flags_memory | XHPROF_FLAGS_CPU); Collect Data register_shutdown_function (function () {$xhprof _data = xhprof_disable () after the program ends; Let the data collection program run in the background if (function_exists (' fastcgi_finish_request ')) {fastcgi_finish_request (); }//Save Xhprof Data ...}); 2. FPM Configuration Injection Vi/usr/local/php7/etc/php-fpm.ini Modify configuration: Auto_prepend_file =/opt/htdocs/xhgui/external/h Eader.php 3. Nginx injected Fastcgi_param php_value "auto_prepend_file=/opt/htdocs/xhgui/external/header.php";
PHP from basics to advanced summary