Home > Backend Development > PHP Tutorial > 2021 PHP interview questions collection

2021 PHP interview questions collection

烟雨青岚
Release: 2023-04-09 08:32:02
forward
4367 people have browsed it

2021 PHP interview questions collection

1. Basic part of PHP

1. One of the major advantages of PHP language is cross-platform. What is cross-platform?

The optimal running environment of PHP is Apache MySQL PHP. This running environment can be configured on different operating systems (such as windows, Linux, etc.) and is not restricted by the operating system, so it is called cross-platform

2. How many methods are there for data submission in WEB development? What's the difference? Which method does Baidu use?

Get and post two methods

Difference:

(1) url visibility: get method url parameters are visible , post is not visible

(2) Cacheability: The get method can be cached, but the post method cannot be cached.

(3) Transmission data size: The general transmission data size of get does not exceed 2k-4k (depending on the browser, the limit is different, but the difference is not big); the size of the post request transmission data is configured according to php.ini The file setting can also be infinitely large.

(4) Data transmission: The get method is used to transmit parameters through the url address bar splicing, and the post method is used to transmit the data through the body.

Suggestion:

1. The get type is less secure than the Post type. It contains confidential information and it is recommended to use the Post data submission type;

2. It is recommended to use the Get method for data query; it is recommended to use the Post method for adding, modifying or deleting data;

The get method used by Baidu, because it can be seen from its URL

3. Master What are the frameworks, template engines, systems, etc. of PHP?

Frameworks: There are many frameworks, such as CI, Yii, Laravel, etc. What we have learned is thinkphp

Template engines: There are also many, in In the textbook, what we have learned is the smart

system: there are many, such as: Kangsheng's products (uchome, supesite, discuzX, etc.), Empire system, DEDE (Dream Weaver), ecshop, etc., we have learned I have passed DEDECMS and Ecshop

4. What are the web front-end technologies you have mastered?

Proficient in p CSS web page layout, JavaScript, jQuery framework, photoshop image processing

5. What are the advantages of AJAX?

ajax is an asynchronous transmission technology that can be implemented through javascript or the JQuery framework to achieve partial refresh, which reduces the pressure on the server and improves the user experience.

6. Security is crucial to a program. Please tell us what security mechanisms should be paid attention to during development?

(1) Use the verification code to prevent the registration machine from flooding.

(2) Use preprocessing, binding parameters, parameter filtering and escaping to prevent sql injection

(3) Use token to prevent remote submission, and use token to verify login status.

7. In the development of the program, how to improve the operating efficiency of the program?

(1) Optimize SQL statements, try not to use select * in query statements, use which field to check which field; use less subqueries and can be replaced by table connections; use less fuzzy queries.

(2) Create an index in the data table.

(3) Generate cache for data frequently used in the program (such as using redis to cache data, such as using ob to staticize dynamic pages, etc.).

(4) Make master-slave replication of mysql and separate reading and writing. (Improve mysq execution efficiency and query speed)

(5) Use nginx for load balancing. (Evenly distribute access pressure to polymorphic servers)

8. Can PHP be used with other databases?

PHP is the best combination with MYSQL database. Of course, PHP can also be used with other databases, such as PostgreSql, SqlServer, Oracle, SqlLite, etc.

9. Nowadays, the MVC three-layer structure is often used in programming. What are the three layers of MVC? What are the advantages?

The three layers of MVC refer to: business model, view, and controller. The controller layer calls the model to process the data, and then maps the data to the view layer for display.

The advantages are:

①It can realize code reusability and avoid code redundancy;

②M and V can realize code separation, so that the same program can be used Different forms of expression

10. Understanding of json data format?

JSON (JavaScript Object Notation) is a lightweight data exchange format. The json data format is fixed and can be used for data transfer in multiple languages.

The function that handles json format in PHP is json_decode( string $json [, bool $assoc ] ), which accepts a JSON format string and converts it into a PHP variable. The parameter json is the json string format to be decoded. String. assoc When this parameter is TRUE, it will return array instead of object;

Json_encode: Convert PHP variables into json format.

11. What are the differences between Print, echo and print_r?

(1) Both echo and print can do output. The difference is that echo is not a function and has no return value, while print is a function with a return value, so relatively speaking, if you just output echo, it will Faster, while print_r is usually used to print information about variables, often used in debugging.

(2) print is to print a string

(3) print_r is to print a composite type such as an array object

12. What is the difference between SESSION and COOKIE?

(1) Storage location: session is stored in the server, cookie is stored in the browser

(2) Security: session security is higher than cookie

(3) session is a 'session service', the service needs to be turned on when using it, cookies do not need to be turned on, you can use it directly

13. Commonly used functions for processing arrays in PHP? (Focus on the 'parameters' and 'return value' of the function)

(1) array() creates an array

(2) in_array() determines whether the element is in the array

(3) count() returns the number of elements in the array

(4) array_merge() merges multiple arrays into one array

(5) array_diff() comparison The difference between two or more arrays

(6)array_intersect() Gets the intersection of two or more arrays

(7)array_keys() Gets the key list of the array

(8)array_values() Get the value list of the array

(9)array_unique() Delete duplicate values ​​in the array

(10)array_push() will one or more Insert the element into the end of the array (push)

(11) array_pop() Pop and return the last element of the array array (push)

(12) array_walk() Use user-defined The function performs callback processing on each element in the array

14. What are the common functions used to process strings in PHP? (Focus on the 'parameters' and 'return value' of the function)

(1) trim() removes blank characters and other characters on both sides of the string;

(2 ) strlen() Get the length of the string

(3) mb_strlen() Get the length of the string (character encoding can be specified, calculate the length of the Chinese string)

(4) substr() Return part of the string;

(5) str_replace() Substring replacement

(6) str_repeat () Repeat a string

(7) is_string() Check whether the variable is a string;

(8) str_shuffle () randomly shuffles a string

(9) sprintf() returns a string generated based on the formatted string (usually used To obtain the data table name after splitting the table)

(10) strstr() Find the first occurrence of the string

(11) addslashes Use backslashes to quote the string

15. Commonly used functions in PHP to process time? (Focus on the ‘parameters’ and ‘return value’ of the function)

(1) date() Format a local time/date.

(2) getdate() Get date/time information.

(3)date_default_timezone_set() sets the default time zone.

(4) date_default_timezone_get() returns the default time zone.

(5)mktime() Returns the Unix timestamp of a date.

(6)strtotime() Parse the date and time description of any string into a Unix timestamp

(7)strftime() Format the local time/date according to the regional settings

16. What are the commonly used functions for PHP to process databases? (Focus on the 'parameters' and 'return value' of the function)

Please refer to the PHP manual and read it carefully. This item is very important.

17. PHP operation files Commonly used functions? (Focus on the 'parameters' and 'return value' of the function)

(1) Open the file fopen()

(2) Read the file fgets(); Note: file_get_contents () also reads the file

(3) writes the file fwrite(); Note: file_put_contents() can also write the file

(4) closes the file handle fclose()

(5) Move/rename file rename()

(6) Copy file copy()

(7) Create file vim or touch

(8 ) Delete the file unlink()

(9) Get the time when the file was last accessed fileatime()

(10) Get the time when the file was last modified filemtime()

(11) Get the file size filesize()

(12) Get the file type filetype()

(13) Get the file details state()

(14) Judgment Is it directory is_dir()

18, a common function for PHP to operate directories (folders)? (Focus on the 'parameters' and 'return value' of the function)

(1) Open the directory opendir()

(2) Read the directory readdir()

(3) Delete directory rmdir()

(4) Close directory handle closedir()

(5) Create directory mkdir()

(6) Return path The directory part in dirname()

(7) Get the current working directory getcwd()

(8) List the files and directories in the specified path scandir()

2. Database part

1. What are the common relational database management system products?

Answer: Oracle, SQL Server, MySQL, Sybase, DB2, Access, etc.

2. What parts does SQL language include? What are the action keywords for each section?

Answer: SQL language includes four parts: data definition (DDL), data manipulation (DML), data control (DCL) and data query (DQL).

Data definition: Create Table, Alter Table, Drop Table, Craete/Drop Index, etc.

Data manipulation: Select, insert, update, delete,

Data control: grant ,revoke

Data query: select

3. What are the integrity constraints?

Data Integrity refers to the accuracy and reliability of data.

Includes:

(1) Entity integrity: stipulates that each row of the table is a unique entity in the table.

(2) Domain integrity: It means that the columns in the table must meet certain data type constraints, which include value range, precision and other regulations.

(3) Referential integrity: It means that the data of the primary key and foreign key of the two tables should be consistent, ensuring the consistency of the data between the tables and preventing data loss or meaningless data. Data is spread across databases.

(4) User-defined integrity: Different relational database systems often require some special constraints based on their application environments. User-defined integrity is a constraint for a specific relational database, which reflects the semantic requirements that a specific application must meet.

4. What is a transaction? and its characteristics?

Transaction: It is a series of database operations and the basic logical unit of database applications.

Features:

(1) Atomicity: that is, indivisibility, either all transactions are executed or none are executed.

(2) Consistency or stringability. The execution of a transaction converts the database from one correct state to another correct state

(3) Isolation. Before the transaction is correctly committed, any changes to the data by the transaction are not allowed to be provided to any other transaction,

(4) Durability. After a transaction is submitted correctly, its results will be permanently saved in the database. Even if there are other failures after the transaction is submitted, the processing results of the transaction will be saved.

Simple understanding: All operations in a transaction either succeed or fail.

5. What is a lock?

The database is a shared resource used by multiple users. When multiple users access data concurrently, multiple transactions simultaneously access the same data in the database. If concurrent operations are not controlled, incorrect data may be read and stored, destroying the consistency of the database.

Locking is a very important technology to achieve database concurrency control. Before a transaction operates on a data object, it first sends a request to the system to lock it. After locking, the transaction has certain control over the data object. Before the transaction releases the lock, other transactions cannot update the data object.
Basic lock types: locks include row-level locks and table-level locks

6. What is a view? What is a cursor?

A view is a virtual table that has the same functions as a physical table. Views can be added, modified, checked, and operated. A view is usually a subset of rows or columns of one table or multiple tables. Modifications to the view do not affect the underlying tables. It makes it easier for us to obtain data compared to multi-table queries.

Cursor: It effectively processes the query result set as a unit. The cursor can be positioned on a specific row in the cell to retrieve one or more rows from the current row in the result set. You can make changes to the current row of the result set. Cursors are generally not used, but when data needs to be processed one by one, cursors are very important.

7. What is a stored procedure? What to call?

The stored procedure is a precompiled SQL statement. The advantage is that it allows a modular design, which means that it only needs to be created once and can be called multiple times in the program later. If a certain operation requires multiple executions of SQL, using stored procedures is faster than executing simple SQL statements. Stored procedures can be called using a command object.

8. What is the role of index? And what are its advantages and disadvantages?

An index is a special query table that the database search engine can use to speed up data retrieval. It is very similar to the table of contents of a book in real life. You can find the data you want without querying the entire book. Indexes can be unique. Creating an index allows you to specify a single column or multiple columns.

The disadvantage is that it slows down the speed of data entry and also increases the size of the database.

How to understand the three paradigms in a popular way?

First normal form: 1NF is an atomicity constraint on attributes, which requires attributes to be atomic and cannot be decomposed;

Second normal form: 2NF is a unique constraint on records , requiring the record to have a unique identifier, that is, the uniqueness of the entity;

Third normal form: 3NF is a constraint on field redundancy, that is, any field cannot be derived from other fields, and it requires that the field is not redundant. .

What is a basic table? What is a view?

The basic table is a table that exists independently. In SQL, a relationship corresponds to a table.

A view is a table derived from one or several basic tables. The view itself is not stored independently in the database, it is a virtual table

Describe the advantages of views?

(1) Views can simplify user operations

(2) Views enable users to view the same data from multiple angles;

(3) Views are The database provides a certain degree of logical independence;

(4) Views can provide security protection for confidential data.

What does NULL mean?

The value NULL represents UNKNOWN (unknown): it does not represent "" (empty string).

Any comparison of the NULL value will produce a NULL value.

You cannot compare any value to a NULL value and logically expect to get an answer.

Use IS NULL for NULL judgment

What is the difference between primary key, foreign key and index?

The difference between primary key, foreign key and index
Definition:
Primary key – uniquely identifies a record, cannot be duplicated, and is not allowed to be empty
Foreign key – foreign key of the table The key is the primary key of another table. The foreign key can have duplicates or null values.
Index – this field has no duplicate values, but can have a null value
Function:
Primary key – used to ensure data Integrity
Foreign keys – used to establish connections with other tables
Indexes – are used to increase the speed of query sorting
Number:
Primary key – there can only be one
foreign key – A table can have multiple foreign keys
Indexes – A table can have multiple unique indexes

What can you use to ensure that fields in a table only accept values ​​in a specific range?

Check limit, which is defined in the database table, is used to limit the value entered in this column.

Tell me what methods are there to optimize SQL statements? (Select a few)

(1) In the Where clause: The connection between where tables must be written before other Where conditions, and those conditions that can filter out the maximum number of records must be written in the Where sub At the end of the sentence.HAVING last.

(2) Replace IN with EXISTS and NOT IN with NOT EXISTS.

(3) Avoid using calculations on index columns

(4) Avoid using IS NULL and IS NOT NULL on index columns

(5) Optimize queries , you should try to avoid full table scans, and first consider creating indexes on the columns involved in where and order by.

(6) Try to avoid making null value judgments on fields in the where clause, otherwise the engine will give up using the index and perform a full table scan

(7) Try to avoid using the where clause Expression operations on fields in clauses will cause the engine to abandon the use of indexes and perform full table scans

What is the difference between 'correlated subquery' and 'non-correlated subquery' in a SQL statement?

(1) Non-correlated subquery is a subquery that is independent of the external query. The subquery is executed once in total, and the value is passed to the external query after execution.

(2) The execution of the relevant subquery depends on the data of the external query. When the external query executes a row, the subquery is executed once.

So non-correlated subqueries are more efficient than correlated subqueries

What is the difference between char and varchar?

char is a fixed-length type, and varchar is a variable-length type.

Difference:

In a char(M) type data column, each value occupies M bytes. If a length is less than M, MySQL will use spaces to the right of it. Character complement. (The padded space characters will be removed during the search operation).

In the varchar(M) type data column, each value only occupies just enough bytes plus one byte to record its length (that is, the total length is L 1 byte).

Mysql storage engine, the difference between myisam and innodb.

MyISAM is a non-transactional storage engine; suitable for applications with frequent queries; table locks, no deadlock; does not support transactions. Suitable for small data and small concurrency

Innodb is a storage engine that supports transactions; suitable for applications with a lot of insertion and update operations; if the design is reasonable, it is a row lock (the biggest difference is in the level of the lock); suitable for large Data, massive concurrency.

What are the data table types?

MyISAM, InnoDB, HEAP, BOB, ARCHIVE, CSV, etc.

MyISAM: Mature, stable, easy to manage, fast to read. Some functions do not support (transactions, etc.), table-level locks.

InnoDB: supports transactions, foreign keys and other features, and data row locking. It takes up a lot of space and does not support full-text indexing, etc.

The MySQL database is used as the storage for the publishing system. More than 50,000 entries are added a day. The operation and maintenance is expected to last three years. How to optimize it?

(1) Design a well-designed database structure, allow partial data redundancy, and try to avoid join queries to improve efficiency.

(2) Select the appropriate table field data type and storage engine, and add indexes appropriately.

(3) Do mysql master-slave replication read-write separation.

(4) Divide the data table into tables to reduce the amount of data in a single table and improve query speed.

(5) Add caching mechanism, such as redis, memcached, etc.

(6) For pages that do not change frequently, generate static pages (such as ob caching).

(7) Write efficient SQL. For example, SELECT * FROM TABEL is changed to SELECT field_1, field_2, field_3 FROM TABLE.

For a website with high traffic, what method do you use to solve the problem of statistics of page visits?

(1) Confirm whether the server can support the current traffic.

(2) Optimize database access.

(3) Prohibit external access to links (hotlinking), such as hotlinking of pictures.

(4) Control file download.

(5) Do load balancing and use different hosts to offload traffic.

(6) Use browsing statistics software to understand the number of visits and perform targeted optimization.

3. Object-oriented part

1. What is object-oriented? (answer with understanding)

Object-oriented is One kind of thinking is based on process-oriented, which means that object-oriented realizes functions through objects, encapsulates functions into objects, and lets the objects implement specific details.

Object-oriented has three major characteristics: encapsulation, inheritance, and polymorphism.

The current pure OO languages ​​are mainly Java and C#. PHP and C also support OO. C is process-oriented.

2. Briefly describe the access rights of private, protected, and public modifiers.

private: Private members can only be accessed inside the class.

protected: Protected members can be accessed within the class and inherited classes.

public: Public members, completely public, no access restrictions.

3. What is the difference between heap and stack?

The stack is a memory space allocated during compilation, so the size of the stack must be clearly defined in your code;

The heap is memory allocated dynamically during program running. Space, you can determine the size of heap memory to be allocated based on the running conditions of the program.

4. The main difference between XML and HTML

Different grammatical requirements:

(1) In html, it is not case-sensitive, in xml Strict distinction.

(2) In HTML, sometimes it is not strict. If the context clearly shows where the paragraph or list key ends, then you can omit the

or similar closing tag. In XML, it is a strict tree structure, and the closing tag must not be omitted.

(3) In XML, elements that have a single tag without a matching closing tag must end with a / character. This way the parser knows not to look for the closing tag.

(4) In XML, attribute values ​​must be enclosed in quotation marks. In HTML, quotation marks are optional.

(5) In HTML, you can have attribute names without values. In XML, all attributes must have corresponding values.

(6) In XML documents, the blank parts will not be automatically deleted by the parser; but html filters out the blanks.

Different tags:

(1) html uses inherent tags; xml does not have inherent tags.

(2) Html tags are predefined; XML tags are free, customizable and extensible.

Different functions:

(1) HTML is used to display data; xml is used to describe data and store data, so it can be used as a persistence medium! Html combines data and display and displays the data on the page; xml separates data and display. XML is designed to describe data, with the focus being the content of the data. HTML was designed to display data, with the focus being on the appearance of the data.

(2) XML is not a substitute for HTML. XML and HTML are two languages ​​with different uses. XML is not intended to replace HTML; in fact, XML can be seen as a complement to HTML. The goals of XML and HTML are different. The design goal of HTML is to display data and focus on the appearance of the data, while the design goal of XML is to describe the data and focus on the content of the data.

(3) The best description of XML may be: XML is a cross-platform, software- and hardware-independent tool for processing and transmitting information.

(4) XML will be ubiquitous in the future. XML will become the most common tool for data processing and data transmission.

5. What are the characteristics of object-oriented?

Mainly include encapsulation, inheritance, and polymorphism. If it is 4 aspects, add: abstraction.

Encapsulation:
Encapsulation is the basis for ensuring that software components have excellent modularity. The goal of encapsulation is to achieve high cohesion and low coupling of software components and prevent changes caused by program interdependence. Impact.

Inheritance:
When defining and implementing a class, you can do it on the basis of an existing class, and use the content defined by this existing class as your own content. And you can add some new content, or modify the original method to make it more suitable for special needs. This is inheritance. Inheritance is a mechanism for subclasses to automatically share parent class data and methods. This is a relationship between classes that improves the reusability and scalability of software.

Polymorphism:
Polymorphism means that the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable are not determined during programming, but only during the running of the program. Determination, that is, which class instance object a reference variable will point to, and which class implements the method call issued by the reference variable, must be determined during the running of the program.

Abstraction:
Abstraction is to find out the similarities and commonalities of some things, and then classify these things into a class. This class only considers the similarities and commonalities of these things, and ignores the similarities and commonalities of these things. Focus on those aspects that are irrelevant to the current topic and goal, and focus on those aspects that are relevant to the current goal. For example, if you see an ant and an elephant and you can imagine how they are similar, that is abstraction.

6. What are the concepts and differences between abstract classes and interfaces?

Abstract class: It is a special class that cannot be instantiated and can only be used as a parent class of other classes. Declared using the abstract keyword.

Interface: It is a special abstract class and a special class, declared using interface.

Difference:

(1) The operations of abstract classes are implemented through the inheritance keyword extends, while the use of interfaces is implemented through the implements keyword.

(2) There are data members in the abstract class, which can realize data encapsulation, but the interface has no data members.

(3) Abstract classes can have constructors, but interfaces have no constructors.

(4) Methods of abstract classes can be modified with private, protected, and public keywords (abstract methods cannot be private), while methods in interfaces can only be modified with public keywords.

(5) A class can only inherit from one abstract class, and a class can implement multiple interfaces at the same time.

(6) An abstract class can have implementation code for member methods, but an interface cannot have implementation code for member methods.

7. What is a constructor, what is a destructor, and what is its function?

The constructor (method) is the first method automatically called by the object after the object is created. It exists in every declared class and is a special member method. Its function is to perform some initialization tasks. In Php, __construct() is used to declare the constructor method, and only one can be declared.

The destructor (method) has the opposite effect to the constructor. It is the last method automatically called by the object before it is destroyed. It is a newly added content in PHP5 that is used to perform some specific operations before destroying an object, such as closing files and releasing memory.

8. How to overload the method of the parent class, give an example

Overloading means overriding the method of the parent class, that is, using the method in the subclass to replace the method from the subclass. Methods inherited from the parent class are also called method overrides.

The key to overriding the parent class method is to create the same method in the parent class in the subclass, including the method name, parameters and return value type. In PHP, only the names of the methods are required to be the same.

9. What are the commonly used magic methods? For example

php stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that your function name should not start with __ unless it is to overload an existing magic method. method.

__construct() is automatically called when instantiating a class.

__destruct() is automatically called when the class object is used.

__set() is called when assigning a value to an undefined property.

__get() is called when undefined attributes are called.

__isset() Will be called when using isset() or empty() function.

__unset() Will be called when using unset().

__sleep() is called when serializing using serialize.

__wakeup() is called when deserializing using unserialize.

__call() is called when calling a method that does not exist.

__callStatic() calls a static method that does not exist.

__toString() is called when converting an object into a string. Such as echo.

__invoke() Called when trying to invoke an object as a method.

__set_state() Called when using the var_export() function. Accepts an array parameter.

__clone() is called when using clone to copy an object.

10. What do the three keywords $this and self and parent represent respectively? In what situations is it used?

$this current object

self current class

parent parent class of the current class

$this is used in the current class, use - >Call properties and methods.

self is also used in the current class, but it needs to be called using ::.

parent is used in the class.

11. How to define constants in a class, how to call constants in a class, and how to call constants outside a class.

The constants in the class are also member constants. A constant is a quantity that does not change and is a constant value.

To define constants, use the keyword const.

For example: const PI = 3.1415326;

Whether it is inside a class or outside a class, the access of constants is different from that of variables. Constants do not need to instantiate objects. The format for accessing constants is the class name plus the scope operation symbol (double colon) to call.

That is: class name:: class constant name;

12. How to use scope operator::? In what situations is it used?

(1) Call class constants

(2) Call static methods (class methods modified with static)

13. __autoload() method How does it work?

The basic condition for using this magic function is that the file name of the class file must be consistent with the name of the class.

When the program is executed to instantiate a certain class, if the class file is not introduced before instantiation, the __autoload() function will be automatically executed.

This function will search for the path of the class file based on the name of the instantiated class. When it is determined that the class file does exist in the path of the class file,

execute include or require to load it. Enter this class, and then the program continues to execute. If the file does not exist in this path, an error will be prompted.

Using the automatically loaded magic function eliminates the need to write many include or require functions.

4. THINKPHP part

1. Common PHP frameworks

Answer: thinkPHP, laravel, yii, ci, etc. .

2. How to understand the single entry file in TP?

ThinkPHP adopts a single entrance mode for project deployment and access. No matter what function is completed, a project has a unified (but not necessarily the only) entrance. It should be said that all projects start from the entry file, and the entry files of all projects are similar.

The entry file mainly includes:

(1) Define the framework path, project path and project name (optional)
(2) Define related constants for debugging mode and running mode (optional)
(3) Load the framework entry file ( Required)

3. What is the MVC layering in ThinkPHP? (Understanding)

MVC is a method of separating the logical layer and presentation layer of an application. ThinkPHP is also based on the MVC design pattern. MVC is just an abstract concept and has no particularly clear regulations. The MVC layering in ThinkPHP is roughly reflected in:

Model (M): The definition of the model is completed by the Model class.

Controller (C): Application controller (core controller App class) and Action controller both assume the role of controller. Action controller completes business process control, while application controller is responsible for scheduling control.

View (V): It consists of View class and template file. The template is 100% separated and can be previewed and produced independently.

But in fact, ThinkPHP does not rely on M or V, which means it can work without a model or view. It doesn’t even rely on C. This is because ThinkPHP also has a master controller on top of Action, the App controller, which is responsible for the overall scheduling of the application. In the absence of C, view V must exist, otherwise it is no longer a complete application.
In short, ThinkPHP's MVC model only provides a means of agile development, rather than sticking to MVC itself.

4. How to optimize SQL? (Students can understand the following explanation, and then just state the general meaning according to their own understanding)

(1) Choose the correct storage engine

MyISAM is suitable for applications that require a large number of queries, but it is not very good for a large number of write operations. Even if you just need to update a field, the entire table will be locked, and other processes, even the reading process, cannot operate until the reading operation is completed. In addition, MyISAM is extremely fast for calculations such as SELECT COUNT(*).
The trend of InnoDB will be a very complex storage engine, and for some small applications, it will be slower than MyISAM. But it supports "row locking", so it will be better when there are many write operations. Moreover, it also supports more advanced applications, such as transactions.

(2) Optimize the data type of the field
Remember a principle, the smaller the column, the faster it will be. If a table only has a few columns (such as a dictionary table, configuration table), then we have no reason to use INT as the primary key. It will be more economical to use MEDIUMINT, SMALLINT or a smaller TINYINT. If you don't need to keep track of time, it's much better to use DATE than DATETIME. Of course, you also need to leave enough room for expansion.

(3) Add an index to the search field
The index does not necessarily mean the primary key or the only field. If there is a field in your table that you will always use for searching, then it is best to index it. Unless the field you want to search is a large text field, then you should create a full-text index.

(4) Avoid using Select The more data is read from the database, the slower the query will become. Moreover, if your database server and WEB server are two independent servers, this will also increase the load of network transmission. Even if you want to query all fields in the data table, try not to use the wildcard character. Making good use of the built-in field exclusion definitions may bring more convenience.

(5) Use ENUM instead of VARCHAR
The ENUM type is very fast and compact. In fact, it holds a TINYINT, but it appears as a string. In this way, it becomes quite perfect to use this field to make some choice lists. For example, if the values ​​of fields such as gender, ethnicity, department, and status are limited and fixed, you should use ENUM instead of VARCHAR.

(6) Use NOT NULL whenever possible
Unless you have a very special reason to use NULL values, you should always keep your fields NOT NULL. NULL actually requires extra space, and your program will be more complex when you perform comparisons. Of course, this does not mean that you cannot use NULL. The reality is very complicated, and there will still be situations where you need to use NULL values.

(7) Fixed-length tables will be faster
If all fields in the table are "fixed-length", the entire table will be considered "static" or " fixed-length". For example, there are no fields of the following types in the table: VARCHAR, TEXT, BLOB. As long as you include one of these fields, the table is no longer a "fixed-length static table" and the MySQL engine will process it in another way.

Fixed length tables will improve performance because MySQL will search faster. Because these fixed lengths make it easy to calculate the offset of the next data, reading will naturally be faster. And if the field is not of fixed length, then every time you want to find the next one, the program needs to find the primary key.
Also, fixed-length tables are easier to cache and rebuild. However, the only side effect is that fixed-length fields waste some space, because fixed-length fields require so much space regardless of whether you use them or not.

5. How to understand the behavior in ThinkPHP 3.0 architecture (core behavior driver)?

(1) Core: It is the core code of the framework, an indispensable thing. TP itself is a framework developed based on the MVC idea.

(2) Behavior: Behavior plays a decisive role in the architecture of the new version of ThinkPHP. On the core of the system, many tag extension bits are set, and each tag position can execute its own function in turn. independent behavior. This is how behavioral extensions were born, and many system functions are also completed through built-in behavioral extensions. All behavioral extensions are replaceable and additive, thus forming the basis for the assembly of the underlying framework.

(3) Driver: database driver, cache driver, tag library driver and template engine driver, as well as external class extensions.

6. What is the conventional configuration?

The so-called conventional configuration is the framework’s own configuration file. This file is in convention.php in the core framework directory, and the configuration content is as follows. Since this file is a configuration file that comes with the framework, in the actual development process, it is mainly used as a reference example for us. We rarely modify the configuration content of this file, and more often configure the fields according to the needs according to the convention. Definitions and annotations to customize configuration content in modules or Common.

7. What is SQL injection? (Understanding)

SQL injection attack is one of the common means used by hackers to attack databases.

Some programmers do not judge the legality of user input data when writing code. The injector can enter a database query code in the form and submit it, and the program will piece together the submitted information to generate a complete sql statement, the server is tricked into executing the malicious SQL command. The injector successfully obtains some sensitive data based on the results returned by the program, and even controls the entire server. This is SQL injection.

8. How does ThinkPHP prevent SQL injection? (Understanding)

(1) Try to use array mode for query conditions, which is a safer way;

(2) If string query conditions must be used as a last resort, use preset Processing mechanism;

(3) Use binding parameters

(4) Turn on data field type verification, and you can force conversion of numerical data types; (Field type verification has been mandatory since version 3.1 )

(5) Use automatic verification and automatic completion mechanisms to customize application-specific filtering;

(6) Use field type checking, automatic verification, and automatic completion mechanisms to avoid malicious data input of.

9. How to enable debugging mode? What are the benefits of debug mode?

Enabling debugging mode is very simple. You only need to add a line of constant definition code to the entry file:

// To enable debugging mode, it is recommended to enable deployment phase comments during the development phase or set it to false
define('APP_DEBUG', true);
The advantages of debugging mode are: Turn on logging, any error information and debugging information will be recorded in detail to facilitate debugging; Turn off template caching, template modifications can take effect immediately; Record SQL logs , to facilitate SQL analysis; turn off field caching, data table field modifications are not affected by caching; strictly check file case (even on Windows platforms), helping you discover Linux deployment problems in advance; can be conveniently used in different stages of the development process, including development Different application modes can configure independent project configuration files for any required situations, such as testing and demonstration.

10. What configuration modes are supported in TP? priority?

Conventional configuration->Application configuration->Mode configuration->Debug configuration->State configuration->Module configuration->Extended configuration->Dynamic configuration

The above is the loading order of configuration files. Because the subsequent configuration will overwrite the previous configuration with the same name (if it does not take effect), the priority is from right to left.

11. What are the URL patterns in TP? Which is the default?

ThinkPHP supports four URL modes, which can be defined by setting the URL_MODEL parameter, including normal mode, PATHINFO, REWRITE and compatibility mode.
The default mode is: PATHINFO mode, set URL_MODEL to 1

12. What are the system variables in TP? How to get system variables?

(1) System variables: ##SERVER_SERVER、 ##REQUEST_REQUEST、KaTeX parse error: Expected 'EOF', got '}' at position 25: …ver.script_name}̲ // Output _SERVER['SCRIPT_NAME'] variable

{

KaTeX parse error: Expected 'EOF', got '}' at position 22: …session.user_id}̲ // Output

_SESSION['user_id']Variable

{KaTeX parse error: Expected 'EOF', got '}' at position 21: ….get.pageNumber}̲ // Output

_GET ['pageNumber']Variable

{KaTeX parse error: Expected 'EOF', got '}' at position 18: …ink.cookie.name}̲ // Output

_COOKIE[' name']Variable

1

3. What is the difference between D function and M function in ThinkPHP framework?

The M method instantiates the model without the user defining a model class for each data table. The D method can automatically detect the model class. If a custom model class exists, instantiate the custom model class. If If it does not exist, the M method will be automatically called to instantiate the Model base class. At the same time, models that have been instantiated will not be instantiated repeatedly (single case mode).

5. smarty template engine

1. What is the difference between compilation and caching?

The compilation process of smarty is to take the template and replace the tags inside with the corresponding php code. This is the compilation of smarty. In fact, it is the process of mixing php and html. Smarty’s caching needs If manually enabled, smarty's cache will execute the compiled file and generate a static html page at the same time. When you access it again, you will access the html file, so in terms of efficiency, it is higher.

2

、What is smarty? What are the advantages of Smarty?


Smarty is a PHP template engine written in PHP. The purpose is The PHP program must be separated from the artist, so that when the programmer changes the logic content of the program, it will not affect the artist's page design, and when the artist re-modifies the page, it will not affect the program logic of the program. This is especially true in multi-person cooperation projects. is particularly important. (It is also easy to develop multi-style programs)

Smarty Advantages

(1) Fast: relative to other template engines.

(2) Compiled type: A program written in smarty must be compiled into a non-template technology PHP file at runtime

(3) Caching technology: It can convert the content that the user finally sees HTML files are cached into a static HTML page

(4) Plug-in technology: smarty can customize plug-ins.

Not suitable for using smarty

(1) Content that needs to be updated in real time. For example, like stock display, it requires frequent data updates

(2) Small projects. A small project that requires both an artist and a programmer because of its simplicity

3. Use {$smarty} to retain variables in the template

{KaTeX parse error: Expected 'EOF', got '}' at position 16: smarty.get.page}̲ //Similar to accessing _GET[page]
{KaTeX in a php script parse error: Expected 'EOF', got '}' at position 16: smarty.cookies.}̲ {smarty.post.}
{KaTeX parse error: Expected 'EOF', got '}' at position 16: smarty.session.}̲ {smarty.server.}

4. Access variables in php in the template

5. Variable mediator

Summary of 2018 PHP classic interview questions (updated) - PHP interview questions

6. When php queries the mysql database, garbled characters appear when querying the Chinese results. How to deal with it?

(1) File meta (when setting browser parsing)

(2) Encoding setting when connecting to the database

(3) Used in PHP files The header function determines the encoding

7. Caching mechanism

If caching is enabled, smarty will generate a static html page at the same time. If it does not expire within the set time, When you visit again, you are accessing the html file, which reduces the need to read the database, so in terms of efficiency, it is higher.

8. Smarty’s assignment and loading template

$Smarty->assign(name,value)
$Smarty->display('index .html')

9. What is the use of marty template technology?

In order to separate php and html, artists and programmers should perform their own duties without interfering with each other.

10. What are the main smarty configurations?

(1) Introduce smarty.class.php;

(2) Instantiate the smarty object;

(3)Re-modify the default template path;

(4) Re-modify the path of the default compiled file;

(5) Re-modify the path of the default configuration file;

(6) Re-modify the default cache path of.

(7) You can set whether to enable cache.

(8) You can set the left and right delimiters.

11. What details do you need to pay attention to when using smarty?

Smarty is a template engine based on the MVC concept. It divides a page program into two parts for implementation: the view layer and the control layer.
That is to say, smarty technology combines the user UI with Separate from php code.
In this way, programmers and artists perform their respective duties without interfering with each other.

12. Pay attention to the following issues when using smarty:

(1) Configure smarty correctly. It is mainly necessary to instantiate the smarty object and configure the path of the smarty template file;

(2) Use assign assignment and display display page in the php page;

(3) It is not allowed to appear in the smarty template file PHP code snippet, all comments, variables, and functions must be included in delimiters.

6. Secondary development system (DEDE, ecshop)

1. Understanding of secondary development

2 Secondary development, to put it simply, is to customize and modify existing software, expand functions, and then achieve the functions you want. Generally speaking, the core of the original system will not be changed.

2, MVC

Model (model) data processing.

View Template display.

Controller (controller) controls the process.

What is the concept of MVC? What are the main tasks of each level?

MVC (Model-View-Controller) is a software design pattern or programming idea.

M refers to the Model model layer, V is the View layer (display layer or user interface), and C is the Controller layer.

The purpose of using mvc is to separate M and V, so that a program can easily use different user interfaces.

In website development,

The model layer is generally responsible for adding, deleting, modifying, and checking database table information,

The view layer is responsible for displaying page content, and

control The controller layer plays a regulating role between M and V. The controller layer decides which method of which model class to call.

After the execution is completed, the controller layer decides which view layer to assign the result to.

3. Some warnings and errors appear when accessing the secondary development program after installation

According to the errors, modify the server configuration parameters and Baidu

4. Functions, replacement of templates, addition and modification of functions

In fact, it is used for object-oriented applications, and replacement of templates is similar to the use of smarty

5 , What secondary development tools have you used?

Dedecms phpcms ecshop, if you have a good foundation, it will be no problem to learn these basic things.

6. Is it better to do primary development like PHP or secondary development?

Generally, small and medium-sized enterprises use cms system for secondary development, all for the sake of efficiency. Of course, if you want to develop it all at once, that’s fine, as long as you know how to use the framework and have enough time. Large companies develop by teams to avoid copyright issues.

7. In the secondary development process, how are the method accesses between many classes transmitted?

It is not class inheritance but object combination. Pass the instantiated objects through global

8. If dedecms changes the directory, a certain item in the background cannot be entered. How to solve it?

Change the background core settings to the current project directory name

9. Do you understand the custom model in dedecms?

There is the concept of content model in the DreamWeaver system. Different content models can be used to build sites with different content forms. The system comes with the following models: ordinary articles, photo albums, Software, products, classified information, special topics.

Through the system's own model, we can use it to build different types of sites. For example, you can use an atlas to build a picture site, and use a software model to build a software download site.

Of course, the above models that come with the system are called system models. Users can define some models themselves, such as books, music albums, etc. Only by customizing these models can they build sites with more content forms.

It is equivalent to us automatically adding the table structure to adapt to changes in current needs

10. Concepts in dede, designing and using templates, you must understand the following concepts

(1) Section (cover) template:

refers to the template used by the website homepage or the more important column cover channel. It is generally named with "index_identification ID.htm". In addition, A single page or custom tag defined by the user can also choose whether to support section template tags. If supported, the system will use the section template tag engine to parse before outputting the content or generating a specific file.

(2) List template:

refers to the template of the list of all articles in a certain column of the website, generally named with "list_identification ID.htm".

(3) File template:

represents the template of the document viewing page, such as the article template, which is generally named with "article_identification ID.htm".

(4) Other templates:

The general system generally includes templates: home page template, search template, RSS, JS compilation function template, etc. In addition, users can also customize a template to create Any file.

11. How many tags are used in dede?

List, content and other tags can only be used within their scope, list tags can only be used in lists, and content tags can only be used in content tags.

Global tags can be used in all pages

12. Familiar with common class libraries

(for example: dedesql.class.php); familiar with the system Function library (common.func.php); familiar with custom function library (extend.func.php); familiar with front-end entry file (common.inc.php)

7. WeChat public platform development

1. WeChat operating mechanism

What language is used to communicate between the official account and php: How to receive Xml

Weixin.php Public account data:

$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//Receive data XML data

2, message type

WeChat currently provides 7 basic message types, namely:

(1) Text message (text);

(2) Picture message (image);

( 3) Voice (voice)

(4) Video (video)

(5) Geographical location (location);

(6) Link message (link);

(7) Event push (event)

type. Master the data transfer format when sending different message types

3. The function to read the entire file into a string is

File_get_contents

4. Commonly used functions

The function that parses xml data into objects is

simplexml_load_string()

The function that converts strings into arrays is___ explode_________, the function that converts an array into a string is ____implode________.

The string that encodes the URL string is ____urlencode________.

5. The role of the Sprintf function

You can check the manual for this.

6. Why is the WeChat official account unable to provide services?

(1) Network reason, data interface reason

(2) Code error, how to guess the reason

Check where to modify, if the code is correct

You can output the data and take a look. Use php to operate files

$myfile = fopen(“newfile.txt”, “w”);
txt="aaaaaaaaaa";fwrite(txt ="aaaaaaaaaa";
fwrite(txt="aaaaaaaaaa";fwrite(myfile, txt);fclose(txt);
fclose(txt);fclose(myfile);
Copy after login

7, event push of custom menu

Click

Click to jump link

Scan the code to push the event

Scan the code to push and pop up

Pop up the event of the system taking pictures and post pictures

Pop up the event of the WeChat album poster

Pop up the geography Events of location selector

8, role of token

Security mechanism verification, used for security verification between WeChat server and PHP server

9. The role of Appid and secrect

When requesting the API interface (such as menu operation), you need to pass the appid and secrect values ​​to obtain the application authorization code

Thank you everyone for reading and I hope everyone has a smooth interview

Recommended tutorial: "php tutorial"

The above is the detailed content of 2021 PHP interview questions collection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template