PHP

  • PHP garbage collection mechanism

    • PHP uses the reference Counting GC mechanism
    • Each object contains a reference counter refcount, and each reference connected to the object increments the counter by one. When reference leaves the living space or is set to NULL, the counter decreases by 1. When an object’s reference counter reaches zero, PHP knows that you no longer need to use the object, freeing up its memory
  • Session and Cookie (Tencent Cloud side)

    • The difference between
      • Storage location: The Session is saved on the server, and the Cookie is saved on the client
      • Storage format: Session is stored on the server in the form of an object, and Cookie is stored on the client in the form of a string
      • Purpose: Cookies are suitable for saving user’s personal Settings, hobbies, etc. Session is suitable for customer authentication
      • Path: Sessions cannot be distinguished between paths. During the same user’s visit to a website, all sessions can be accessed from any place. If the path parameter is set in the Cookie, the cookies in different paths of the same website can not be accessed to each other
      • Security: Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used
    • contact
      • A Session needs cookies to work. If the client disables cookies completely, the Session is invalid! A Session is a server-side storage space maintained by the application server. When users connect to the server, the server generates a unique SessionID and uses this SessionID as an identifier to access the Session storage space on the server. The SessionID data is saved to the client using cookies. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process is done without developer intervention. So once the client disables the Cookie, the Session is also invalidated
  • The static and global keywords inside the function

    • Static is a static variable that exists in a local function and is initialized only once. When used again, the result of the last execution is used. As counts, internal program caches, singleton patterns are useful
    • The global keyword, referring to global variables, is used extensively in wordpress, such as procedural development
    • Static a static method that is a member of a class but can be used directly without instantiating the class
    • GLOBAL Uses globally-scoped variables inside functions, such as GLOBAL[‘a’]
  • What are the restrictions on subclasses overwriting protected methods of their parent? Or are there any rules to follow

    • Final class methods cannot be overridden by subclasses
    • Whether PHP overrides a superclass method is determined only by whether the method name is the same.
    • When overridden, the access level can only be equal to or less than the parent class’s unpromoted access level
  • Should I add to the end of the PHP file? > < p style = “max-width: 100%; clear: both; min-height: 1em;

    • Prevent include and require from referring to a file, including possible carriage returns and Spaces at the end of the file
    • Other functions must be called without any output, resulting in undesirable results
  • What are the methods for downloading web images using PHP?

    • 1.file_get_contents
    • 2. Readfile Reads the content
    • 3. Fopen series functions
    • 4.curl
  • What is the difference between the statements include and require? To avoid including the same file more than once, what statements can be used instead of them (Tencent Cloud side)

    • Include produces a warning, while require produces an error interrupt directly
    • Require is loaded before run
    • Include is loaded at run time
  • Describe the access permissions for private, protected, and public modifiers

    • Private: Private member, accessible only inside the class
    • Protected: Protected members that can be accessed within the class and in inherited classes
    • Public: Public member, fully public, no access restrictions
  • How does the __autoload() method work

    • The basic condition for using this magic function is that the name of the class file must be the same as the name of the class
    • When the program executes to instantiate a class, the __autoload() function is automatically executed if the class file is not introduced before instantiation
    • This function will find the path of the class file based on the name of the instantiated class. If the class file does exist in the path, it will execute include or require to load the class. Then the program will continue to execute, if the file does not exist in the path, an error message is displayed
    • Using auto-loaded magic functions eliminates the need to write many include or require functions
    • spl_autoload_register
  • Regular expression

    • General atoms: \d: decimal 0 to 9, \d: invert, \W: digits, letters, underscores, \W: invert, \S: blank, \S: except blank
    • Metacharacters:.: Any character except newline. *: matches the preceding content 0, 1, more than,? : match the content appears in front of zero, one, ^ : must begin with it, $: must end with it, + : one or more times, {n} : n times, {n,}, {n, m}, [], (),
    • Fixed modes: I: case insensitive, U: remove greedy mode, x: ignore whitespace
    • The sample
      //demo1
      $str = 'Chinese';
      $pattern = '/[\x{4e00}-\x{9fa5}]+/u';
      preg_match($pattern.$str.$match);
      var_dump($match); //demo2 // The 11-digit mobile phone number starting with 139$str = '13982929292';
      $pattern = '/^139\d{8}$/';
      preg_match($pattern.$str.$match);
      var_dump($match); //demo3 // Match SRC values in all img tags$str = '< img Alt = "jiaojia village" id = "sanhuan" SRC = "langbei. JPG" / >';
      $pattern = '/
                
                 /i'
                *?>;
      preg_match($pattern.$str.$match);
      var_dump($match);
      Copy the code
  • File and directory processing

    • Open mode fopen

      • R Read-only mode, the file pointer to the file header
      • The r+ read/write mode is turned on, and the file pointer points to the file header
      • W Write mode is turned on, the file pointer points to the file header and the file size is cut to zero. If the file does not exist, try to create it
      • The w+ read/write mode is turned on, the file pointer points to the file header and the file size is cut to zero. If the file does not exist, try to create it
      • A Write mode is enabled, and the file pointer points to the end of the file. If the file does not exist, try to create it
      • Open a+ read/write mode and point to the end of the file. If the file does not exist, try to create it
    • Write a function

      • Fwrite () Writes to a file (can be used safely for binary files)
    • Read function

      • Fread () reads the file
      • Fgets () reads a line from the file pointer
      • Fgetc () reads characters from the file pointer
      • Close function: fclose()
    • Functions that do not need to be opened by fopen

      • file_get_contents()
      • file_put_contents()
    • Other reading functions

      • File () reads the entire file into an array
      • Readfile () outputs the file
    • The sample

      //demo1
      $file = './hello.txt'; // Open the file$handle = fopen($file.'r'); // Read out the contents of the file and add hello world at the beginning$content = fread($handle, filesize($file)); // Return the concatenated string to the file$content = 'hello world'.$content;
      fclose($handle);
      $handle = fopen($file.'w');
      fwrite($handle.$content);
      fclose($handel);
      
      //demo2
      $dir = './test'; // Open directory // Read files in directory // Continue to open directory if the file type is directory // Read files in subdirectory // If the file type is file, print the file name // close directoryfunction loopDir($dir)
      {
          $handle = opendir($dir);
          while(false! = = ($file = readdir($handle)))
          {
              if($file! ='. ' && $file! ='.. ')
              {
                  echo $file."\n";
                  if (filetype ($dir.'/'.$file) = ='dir')
                  {
                      loopDir($dir.'/'.$file);
                  }
              }
          }
      }
      loopDir($dir);
      Copy the code
  • Magic methods

    • In view of the variable __get (), __set (), __isset (), __unset () through the __get (), __set (), __isset (), __unset () respectively to no attribute assignment, read, whether attribute set, destroy properties. You can define an array variable in a class to hold the names and values of all properties
    • For method __call(),__callstatic() uses __call(),__callstatic() to make calls to nonexistent and static methods. __callstatic must also be declared static. When writing __call() methods, we can add value arguments to operate on different function names. PHP uses -> to read a class property or call a method, and :: to read a static property. Superclass methods also need to use:
    • The __toString method is called automatically when an object is converted to a string, such as when an object is printed with echo. If the class does not implement this method, the object cannot be printed with echo
    • An __invoke class that treats a class as a function output cannot be called directly as a function, such as echo $object(); If the object class defines an __invoke() function, the __invoke() function is automatically called when the class is called as a function
  • Interfaces and abstract classes

    • An abstract class
      • Abstract classes are classes that have the abstract keyword prefixed to class and have abstract methods (the abstract keyword prefixed to the function keyword)
      • Abstract classes cannot be instantiated directly. An abstract class defines (or partially implements) only the methods that a subclass needs. A subclass can externalize an abstract class by inheriting it and implementing all of its abstract methods
      • If a subclass needs to be instantiated, it must implement all the abstract methods in the abstract class. A subclass is an abstract class if it does not fully implement all of the abstract methods in the abstract class
      • If B implements the abstract method abstract_func(), then the access control of an abstract_func() method in B cannot be more stringent than that of an abstract_func() method in A
    • interface
      • The mouth is a pure template. Interfaces define functionality, not implementation content. Interfaces are declared with the keyword interface
      • Interfaces are completely abstract and can only declare methods, and only public methods, not private and protected methods, method bodies, and instance variables. Interfaces, however, can declare constant variables
      • Any class that implements an interface implements all the methods defined in the interface
    • The same
      • Both are abstract classes and cannot be instantiated
      • Both the Nterface implementation class and the Abstract class subclasses must implement declared abstract methods
    • The difference between
      • Interface emphasizes the implementation of a particular function, while Abstract class emphasizes ownership
  • An array of

    • Intersection array_intersect
    • And set the array_merge
    • Difference set the array_diff
  • echo,print,print_r,var_dump

    • Difference between Echo and print
      • First, echo and print are not strictly functions; they are both language constructs. They can output only strings, ints and ints. You cannot print compound and resource data
      • Echo can print multiple variables consecutively, whereas print can print only one variable at a time
    • Var_dump () and print_r()
      • Both can print compound variables like arrays and objects
      • Print_r () only prints easy-to-understand information, and print_r() moves the pointer to the end of the array when printing it. Using reset() returns the pointer to the beginning. Var_dump () prints not only compound types of data, but also resource type variables. Var_dump () outputs more detailed information, which is often used during debugging
  • The HTTP status code

    • 200 (Success) The server has successfully processed the request. Typically, this means that the server has provided the requested web page
    • The page for request 301 (Permanent move) has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location
    • The 302 (temporary mobile) server currently responds to requests from web pages in different locations, but requesters should continue to use the original location for future requests
    • 403 (Forbidden) The server rejects the request
    • 404 (Not found) The server could not find the requested page
    • 500 (Server internal error) The server encountered an error and could not complete the request
    • 502 (Error Gateway) server, acting as gateway or proxy, received invalid response from upstream server
    • 503 (Service unavailable) The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state
    • 504 (Gateway Timeout) The server acted as a gateway or proxy, but did not receive the request from the upstream server in time
  • Redis connect and pconnect

    • Connect: The connection is released after the script ends
    • Pconnect: The connection is not released after the script ends and remains in the php-fpm process. Each php-FPM process occupies one connection, which is released when the php-FPM process ends, so using pconnect instead of Connect reduces the cost of frequently establishing Redis connections
    • If your application/service can have separate processes and use its own memory, it can safely use PConnect
  • Ob cache

    • Ob_start () enables caching
    • Ob_get_contents () gets the contents of the buffer
    • Ob_clean () deletes the contents of the buffer
    • Ob_get_clean () gets and then deletes the buffer contents
  • PHP7 new features

    • Type declaration
    • Set_exception_handler () no longer guarantees that an Exception object is received
      • Many fatal errors, as well as recoverable fatal errors, are converted to exceptions for handling. These exceptions inherit from the Error class, which implements the Throwable interface
    • New operator ‘<=>’
    • Add operator “??”
    • Define () defines an array of constants
    • Anonymous functions
      $anonymous_func = function() {return 'function'; };echo $anonymous_func(a); / / outputfunction
      Copy the code
    • Namespace reference optimization
  • Array implementation

    • PHP uses HashTable to store key-value pairs, but has some additional design for HashTable to ensure array order, maintains a k-V correspondence, can quickly retrieve values by key, and the search time is O(1).
      • Key: Can be a number or a string
      • Value: indicates the target data
      • Bucket: storage unit of hashtable, a container used to store K-V
      • Slot: indicates a slot. A slot can have one or more buckets
      • PHP resolves hash conflicts by linking buckets in the same slot in a linked list
    • Improvements to hashtable in PHP
    • The first is to add the H field in the bucket
    • Then split the hash function into hash1 and hash2
      • Hash1: Maps key to h value
      • Hash2: Maps the h value to the index value in slot
      • Purpose of splitting
        • If the key can be a string or a number, h in the bucket is the key of a number and key is the key of a string
        • The hash value (h) generated with hash1 can be used to speed up the comparison of strings between keys. Since the calculated hash value is different, each insertion lookup does not need to check for duplicate keys, so it can be used to improve the speed
    • All keys in the bucket are string keys
  • Seconds kill

    • mysql
      • Optimistic locking
      • Pessimistic locking
    • redis
      • stand-alone
        • Lock + descby
      • The cluster
        • lua
    • rabbitmq
  • A red envelope

    • Randomly generate 10 numbers, sum them up, find the ratio of each number, multiply it by the sum of the red envelopes and you get the money in each red envelope
    • Wife: 100 dollars insert 9 board son, be a train of thought with afore-mentioned actually

other

  • Nginx load balancing can be implemented in several ways

    • Polling (default)
      • Each request is allocated to a different backend server one by one in chronological order. If the backend server goes down, the request is automatically removed
    • weight
      • Specifies the polling probability. Weight is proportional to the access ratio. It is used in the case of uneven back-end server performance
    • ip_hash
    • Url_hash (third party)
      • Requests are allocated based on the hash result of the url accessed so that each URL is directed to the same (corresponding) back-end server, which is more efficient when the back-end server is cached
    • Fair (Third Party)
      • Requests are allocated based on the response time of the back-end server, with priority given to those with short response times
  • What is CGI? What is FastCGI? What is the relationship between php-fpm, FastCGI and Nginx?

    • CGI: is a protocol for data exchange between the common gateway interface Web Server and Web Application
    • FastCGI: FastCGI is like a long-live CGI program that runs forever. CGI is a communication protocol, but a little more efficient than CGI. It is a bridge between applications and WEB servers. Instead of communicating directly with phP-FPM, Nginx hands requests to php-FPM through FastCGI
    • Php-fpm: PHP (Web Application) FastCGI protocol interface program for Web Server, in addition to providing relatively intelligent task management
    • FastCGI is used to improve the performance of CGI programs. Start a master and start multiple workers without parsing php.ini every time. Php-fpm implements the FastCGI protocol and is the process manager of FastCGI. It supports smooth restart and can generate multiple processes in advance when starting
      location ~ \.php$ {
          try_files $uri /index.php =404;
          fastcgi_pass 127.0.0.1:9000;
          fastcgi_index index.php;
          fastcgi_buffers 16 16k;
          fastcgi_buffer_size 32k;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
      }
      Copy the code
  • What is a CSRF attack? XSS attacks? How to prevent?

    • CSRF, cross-site request forgery, where an attacker sends a request disguised as a user’s identity to steal information or compromise a system
      • Basic principle: the user to access A landing site and generate A cookie, then visit site B, if A site is CSRF vulnerabilities, the request of the B site to A web site at this time (this time quite so users access), A website will think that is the user’s request, to site B is A disguise your identity, so called cross-site scripting attacks.
      • CSRF protection:
        • Reasonable specification of API request methods, GET, POST
        • For POST request and token verification, a random code is generated and stored in session. This random code is carried in the form, and the server verifies whether the random code is the same when submitting the request.
    • XSS, cross-site scripting attacks
      • Guard against: Don’t trust any input, filter input
  • Explain Index types

    • System this is a special case of the const join type, and only one row of the table satisfies the condition
    • Const When it is certain that at most there will be a row match, the MySQL optimizer reads it only once before the query, so it is very fast. When the primary key is placed in the WHERE clause, mysql converts the query to a constant (efficient)
    • Eq_ref returns at most one qualified record. Occurs when using a unique index or primary key lookup (efficient)
    • Ref An index access that returns all matches to a single worthy row. Such index access can only occur if a non-unique index or a unique index non-unique prefix index is used. This type differs from eq_ref in that it uses only the left-most prefix of the index in the associative operation, or the index is not UNIQUE or PRIMARY KEY. Ref can be used for indexed columns that use the = or <=> operators.
    • Range scan, a limited index scan. The key column shows which index is used. You can use range when comparing keyword columns with constants using the =, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN, or IN operators
    • Index is the same as full table scan. Only the table is scanned in index order instead of rows. The main advantage is that sorting is avoided, but the overhead is still very high. An overwrite index is being used to scan only the index, which is much cheaper than a full table scan in index order
    • All Worst case, full table scan