Oop is object-oriented programming. Object oriented programming is a computer programming architecture. One of the basic principles of OOP is that a computer program is composed of a single unit or object that can act as a subroutine.

Encapsulation: Also known as information hiding, the separation of the use and implementation of a class, leaving only some interfaces and methods exposed to the outside world, or exposing only some methods for use by developers. Therefore, developers only need to pay attention to how this class is used, rather than the specific implementation process. In this way, MVC division of labor and cooperation can be realized, interdependence between programs can be effectively avoided, and loose coupling between code modules can be realized.

Inheritance: A subclass automatically inherits properties and methods from its parent class, and can add new properties and methods or overwrite some properties and methods. Inheritance increases the reusability of code. PHP only supports single inheritance, which means that a subclass can have only one parent class.

Polymorphism: Subclasses inherit attributes and methods from the parent class and override some of those methods. Polymorphism is a technique in which objects instantiated by multiple subclasses with the same methods can get completely different results when they call the same methods. Polymorphism enhances the flexibility of software.

Easy to maintain, high quality, high efficiency, easy to expand Due to the characteristics of inheritance, packaging, polymorphism, natural design of high cohesion, low coupling system structure, making the system more flexible, easier to expand, and low cost.

2. Advantages of Each framework ThinkPHP:

1. Simplify development, improve efficiency, easy to expand, easy to use, with rich Chinese documents;

2. Strong compatibility of the framework, PHP4 and PHP5 are fully compatible, fully support UTF8 and so on.

3. Suitable for the development of small and medium-sized projects

Disadvantages:

1. Ajax support is not very good;

2. The directory structure is chaotic and takes time to sort out.

3. It is easy to get started, but difficult to learn deeply.

YII advantages

1. Pure OOP

2. Used for large-scale Web applications

3. The model is easy to use

4. The development speed is fast and the operation speed is fast. Excellent performance and rich features

5. Use a command-line tool.

Disadvantages:

1. Less guidance and consideration for the Model layer

2. Fewer document instances

3. Too much English

4. Require PHP technical proficiency, OOP programming to be proficient!

5. A View is not an ideal View. An ideal View might just be HTML code, not PHP code.

CodeIgniter advantages: simple, simple configuration, all configuration using PHP script configuration, high execution efficiency, fast and concise, not much code, high execution performance, simple framework, easy to use, low learning cost, detailed documentation; With a number of libraries that are easy to use, the framework is suitable for small applications. Disadvantages: Internal structure is too chaotic, although easy to use, but lack of scalability. Think of the Model layer simply as database operations. The framework is a bit simple and can only meet the needs of small applications, slightly less suitable for medium-sized applications.

The Laravel framework is designed with advanced thinking and is ideal for applying various development patterns. As a framework, it has everything ready for you. The laravel framework’s greatest strength and excellence is its combination of relatively new features of PHP, as well as various design patterns, Ioc patterns, dependency injection, and so on.

  • Powerful REST Router: Can be called with a simple callback function, quickly binding controller and Router
  • Artisan: Command-line tools that automate many manual tasks
  • Inheritable templates that simplify view development and management
  • Blade Templates: Render faster
  • ORM operates the database
  • Migration manages databases and version control
  • Composer is also a highlight
  • Testing is also powerful. Disadvantages: it is based on a component-based framework, so it is bloated

3. Database optimization

Secondary structure layer: Web server adopts load balancing server, mysql server adopts master-slave replication, read/write separation from storage layer: Appropriate storage engine is adopted, and three paradigms are adopted from design layer: Mysql cache is enabled from THE SQL statement layer: Under the same results, SQL statements with high efficiency and high speed save resources are used to perform load balancing:

  • HTTP redirection implements load balancing
  • DNS Load Balancing
  • Reverse proxy load balancing reference links: www.cnblogs.com/tuojunjie/p…

The basis for data replication between MySQL is binary log files. The Master logs changes to the binary log. Slave copies the binary log of the Master to its Relay_log. The Slave reworks events in the Relay_log to alter data that reflects itself

Mysql Primary/secondary replication Purpose Real-time DISASTER recovery for read/write separation during failover and backup of query services to avoid service impact

The primary/secondary deployment must be as follows: Binlog log is enabled for the primary library (set the log-bin parameter). The primary and secondary server ids are different. The secondary server can communicate with the primary library

Principle: Primary: log Dump thread transmits binlog. From: THE I/O thread reads the binlog and writes it to the relay log file. The SQL thread reads the binlog from the relay log file and persists it

Master-slave replication links: blog.csdn.net/wangyuanjun…

4. How to deal with load and high concurrency

  • HTML static
  • Image server separation
  • Database cluster and database table hashing and caching: the concurrent connection of the database is 100, a database is far from enough, you can start from read and write separation, master and slave replication, database cluster. In addition, to minimize database access, you can use cached databases such as memcache and Redis.
  • Load balancing: The maximum concurrent connection of Apache is 1500. Only servers can be added. You can start from hardware, such as F5 server. Of course the cost of hardware is relatively high, we tend to start from the software side.

1. Flow optimization

(1) Anti-theft chain processing (removing malicious requests)

(2) Control the download of large files.

(3) Check whether the server hardware is sufficient to support the current traffic

(4) Use traffic analysis and statistics software

(5) try to use static pages, cache

2. Front-end optimization

(1) Reduce HTTP requests [merge CSS, JS, etc.]

(2) Add asynchronous request (first do not show all data to the user, the user triggers an event, will be asynchronous request data)

(3) Enable browser caching and file compression

(4) the CDN acceleration

(5) Establish an independent image server (reduce I/O)

3. Server optimization

(1) Page static

(2) Concurrent processing

(3) Queue processing

4. Database optimization

(1) Database cache

(2) Sub-database sub-table, partition

(3) Read and write separation

(4) Load balancing

5. Web server optimization

(1) NGINx reverse proxy to achieve load balancing

(2) LVS load balancing original text: blog.csdn.net/m_nanle_xia…

Pessimistic lock: usually said “one lock two check three update” refers to the use of pessimistic lock. The database itself is required to provide support through the usual select… The for Update operation implements pessimistic locking. Select for UPDATE implementation and support vary from database to database, and all scanned rows are locked during select for UPDATE execution, which can cause problems. Therefore, if you use pessimistic lock in mysql, make sure that the index is crossed, not the full table scan.

Optimistic lock: Just pick up the lock at the end of the business operation that actually needs to update the data. No special database support is required. It is common practice to add a version number or timestamp to the data that needs to be locked:

1. SELECT data AS old_data, version AS old_version FROM... ; 3. UPDATE SET data = new_data, version = new_version WHERE version = old_versionif(Updated row > 0) {// Optimistic lock obtained successfully, operation complete}else{// Optimistic lock acquisition failed, rollback and retry}Copy the code

High concurrency: www.cnblogs.com/phpper/p/67…

5, mysql default port

3306  
Copy the code

Obtaining an IP Address

The client side -$_SERVER['REMOTE_ADDR']; Server side -$_SERVER["SERVER_ADDR"]; Gethostname -- gethostname ip2long -- convert IPV4 string Internet protocol to long integer number long2ip -- convert long integer to string form dot Internet standard format address (IPV4) example:$ip = gethostbyname('www.baidu.com'); / / 14.215.177.39$ip2long = ip2long($ip); / / 249016615Copy the code

Encoding the conversion function

Iconv('utf-8'.'gb2312'.$str);
Copy the code

6, architecture class of things database read-write separation, master/slave replication and clustering.

Nginx load balancing

Redis cluster and master/slave

7. Differences between Session and Cookie Cookie data is stored in the browser of third-party applications, and session data is stored on the server.

Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used.

Sessions are stored on the server for a certain amount of time. Session uses a new mechanism to keep synchronization with clients, independent of client Settings. It will occupy server resources and increase the load on the server side. Especially when there are many concurrent users, a large number of sessions will be generated and the performance of the server will be affected. In view of reducing the performance of the server, cookies should be used. Session storage is more sensitive and stored as a file on the server, so it still poses a security risk.

A single cookie can hold no more than 4K of data, and many browsers limit the number of cookies a site can hold to 20.

The SESSION is stored on the server and the COOKIE is stored on the client. Session is secure, cookie can be modified by some means, not secure. Sessions rely on cookies for delivery. After cookies are disabled, the session can be used. Generate the sessionID in the file storing the session, send the sessionID to the page for session sharing through get, read the sessionID, and obtain data from the session.

Disable cookies and use the session method

  1. Set “session.use_trans_sid = 1” in the php.ini configuration file, or enable the “–enable-trans-sid” option at compile time to have PHP automatically pass the session ID across pages.
  2. Manually pass the Session ID through the URL and hide the form.
  3. Save Session IDS in files, databases, etc., and call them manually during page crossing.

Session_start (); session_start(); session_start(); The code is preceded by the code Session ID(the passed Session ID).

Therefore, personal advice: store important information such as login information as SESSION and other information in cookies if necessary

Abstract classes: Any class that has at least one method declared as abstract must be declared as abstract. Abstract methods have no method body. When inheriting an abstract class, the subclass must define all the abstract methods in the parent class. In addition, access control for these methods must be the same (or looser) as in the parent class. Interface: defined by the interface keyword, methods in the interface also have no method body. You cannot declare variables in an interface, but you can declare class constants. It is a feature of the interface that all methods defined in the interface must be public. Note that it is permissible to define a constructor in an interface. This can be useful in some scenarios, such as factory mode. To implement an interface, use the implements operator. All methods defined in the interface must be implemented in the class or a fatal error will be reported. Class can implement multiple interfaces, separating the names of the interfaces with commas.

An abstract class

<? php abstract class Animal { public$name;
  abstract public function eat($food); }? > <? php class Whale extends Animal { publicfunction __construct() {
    $this->name = "Whale";
  }
  public function eat($food) {
    echo $this->name . " eat " . $food . ".\n";
  }
}
?>

<?php
  $whale = new Whale();
  $whale->eat("fish"); ? >Copy the code

interface

<? php interface IAction { publicfunction eat($food);
  public functionswim(); }? > <? php class Whale implements IAction { publicfunction eat($food) {
    echo "Whale eat " . $food . "\n.";
  }
  public swim() {
    echo "Whale is swimming.\n";
  }
}
?>

<?php
  $whale = new Whale();
  $whale->eat("fish"); ? >Copy the code

interface Eat
{
    public function eat();
}

class Pig implements Eat
{
    public function eat()
    {
        echo 'pig eat ... ';
    }
}

class Cat implements Eat
{
    public function eat()
    {
        echo 'cat eat .... ';
    }
}

class Test
{
    function aa(Eat $animal)
    {
        $animal->eat(); }}$test = new Test();
$pig = new Pig();
$cat = new Cat();
$test->aa($pig);
$test->aa($cat);
Copy the code

Abstractions are used for different things, while interfaces are used for the behavior of things. For example, aquatic life is the abstract concept of whales, but aquatic life is not the behavior of whales. Eating is the behavior of whales. For large projects, objects are implemented by inheritance from basic abstract classes whose methods are often defined by interfaces. In addition, it is recommended to use interfaces rather than direct assignments or other methods to change the properties of objects.

First normal form (1NF) : fields are atomic and cannot be divided. All relational database systems meet the first normal form, in which the fields in database tables are single-attribute and non-divisible. For example, in the first name field, the first and last names must be considered as a whole. It is impossible to distinguish between the first and last names. If the first and last names are to be distinguished, they must be designed as two separate fields.

Second Normal Form (2NF) : Each instance or row in a database table must be uniquely distinguishable. It is often necessary to add a column to a table to store the unique identity of each instance. This unique attribute column is called the primary key or primary key.

Third normal Form (3NF) : One database table is required not to contain non-primary keyword information that is already contained in other tables.

Summary: 1, each column has only one value (field is not separable) 2, each row can be distinguished. 3. Each table does not contain non-primary key information that other tables already contain.

The database without redundancy is not necessarily the best database. Sometimes, in order to improve the operation efficiency and read performance, it is necessary to reduce the standard of the paradigm and reserve the redundant data appropriately. Follow the third normal form in conceptual data model design, and lower the standard to consider in physical data model design. Reducing the normal form is to increase the number of fields, reducing the correlation of queries and improving query efficiency, because the percentage of queries in database operations is much larger than the percentage of DML. However, antiformalization must be moderate and be adjusted on the basis of satisfying the three paradigms.

One is table locking (MyISAM storage engine), and the other is row locking (InnoDB storage engine). 1. The storage engine is used differently. Active data, can use Innodb, can have better update speed. 2. Carry out more slave library configuration for cold data, because more operations are query, so as to speed up the query. For hot data, there can be relatively more horizontal sub-table processing of the main library. 3, for some special active data, you can also consider the use of memcache, Redis and other caches, such as accumulated to a certain amount before updating the database.

11. Database engine

InnoDB: transaction support, foreign key support, crash repair capability and concurrency control. If you need high transaction integrity (such as banks) and concurrency control (such as ticketing), InnoDB has great advantages. If you need a database with frequent updates and deletes, you can also choose InnoDB because it supports commit and rollback transactions.

MyISAM: Fast data insertion, low space and memory usage. If the table is primarily used for inserting new records and reading records, then choosing MyISAM can be efficient for processing. It can also be used if the application has low requirements on integrity and concurrency.

MEMORY: All data is stored in MEMORY. The data processing speed is fast, but the security is not high. If you need fast read and write speeds with low data security requirements, choose MEMOEY. It has requirements on the size of the table and cannot create tables that are too large. Therefore, this type of database is only used in relatively small database tables.

Merge: Used for logging and data warehousing

Archive: Used for logs. Only select and INSERT files are supported. Indexes are not supported.

Note that the same database can also use tables from multiple storage engines. If a table requires high transaction processing, use InnoDB. In this database, the tables with high query requirements can be selected for MyISAM storage. If the database needs a temporary table to query, the MEMORY storage engine can be used.

If MySQL cannot determine the range to be scanned when executing a SQL statement, InnoDB will also lock the entire table. For example, update table set num=1 where name like “a%”

This means InnoDB will still lock tables in uncertain ranges.

InnoDB must be used for two things:

1) InnoDB is used for high reliability or transaction processing. This is a must.

2) InnoDB data engine is created when table updates and queries are fairly frequent and the chances of table locking are high.

In contrast, MyISAM is used in the following scenarios:

1) Do a lot of count calculations. Such as some log, the investigation of the business table.

2) Insert modification is not frequent, query is very frequent.

12. Database Transactions A transaction is a series of operations performed as a single logical unit of work, which can be viewed as a collection of SQL statements in a single unit. You either do it all or you don’t. Without concurrency control, exceptions such as dirty reads, non-repeat reads, phantom reads, and missing modifications may occur. A, Atomacity (all procedures are either executed or none are executed. C, Consistency (e.g., Total amount before and after transfer remains the same) I, Isolation (Data does not change as long as transactions are not committed) D, Durability (Transaction commit, must change)

13. Transaction isolation is based on locks. In DBMS, database locks can be divided into row level locks (INNODB engine), table level locks (MYISAM engine) and page level locks (BDB engine).

Row-level locking is the most fine-grained lock in Mysql. It only locks the current row. Row-level locking can greatly reduce conflicts in database operations. Its locking particle size is the smallest, but the locking cost is also the largest. Row-level locks are divided into shared locks and exclusive locks. It is characterized by large overhead and slow locking; Deadlocks occur; The lock granularity is the lowest, the probability of lock conflict is the lowest, and the concurrency is the highest.

Table-level lock is the lock with the largest granularity in MySQL. It locks the entire table in the current operation. It is simple to implement and consumes less resources, and is supported by most MySQL engines. Both MYISAM and INNODB support table-level locking. Table level locks are classified into shared table read locks (shared locks) and exclusive table write locks (exclusive locks). It is characterized by low overhead and fast locking; No deadlocks occur; The lock granularity is large, and the probability of lock conflict is high and the concurrency is low.

Page-level locking is a kind of lock whose granularity is between row-level locking and table-level locking in MySQL. Table level locking is fast but has many conflicts, while row level locking is slow but has few conflicts. So the page level is folded, locking adjacent sets of records at a time. The overhead and locking time are between table locking and row locking. Deadlocks occur; The locking granularity is between table locks and row locks, and the concurrency is average

14. Partition sub-table

Partitioning: To store the files and indexes of a table in different physical files. Table partitioning refers to splitting a table in a database into smaller, manageable parts according to certain rules. Logically, there is only one table, but the underlying table is composed of multiple physical partitions.

Split table: refers to the partition of a table into multiple different tables according to certain rules, each small table is a complete table, all corresponding to three files (MyISAM engine: one. MYD data file,.myi index file,.frm table structure file). For example, record user orders into multiple tables based on time.

Partition table and partition difference: implementation: partition from the logical speaking only one table, and partition table is to decompose a table into many tables.

Data processing: after the sub-table data are stored in the sub-table, the general table is only a shell, access data occurs in a sub-table inside. Partition does not exist the concept of partition table, partition only store data files into many small pieces, partition table is still a table, data processing or by their own to complete.

Improved performance: The concurrent capability of a single table is improved and the disk I/O performance is also improved. Partition breaks the disk I/O bottleneck, and wants to improve the disk read and write ability to increase mysql performance. At this point, partitioning and sub-table test focus is different, sub-table focus is to access data, how to improve mysql concurrency; Partition, how to break the disk read and write ability, so as to achieve the purpose of improving mysql performance.

The difficulty of implementation: There are many ways to divide tables. Merge is the easiest way to divide tables. This approach is about as easy as partitioning and transparent to the program code. If it is to use other sub-table way is more trouble than the area. Partition implementation is relatively simple, the establishment of partition table, with the establishment of ordinary table is no different, and is transparent to the code side. The purpose of partitioning and table splitting is to reduce the execution burden of the database and stabilize SQL performance.

Partition The partition types supported by mysql include Range, List, Hash, and Key

CREATE TABLE user (
	id INT NOT NULL auto_increment,
	username VARCHAR (10),
	PRIMARY KEY (id)
) ENGINE = INNODB charset = utf8 PARTITION BY RANGE (id)(
	PARTITION user_1 VALUES less than (10),
	PARTITION user_2 VALUES less than (20),
	PARTITION user_3 VALUES less than MAXVALUE
);
Copy the code

Table partitioning benefits: 1) Partitioned table data can be distributed across different physical devices, making efficient use of multiple hardware devices. 2) Can store more data than a single disk or file system 3) Optimize queries. When partitioning conditions are included in a WHERE statement, you can scan only one or more partitioned tables to improve query efficiency; When sum and count statements are involved, they can also be processed in parallel across multiple partitions, and the results can be summarized. 4) Partition tables are easier to maintain. For example, if you want to delete a large amount of data in a batch, you can clear the entire partition. 5) You can use partitioned tables to avoid some special bottlenecks, such as mutual exclusive access of single indexes in InnoDB, inode lock contention in ext3, etc.

Partition restrictions:

  • The primary key or unique index must contain partitioned fields such as primary key (ID,username), but innoDB’s large component performance is poor.
  • Most of the time, you don’t need to use primary keys when you’re using partitions, because that can affect performance.
  • Partitioning can only be done by fields of type int or expressions that return type int, usually using functions such as year or to_days (mysql 5.6 is starting to loosen restrictions).
  • Each table has a maximum of 1024 partitions, and multiple partitions consume a lot of memory.
  • Partitioned tables do not support foreign keys, and the associated logical constraints need to be implemented programmatically.
  • Indexes may become invalid after partitioning. Therefore, verify the partitioning feasibility.

table

CREATE TABLE 'member' (' id 'int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT' ', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1; Insert into member(name) values(member(name);'a'); insert into member(name) select name from member; // Create two sub-tables tb_member1,tb_member2 DROP TABLE IF EXISTS tb_member1; CREATE TABLE tb_member1 ( `id` INT (10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR (20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT' ', PRIMARY KEY (`id`) ) ENGINE = MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1; DROP TABLE IF EXISTS tb_member2; CREATE TABLE tb_member2 LIKE tb_member1; // Create a primary TABLE tb_member DROP TABLE IF EXISTS tb_member; CREATE TABLE tb_member ( `id` INT (10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR (20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT' ', PRIMARY KEY (`id`) ) ENGINE = MERGE UNION = (tb_member1, tb_member2) INSERT_METHOD = LAST CHARSET = utf8 AUTO_INCREMENT = 1; Insert into tb_member1(id, name) select id,name from memberwhere id%2=0;
insert into tb_member2(id, name) select id,name from member where id%2=1;
Copy the code

Problems existing in sub-tables:

  • Join problems across libraries and tables
  • Additional data management burden and data operation pressure (data positioning problems and repeated execution of data adding, deleting, modifying and checking)

There are several common ways to divide tables:

  • Pre-estimate the amount of data in a large table, divide all of them into fixed number tables (modulo autoincrement ID, modulo autoincrement ID mantissa, hash a field)
  • Data that grows faster in time can be broken down by time (day, month, year, etc.)
  • Split by fixed number of rows per table
  • Migrate long-ago data to a history table

Table link: www.cnblogs.com/johnnyzhang…

MySQL > select * from ‘MySQL’; Composite index a composite index consisting of two or more columns, using only a portion of the index, or more specifically, the leftmost portion (left-most first). That is, when the first part of the value is used as the index cover index query, only the index is read and the data is obtained, without the need to query the related table twice. For an index cover query, explain is used, and extra is displayed as using index to judge

Suppose we create sequential indexes: C1, C2, C3, and C4

  • In equivalent queries, changing the order of the index columns does not affect the explain results because mysql is optimized, but it is recommended to write SQL statements based on the order of the index columns.
  • When Using Order BY, pay attention to index order, constants, and situations that might lead to Using filesort
  • The index column to the right of the range is invalid, but the index at the current location of the range is valid
  • C1, C2, C3, C4. If C3 has a range,c4 will fail. If C4 has a range, there are no invalid index columns and all indexes are used.
  • In the best left prefix rule, if the left-most index fails, all subsequent indexes fail.
  • Use the best left prefix rule: no break in the middle, use the C1 and C2 indexes (lookup), and the C3 index column is used during sorting.
  • Group by easily generates Using temporary

Popular understanding of formula:

Full value match my favorite, most left prefix to obey;

The first brother cannot die, the middle brother cannot be broken;

Less calculation on index column, all invalid after range;

LIKE 100 write most right, cover index does not write star;

Unequal null values and OR, index failures should be used sparingly.

See also: www.cnblogs.com/morewindows…

Index length calculation: 1. If not NULL is not set for all index fields, add one byte. 2. The fixed-length field contains four bytes int, three bytes date, and n characters char(n). 3. For varchar(n), n characters + 2 bytes. 4. The number of bytes occupied by a character varies according to character sets. Latin1-encoded, a character occupies one byte, GBK encoded, a character occupies two bytes, utF8 encoded, a character occupies three bytes.

16,

/ / the connection$dbhost = 'localhost'; // mysql server host address$dbuser = 'root'; // mysql user name$dbpass = ' '; // mysql user name password$conn = mysqli_connect($dbhost.$dbuser.$dbpass);
if (!$conn) {
    die('Could not connect: ' . mysqli_error());
}
echo 'Database connection successful! '; Mysqli_query (mysqli_query($conn , "set names utf8");
 
$sql = 'SELECT id, name FROM user';
 
mysqli_select_db($conn.'test');
$retval = mysqli_query($conn.$sql);
if(!$retval)
{
    die('Cannot read data:' . mysqli_error($conn));
}

while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
    print_r($row); Mysqli_free_result ()$retval);
mysqli_close($conn);
Copy the code

$sort = [$sort]; $sort = [$sort]; Bubble Sort (from small to large)

Second: in the first round for the first time: 1,6,2,4,5,3:1,2,6,4,5,3 third: 1,2,4,6,5,3 fourth: 1,2,4,5,6,3 fifth: 1,2,4,5,3,6

Second: the first: 1,2,4,5,3,6 second: 1,2,4,5,3,6 third: 1,2,4,5,3,6 fourth: 1,2,4,3,5,6

The third round: first: 1,2,4,3,5,6 second: 1,2,4,3,5,6 third: 6

Round 4: first time: 1,2,3,4,5,6 second time: 1,2,3,4,5,6

Round 5: first time: 1,2,3,4,5,6

<? php$arr = [6, 7, 3, 5, 9, 10, 1];
$length = count($arr); / / wheelfor ($i = 1; $i < $length; $i+ +) {/ / timefor ($j = 0; $j < $length - $i; $j{+ +)if ($arr[$j] > $arr[$j + 1]) {
            $tmp = $arr[$j];
            $arr[$j] = $arr[$j + 1];
            $arr[$j= + 1]$tmp; }}}echo '<pre>';
print_r($arr);
Copy the code

Iterate through the code for folders and other underlying files

function getAllFile($dir) {
    $allFileArr = [];
    if (is_dir($dir)) {
        $res = opendir($dir);
        while ($row = readdir($res)) {
            if ($row= ='. ' || $row= ='.. ') {
                continue;
            }
            if (is_file($dir . '/' . $row)) {
                $allFileArr[] = $row;
            } else if (is_dir($dir . '/' . $row)) {
                $allFileArr[$row] = getAllFile($dir . '/' . $row);
            }
        }
        closedir($res);
    }
    return $allFileArr;
}

$dir = 'E:\ruanjian\wamp64\www\learn';
echo '<pre>';
print_r(getAllFile($dir));
Copy the code

19. How to prevent SQL injection, XSS and CSRF attacks

SQL injection: mysqli_real_escape_string() escapes key characters; CSRF attack: Cross-site attack. Prevent: token, verification code XSS attack: alert Prints some cookie information; Filter out key strings such as <>. Decode the data and filter out dangerous labels, attributes and events; DOM XSS occurs primarily as a result of using EVAL in JS, so the eval statement should be avoidedCopy the code

XSS hazards

  • Steal cookies through Document. cookie
  • Using JS or CSS to break the normal structure and style of the page
  • Traffic hijacking (locating to another page by accessing a segment with window.location.href)
  • Dos attack: The use of reasonable client requests to occupy too many server resources, so that legitimate users cannot get a response from the server.
  • Use iframe, Frame, XMLHttpRequest, or the above Flash method to perform administrative actions as the (attacked) user, or perform general operations such as tweeting, adding friends, and sending private messages.
  • By taking advantage of the fact that the domain that can be attacked is trusted by other domains, the trusted source requests some operations that are not normally allowed, such as improper voting activities.

20. Detailed process of PHP program work

PHP works as a collaborative process between Apache, PHP, and browsers:

① When the user enters the name of the PHP page to visit in the browser address, and then press Enter, the PHP request will be triggered, and the request will be sent to the PHP support WEB server (Apache).

② The WEB server (Apache) accepts the request and determines if it is a PHP request based on its suffix. The WEB server (Apache) retrieves the PHP application that the user wants to access from the hard disk or memory and sends it to the PHP engine program.

③ THE PHP engine program will scan the files sent by the WEB server (Apache) from beginning to end and read from the background according to the command, process the data, and dynamically generate the corresponding HTML page.

④ The PHP engine generates HTML pages and returns them to the WEB server (Apache). The WEB server (Apache) returns the HTML page to the client browser, and the final complete page is displayed through the browser.

HTTP An HTTP request consists of three parts: the request line, the request header, the blank line, and the request body. The HTTP response consists of four parts: the status line, the message header, the blank line, and the response body. The first part: status line, which consists of HTTP protocol version number, status code, and status message. The first behavior status line, (HTTP/1.1) indicates HTTP version 1.1, status code 200, and status message (OK)

The second and third lines of the message headers, Date: the Date and time the response was generated. Content-type: SPECIFIES the MIME Type of HTML(text/ HTML) and the encoding Type is UTF-8. Part 3: Blank lines. Blank lines after the message header are required. The HTML following the blank line is the response body.

GET, POST, HEAD version 1.1 also added a number of verb methods: PUT, PATCH, HEAD, OPTIONS, DELETE

HTTP request header attributes: Accept: Tells the server what type of response the client accepts. Cookie: The Cookie of the client is passed to the Referer of the server via this header property: Indicates the URL from which the request comes. If you search for an advertising page of a merchant through Google and you are interested in this advertising page, send a request message to the website of the merchant with a click of the mouse. The attribute value of the Referer header of the request message is http://www.google.com. Cache-control: controls the Cache

Attributes of the HTTP response header are as follows: cache-control: After the response is sent to the client, the server uses the header to tell the client how to Control the Cache of the response. A header attribute that represents the version of the response server resource (such as a page). If a server resource changes, this ETag changes accordingly. It is a useful complement to cache-control, allowing clients to be “smarter” about when to fetch resources from the server and when to return a response directly from the Cache. Location: Redirect A page to page A, which means the client sends A request to page A. The URL that needs the Redirect to page A tells the client set-cookie via the Location attribute in the response header: The server can set the Cookie of the client

A common status code 1XX message tells the client that the request has been received and is being processed. 2XX Processing is successful: The request is received, I understand what you want, the request is accepted, and the processing is complete. 3XX redirect to another location. It lets the client make another request to complete the processing. 4XX processing errors occur, and the client is responsible for such errors. For example, the client requests a non-existent resource, the client is not authorized, and access is prohibited. When 5XX processing errors occur, the fault is on the server. For example, the server throws an exception, the route fails, and the HTTP version is not supported.

The details are as follows: 2XX series: Indicates that the request is successfully received, understood, and accepted by the server. 200 status code: the request was successful. The desired response header or data body is returned with this response. 201 status code: the request was successful and the server created a new resource, whose URI has been returned with the Location header. If the required resource cannot be created in time, return ‘202 Accepted’

4XX series: Request error. Represents that the client appears to have made an error that interferes with the server’s processing. 401 Status code: The request requires authentication. The server may return this response for a web page that requires login. 403 Status code: The server understands the request, but refuses to execute it. Unlike the 401 response, authentication does not help, and the request should not be submitted twice. 404 Status code: The request fails because the requested resource is not found on the server.

5XX series: Indicates that an error or exception occurs when the server processes a request, or the server realizes that the current hardware and software resources cannot complete the processing of the request. 500 status code: The server encountered an unexpected condition that prevented it from completing processing the request. Typically, this problem occurs when the server’s code fails. 503 Status code: The server is currently unable to process requests due to temporary server maintenance or overload.

Blog.csdn.net/u010256388/… 22, design patterns, reference links: www.cnblogs.com/leedaily/p/…

Pass a parameter to a PHP script:

  • php -r “var_dump($argv);” — -h (If the argument to be passed begins with -, the argument list delimiter must be used to pass the argument correctly)
  • Test.php assumes the file is in the current directory with the code:
#! /usr/bin/php<? php var_dump($argv); ? > // Add at the beginning of the PHP file#! /usr/bin/php can pass arguments starting with - directly
./test.php -h -- foo  
Copy the code

The difference between Redis and memcached

  • There is a snapshot of the Redis system library, if there is a power outage, the data will still be there, and Memached will not be
  • Memcached is a simple key-value pair, key-value, redis supports many storage methods (strings, bidirectional lists, hashes, collections, ordered collections), and many application scenarios
  • Redis performs better than Memached
  • Memcached is a multithreaded, non-blocking IO reuse network model. Redis uses a single-threaded multiplex IO multiplexing model.

SQL injection SQL injection attack is one of the common methods used by hackers to attack databases. When writing the code, the validity of the user input data is not judged. The injector can enter a piece of database query code into the form and submit it. The program will piece together the submitted information to generate a complete SQL statement, and the server will be tricked into executing the malicious SQL command. According to the results returned by the program, the injector can successfully obtain some sensitive data and even control the entire server. This is called SQL injection.

What is the difference between HTTP and HTTPS? Data transmitted through HTTP is unencrypted, that is, plaintext. Therefore, it is very insecure to use HTTP to transmit private information. To ensure that private data can be encrypted, Netscape designed Secure Sockets Layer (SSL) to encrypt data transmitted through HTTP. HTTPS was born. To put it simply, HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identities. It is more secure than HTTP. The main differences between HTTPS and HTTP are as follows:

  • HTTPS requires you to apply for a certificate from a CA. Generally, there are few free certificates, so a certain cost is required.
  • HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol.
  • HTTP and HTTPS use completely different connections and use different ports, the former 80 and the latter 443.
  • HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.

27, from what has happened to enter the URL to the page load segmentfault.com/a/119000000…

Message queue in essence, message queue is a queue structure of middleware, that is, messages put into the middleware can be directly returned, without immediate system processing, and another program will read these data, and sequential processing. That is, when you have a very large concurrency that takes a very long time and doesn’t need to return the result immediately, you can solve this problem by using message queues.

Business systems team – > message queuing out team – > queue processing system consists of a business team, the news of successive inserted into the message queue, insert after successful returned directly successful as a result, the subsequent will have a message processing system, the system will remove the record in successive message system and process, complete a team process.

www.cnblogs.com/dump/p/8243…

29. Timing script blog.csdn.net/xf_come_on/…

30. Network Layer 7 Protocol 7 Application layer 6 Presentation layer 5 Session layer 4 Transport layer 3 Network Layer 2 Data link layer 1 Physical layer Layer 7, 6, 5, and 4 define the functions of applications Layer 3, 2, and 1 are mainly for the end-to-end data flow over the network

TCP UDP
Whether connection connection-oriented Oriented disconnection
Incoming reliability reliable unreliable
Refer to the scene Transfer large amounts of data Transmit a small amount of data
speed slow fast
For example, bank Windows ping qq to send messages

HTTP, also known as Hypertext Transfer Protocol, is the foundation of Web networking and one of the protocols commonly used in mobile networking. HTTP is an application based on TCP. An HTTP connection is a “short connection” because HTTP actively releases the connection at the end of each request. Socket is not a protocol, but a layer abstracted to facilitate the use of TCP or UDP. It is a group of interfaces between the application layer and the transmission control layer. When creating a Socket connection, you can specify the transport layer protocol to be used. The Socket supports different transport layer protocols (TCP or UDP). When TCP is used for connection, the Socket connection is a TCP connection.

WebSocket is also an application-layer protocol like HTTP, but it is a two-way communication protocol built on TOP of TCP. In WebSocket, the server and browser only need to shake hands through HTTP protocol, and then establish a SEPARATE TCP communication channel for data transmission.

HTTP is based on the application layer. Socket is based on the transport layer (TCP/UDP).

HTTP connections use a “request-response” approach, which not only requires the connection to be established during the request, but also requires the client to send a request to the server before the server can reply to the data. At the end of the request, the connection is actively released. Normally, a Socket connection is a TCP connection. Once a Socket connection is established, the communication parties can send data to each other until the connection is disconnected.

In the case of video, picture, breakpoint continued to use socket, HTTP protocol stateless can not achieve this function.

The disadvantage of HTTP continuous request sending: it will lead to too many unnecessary requests, wasting traffic and server resources. Each request and reply wastes a certain amount of traffic on the same header information

WebSocket and HTTP have the following similarities: 1. They are both based on TCP and are both reliable transmission protocols. 2. Differences of application layer protocols: 1. WebSocket is a two-way communication protocol that simulates the Socket protocol and can send or receive information in both directions. HTTP is one-way. 2. WebSocket requires a handshake to establish a connection.

Mysql date_sub(‘2012-05-25’,interval 1 day) indicates 2012-05-24 date_sub(‘2012-05-25’,interval 0 day) indicates 2012-05-25 Date_sub (‘2012-05-25’, interval-1 day) Indicates 2012-05-26. Date_sub (curdate(),interval 1 day) indicates 2013-05-19 Date_sub (curdate(), interval-1 day) indicates 2013-05-21 date_sub(curdate(),interval 1 month) indicates 2013-04-20 Date_sub (curdate(), interval-1 month) indicates 2013-06-20 date_sub(curdate(),interval 1 year) indicates 2012-05-20 Date_sub (curdate(), interval-1 year) indicates 2014-05-20

Select unix_timestamp(DATE_SUB(CURDATE(),INTERVAL 1 day)), unix_timestamp(date_sub(curdate(), interval 0 day));

SELECT UNIX_TIMESTAMP(‘2018-10-31’);

Select FROM_UNIXTIME(1540915200, ‘%Y-%m-%d’);

32,

/ / an even number$a = [6, 7, 8, 9];
$arr = array_filter($a.function ($v) {
    return ($v& 1); }); Return: [1 => 7 3 => 9]$file = 'E:\php1\wamp64\www\test.txt';
$content = file($file);
foreach ($content as $key= >$value) {
    $value = mb_convert_encoding($value.'utf-8'.'gbk');
    $v = explode("\t".$value); } Second:$handle = fopen($file.'r');
if ($handle) {
    while (($row = fgets($handle))! = =false) {
        $row = mb_convert_encoding($row.'utf-8'.'gbk');
        $v = explode("\t".$row);
    }
    fclose($handle); } // The first and last day of the current month$monthFirstDay = date('Y-m-01', strtotime(date("Y-m-d")));
$monthLastDay = date('Y-m-d', strtotime($monthFirstDay . ' +1 month -1 day')); // The last day of the last month on the specified date$lastDay = date('Y-m-t', strtotime('last month', strtotime('20181116'))); / / 2018-10-31$arr = range('a'.'z');
$str = implode($arr); // abcdefghijklmnopqrstuvwxyz$a = "aa";
$b = "bb"; // Swap two variables var_dump([$a.$b]); / / /'aa'.'bb']
list($a.$b) = [$b.$a];
var_dump([$a.$b]); ['bb'.'aa'] // Invert the stringfunction mb_strrev($str)
{
    $r = ' ';
    for ($i = mb_strlen($str); $i> = 0;$i-) {$r .= mb_substr($str.$i, 1);
    }
    return $r;
}
echo mb_strrev("Being ❤ world me"); / / I am dlrow ❤ do thingsCopy the code
echo mb_internal_encoding(); // UTF-8
$str = "Ab.cb tested."; 
echo strlen($str); // A UTF8 Chinese character =3 bytes, so 3+1+2+1+9=16echo mb_strlen($str."utf-8"); //UTF-8 treats Chinese characters as one character, so 3+1+2+1+3=10echo mb_strlen($str."gbk"); // GBK, a Chinese character is 1.5 characters,3+1+2+1+4.5=11.5Copy the code
Empty () can be used to determine whether all data types are empty or false, while is_null, like isset, can only be used to determine whether all data types are NULL and undefined.Copy the code
echo count(strlen('https://www.baidu.com/')); // Result: 1, count(var) is used to count the number of elements in an array or object. When var is null or an empty array, the result is 0. If var is a normal variable, return 1. Normally returns the number of elements or attributes in var.Copy the code

PHP discourages closing tags to avoid the possibility of accidentally adding a space or line break after the PHP closing tag, which would cause PHP to start printing white space. The most important time to do this is when you use include and require, Adding an end tag followed by a space can result in redundant output, PHP errors, subsequent output not being displayed, and empty pages due to functions like session_start(). When you have the body output before session_start(), you can no longer set header set-cookie, and sessions rely on cookies.

CGI represents a bridge between PHP and Web Server. FastCGI is a modified VERSION of CGI called phP-FPM process manager

CGI: is a protocol for data exchange between Web Server and Web Application. FastCGI: The same as CGI, is a communication protocol, but more efficient than CGI to do some optimization. Again, the SCGI protocol is similar to FastCGI. Php-cgi: PHP interface to the CGI protocol provided by the Web Server. Php-fpm: PHP to the Web Server to provide the FastCGI protocol interface program, in addition to providing relatively intelligent task management.

In WEB, WEB Server generally refers to Apache, Nginx, IIS, Lighttpd, Tomcat and other servers, and WEB Application generally refers to PHP, Java, Asp.net and other applications.

34, the json

$.ajax({
    type: 'get',
    async: false,
    url: "http://test.com/learn/jsonp.php",
    dataType: 'jsonp',
    jsonp: 'callback', // The parameter name passed to the request handler or page to obtain the name of the jSONp callback function (default :callback)'callbackFun', // Jsonp callback function name, default is automatically generated by jQuery random function name, can also be written"?", jQuery will automatically process the data for youfunction (res) {
        console.log(res)
    },
    error: function () {
        console.log('fail'}}) jsonp.php page header('Content-type: application/json');
$callback = htmlspecialchars($_REQUEST['callback']);
$jsonData = json_encode(['id'= > 1,'name'= >'Kitty']);
echo $callback . '(' . $jsonData . ') ';
exit;
Copy the code

Dependency injection ORM mysql primary/secondary replication read-write separation distributed unit test

Other interview website: www.cnblogs.com/gaowei521/p…