Related recommendations: "2019 PHP Interview Questions Summary (Collection)"
1. Basic PHP Part
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: The get method url parameter is 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.
Suggestions:
1. The get type is less secure than the Post type. It contains confidential information. It is recommended to use the Post data submission type;
2. It is recommended to use Get for data query. For adding, modifying or deleting data, it is recommended to use the Post method;
The get method used by Baidu, because it can be seen from its URL
3. Master which frameworks and templates of PHP Engines, systems, etc.
Frameworks: There are many frameworks, such as CI, Yii, Laravel, etc. What we have learned is thinkphp
Template engines: There are also many, including them in textbooks, we learn 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. What we have learned is DEDECMS, Ecshop
4. Tell me what web front-end technologies you have mastered?
Proficient in DIV 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 verification code to prevent registration machine 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, MVC three-layer structure is often adopted 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 realize code separation, so that the same program can use different expressions
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 in PHP that handles json format 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 it will be faster if it just outputs echo. Print_r is usually used to print information about variables, usually 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 For 'session service', you need to enable the service when using it. Cookies do not need to be enabled. You can use
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() compares two or 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() Insert one or more elements into the array end of the array (push)
(11) array_pop() pops and returns the last unit of the array array (push)
(12) array_walk() uses a user-defined function to Callback processing is performed on each element in
14. What are the common functions for PHP to process strings? (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, and calculate the length of the Chinese string)
(4) substr() returns the string part of Is a string;
(8) str_shuffle () randomly shuffles a string
(9) sprintf() returns a string generated based on a formatted string (usually used to obtain points The data table name after the table)
(10) strstr() finds the first occurrence of the string
(11) addslashes uses backslashes to quote the string
15, Common functions for processing time in PHP? (Focus on the ‘parameters’ and ‘return value’ of the function)
(1) date() formats 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() Parses 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. Common functions used in 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. What are the commonly used functions for operating files in PHP? (Focus on the 'parameters' and 'return value' of the function)
(1) Open the file fopen()
(2) Read the file fgets(); Note: file_get_contents() is also Read the file
(3) Write the file fwrite(); Note: file_put_contents() can also write the file
(4) Close the file handle fclose()
(5) Move/rename the file rename()
(6) Copy the file copy()
(7) Create the 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) Determine whether it is a directory is_dir()
18. Commonly used functions in 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 the directory rmdir()
(4) Close the directory handle closedir()
(5) Create the directory mkdir()
(6) Return the directory in the path Part dirname()
(7) Get the current working directory getcwd()
(8) List the files and directories in the specified path scandir()
2. Database partWhat are the common relational database management system products?
Answer: Oracle, SQL Server, MySQL, Sybase, DB2, Access, etc. 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
What are the integrity constraints included?
Data integrity (Data Integrity) refers to the accuracy (Accuracy) and reliability (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.
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 made 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.
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
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.
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.
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 atomic constraint on attributes, which requires attributes to be atomic and cannot be decomposed;
Second normal form: 2NF is a unique constraint on records, which requires records There is 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 fields are 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 the view?
(1) Views can simplify user operations
(2) Views enable users to view the same data from multiple angles;
(3) Views provide database 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 are the differences between primary keys, foreign keys and indexes?
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 – the foreign key of a table is the primary key of another table. The foreign key can have duplicates and can be a null value
Index – the field has no duplicate values, but can have a null value
Function:
Primary key – used to ensure data integrity
Foreign key – used to establish connections with other tables
Index – used to increase the speed of query sorting
Number:
Primary key – there can only be one primary key
Foreign keys – a table can have multiple foreign keys
Index – a table can have multiple unique indexes
What can you use to ensure that fields in a table only accept specific ranges The value in ?
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 the where tables must be written before other Where conditions, and those conditions that can filter out the maximum number of records must be written at the end of the Where clause .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 per 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 large 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 an idea based on Process-oriented means that object-oriented implements 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 a memory space dynamically allocated during program running. You The size of the heap memory to be allocated can be determined based on the running conditions of the program.
4. The main difference between XML and HTML
The grammatical requirements are different:
(1) It is not case-sensitive in html, but strictly distinguished in xml.
(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 program interdependence from causing problems. Impact of future changes.
Inheritance:
When defining and implementing a class, it can be done on the basis of an existing class, and the The content is regarded as its own content, and some new content can be added, or the original method can be modified 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 in the program It is determined during running time that a reference variable will point to an instance object of which class. The method call issued by the reference variable is a method implemented in which class. This must be determined during the running of the program.
Abstract:
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 Will ignore those aspects that are irrelevant to the current topic and goal, and focus on 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) is exactly the opposite of 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 methods of the parent class, give an example
Overloading means overriding the methods of the parent class, that is, using the methods in the subclass to replace the methods inherited from the parent class. , also called method rewriting.
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.
__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 -> to 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. What is the working principle of the __autoload() method?
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 part1. 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 the debugging mode and running mode Related constants (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 some needs Great for query-heavy applications, but not very good for large 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 wildcards. 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 arrays for query conditions, which is a safer way;
(2) If string query conditions must be used as a last resort, use the preprocessing mechanism;
(3) Use binding parameters
(4) Enable 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 perform custom filtering for applications;
(6) Use field type checking, automatic verification, and automatic completion mechanisms to avoid the input of malicious data.
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:
// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为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 will not be affected by the cache; strictly check file case (even on Windows platforms) to help you advance Discover Linux deployment issues; It can be conveniently used in different stages of the development process, including development, testing and demonstration, and any other necessary situations. Different application modes can be configured with independent project configuration files.
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
Above It is the loading order of configuration files. Because the later configuration will overwrite the previous configuration with the same name (if it is not effective), 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, SERVER, _ENV, $_POST, $_GET, REQUEST, _REQUEST, REQUEST, _SESSION and $_COOKIE variables
(2) Get system variables:
{KaTeX parse error: Expected 'EOF', got '}' at position 25: …ver.script_name}̲ // 输出_SERVER[‘SCRIPT_NAME’]变量 {KaTeX parse error: Expected 'EOF', got '}' at position 22: …session.user_id}̲ // 输出_SESSION[‘user_id’]变量 {KaTeX parse error: Expected 'EOF', got '}' at position 21: ….get.pageNumber}̲ // 输出_GET[‘pageNumber’]变量 {KaTeX parse error: Expected 'EOF', got '}' at position 18: …ink.cookie.name}̲ // 输出_COOKIE[‘name’]变量
13. 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 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 to separate PHP programs from artists, so that programmers can Changing the logical content of the program 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 particularly important in multi-person collaboration projects. (It is also easy to develop multi-style programs)
Smarty advantages
(1) Fast: compared 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 needs to update data frequently
(2)小项目。小项目因为项目简单而美工与程序员兼于一人的项目
3、在模板中使用{$smarty}保留变量
{KaTeX parse error: Expected 'EOF', got '}' at position 16: smarty.get.page}̲ //类似在php脚本中访问_GET[page] {KaTeX 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.}
在模板中访问php中的变量
5、变量调解器
2018PHP经典面试题大全汇总(更新)-PHP面试题
6、php查询mysql数据库时,查询中文结果时出现的乱码。怎么解决?
(1)文件meta(设置浏览器解析的时候)
(2)连接数据库时编码设定
(3)PHP文件中使用header函数确定编码
7、缓存机制
如果开启了缓存,smarty同时生成一份静态的html页面,如果在设定的时间没有过期,再次访问的时候,你访问的就是是html文件了,减少了读取数据库,所以就效率来说,要高一些。
8、smarty的赋值和载入模板
$Smarty->assign(name,value) $Smarty->display(‘index.html’)
9、marty模板技术的用途是什么?
为了php与html分开,美工和程序员各司其职,互不干扰。
10、smarty配置主要有哪几项?
(1)引入smarty.class.php;
(2) 实例化smarty对象;
(3)重新修改默认的模板路径;
(4)重新修改默认的编译后文件的路径;
(5)重新修改默认的配置文件的路径;
(6)重新修改默认的cache的路径。
(7) 可以设置是否开启cache。
(8)可以设置左侧和右侧定界符。
11、smarty在使用过程中需要注意哪些细节?
Smarty是基于MVC概念的一种模板引擎,它将一个页面程序分成了两部分来实现:即视图层和控制层,
也就是说smarty技术将用户UI与php代码分离开。
这样程序员和美工各司其职,互不干扰。
12、smarty运用过程中要注意以下几个问题:
(1)正确配置smarty。主要要实例化smarty对象,配置smarty模板文件的路径;
(2)php页面中使用assign赋值 和display显示页面;
(3)smarty模板文件中不允许出现php代码段,所有的注释,变量,函数都要包含在定界符内。
六、二次开发系统(DEDE、ecshop)
1、对二次开发的理解
二次开发,简单的说就是在现有的软件上进行定制修改,功能的扩展,然后达到自己想要的功能,一般来说都不会改变原有系统的内核。
2、MVC
Model(模型)数据处理。
View(视图) 模板显示。
Controller(控制器) 控制流程。
MVC的概念是什么?各层主要做什么工作?
MVC(即模型-视图-控制器)是一种软件设计模式或者说编程思想。
M指Model模型层,V是View视图层(显示层或者用户界面),C是Controller控制器层。
使用mvc的目的是实现M和V分离,从而使得一个程序可以轻松使用不同的用户界面。
在网站开发中,
模型层一般负责对数据库表信息进行增删改查,
视图层负责显示页面内容,
控制器层在M和V之间起到调节作用,控制器层决定调用哪个model类的哪个方法,
执行完毕后由控制器层决定将结果assign到哪个view层。
3、二次开发程序安装后访问时候出现一些警告以及错误
根据错误,来修改服务器配置参数以及百度
4、功能,模板的更换,功能的添加修改
其实也就是面向对象的应用 用,以及模板的更换类似smarty的使用
5、用过哪些二次开发的东西?
Dedecms phpcms ecshop,基本这些的东西如果基础好了 学习起来都是没问题的。
6、像php做一次开发好,还是二次开发好?
一般中小企业都用cms系统二次开发,都是为了效率。当然如果想一次开发也行,会用框架而且时间充足的话就可以了,大企业都是团队来开发的,杜绝版权问题。
7、二次开发过程中很多类与类之间进行之间的方法访问,是通过什么方式传递的?
不是类继承而是对象组合,把实例化好的对象通过global传递进去
8、dedecms如果更换目录,后台某项就进不去了如何解决?
后台核心设置中修改成现在的 项目目录名称
9、dedecms中自定义模型的理解?
在织梦系统中有内容模型这个概念,不同内容模型可以用来构建不同内容形式的站点,在系统中自带了以下几种模型:普通文章、图集、软件、商品、分类信息、专题。通过系统自带的模型,我们可以用来构建不同类型的站点,例如:使用图集可以做一个图片站,用软件模型构建一个软件下载站点。
当然以上随系统附带的模型被称为系统模型,用户可以自己定义一些模型,比如图书、音乐专辑等,自定义了这些模型才可以构建更多内容形式的站点。
相当于我们自动添加了表结构,适应现在当前需求的变化
10、dede中概念,设计和使用模板,必须要理解下面几个概念
(1)板块(封面)模板:
指网站主页或比较重要的栏目封面频道使用的模板,一般用“index_识别ID.htm”命名,此外,用户单独定义的单个页面或自定义标记,也可选是否支持板块模板标记,如果支持,系统会用板块模板标记引擎去解析后才输出内容或生成特定的文件。
(2)列表模板:
指网站某个栏目的所有文章列表的模板,一般用 “list_识别ID.htm” 命名。
(3) 档案模板:
表示文档查看页的模板,如文章模板,一般用 “article_识别ID.htm” 命名。
(4) 其它模板:
一般系统常规包含的模板有:主页模板、搜索模板、RSS、JS编译功能模板等,此外用户也可以自定义一个模板创建为任意文件。
11、dede中几种标签的使用?
列表 内容 等标签 只能在其本范围内使用,列表标签只能在列表中使用,内容标签只能在内容标签中使用。
全局标签能在所有页面中使用
12、熟悉常用类库
(例如:dedesql.class.php);熟悉系统函数库(common.func.php);熟悉自定义函数库(extend.func.php);熟悉前台入口文件(common.inc.php)
七、微信公众平台开发
1、微信运行机制
公众号与php之间用什么语言通信:Xml
Weixin.php中是如何接收公众号数据的:
$postStr = $GLOBALS[“HTTP_RAW_POST_DATA”];//接收数据 XML数据
2、消息类型
微信目前提供了7种基本消息类型,分别为:
(1)文本消息(text);
(2)图片消息(image);
(3)语音(voice)
(4)视频(video)
(5)地理位置(location);
(6)链接消息(link);
(7)事件推送(event)
类型。掌握不同的消息类型发送时的数据传递格式
3、将整个文件读入一个字符串的函数是
File_get_contents
4、常用函数
把xml数据解析成对象的函数是
simplexml_load_string( )
将字符串转换为数组的函数是___ explode_________,将数组转化为字符串的函数是____implode________.
编码 URL 字符串的字符串是____urlencode________.
5、Sprintf函数的作用
这个都是可以查手册的。
6、微信公众号出现无法提供服务的原因?
(1)网络原因 ,数据接口原因
(2)代码错误,怎么推测原因
修改的哪里检查一下,如果代码没错
可以输出数据 看一下。用php操作文件
$myfile = fopen(“newfile.txt”, “w”); txt="aaaaaaaaaa";fwrite( txt ="aaaaaaaaaa";fwrite(txt="aaaaaaaaaa";fwrite(myfile, txt);fclose( txt);fclose(txt);fclose(myfile);
7、自定义菜单的事件推送
单击
单击跳转链接
扫码推事件
扫码推且弹出
弹出系统拍照发图的事件
弹出微信相册发图器的事件
弹出地理位置选择器的事件
8、token的作用
安全机制验证,用于微信服务器与PHP服务器之间的安全验证
9、Appid与secrect的作用
请求api接口(例如菜单的操作)时需要传appid与secrect两个值,用来获取应用的授权码
laravle面试题
PHP7 和 PHP5 的区别,具体多了哪些新特性?
性能提升了两倍
结合比较运算符 (<=>)
标量类型声明
返回类型声明
try…catch 增加多条件判断,更多 Error 错误可以进行异常处理
匿名类,现在支持通过new class 来实例化一个匿名类,这可以用来替代一些“用后即焚”的完整类定义
…… 了解更多查看文章底部链接 PHP7 新特性
为什么 PHP7 比 PHP5 性能提升了?
变量存储字节减小,减少内存占用,提升变量操作速度
改善数组结构,数组元素和 hash 映射表被分配在同一块内存里,降低了内存占用、提升了 cpu 缓存命中率
改进了函数的调用机制,通过优化参数传递的环节,减少了一些指令,提高执行效率
laravel 模块
服务提供者是什么?
服务提供者是所有 Laravel 应用程序引导启动的中心, Laravel 的核心服务器、注册服务容器绑定、事件监听、中间件、路由注册以及我们的应用程序都是由服务提供者引导启动的。
IoC 容器是什么?
IoC(Inversion of Control)译为 「控制反转」,也被叫做「依赖注入」(DI)。什么是「控制反转」?对象 A 功能依赖于对象 B,但是控制权由对象 A 来控制,控制权被颠倒,所以叫做「控制反转」,而「依赖注入」是实现 IoC 的方法,就是由 IoC 容器在运行期间,动态地将某种依赖关系注入到对象之中。
Simply speaking, its function is to use dependency injection to decompose complex applications into cooperating objects, thereby reducing the complexity of problem solving and achieving low coupling and high expansion of application code.
The service container in Laravel is a tool used to manage class dependencies and perform dependency injection.
What are Facades?
Facades (a design pattern, usually translated as appearance mode) provides a "static" (static) interface to access classes registered in the IoC container. Provides a simple, easy-to-remember syntax without having to remember long class names that must be manually injected or configured. Additionally, testing is made very easy due to the unique use of PHP's dynamic methods.
What is Contract?
Contract (contract) is the interface for laravel to define the core services provided by the framework. There is no essential difference between Contract and Facades. Their function is to make the interface less coupled and simpler.
The principle of dependency injection?
I won’t explain this. This is the prerequisite for understanding IoC containers.
What is Composer and how does it work?
Composer is a dependency management tool for PHP. The working principle is to download the developed extension package from the packagist.org composer repository into our application, and declare dependencies and version control.
Caching
What is the difference between Redis and Memecached?
Redis supports richer data storage types, String, Hash, List, Set and Sorted Set. Memcached only supports simple key-value structures.
Memcached key-value storage has higher memory utilization than Redis using hash structure for key-value storage.
Redis provides transaction functions to ensure the atomicity of a series of commands
Redis supports data persistence and can keep data in memory on disk
Redis only uses a single core, while Memcached can use multiple cores, so on average Redis has higher performance than Memcached when storing small data on each core.
How does Redis achieve persistence?
RDB persistence saves the state of redis in memory to the hard disk, which is equivalent to backing up the database state.
AOF persistence (Append-Only-File), AOF persistence records the database by saving the write status of Redis server lock execution. Equivalent to the commands received by the backup database, all commands written to AOF are saved in the redis protocol format.
Database
What is an index and what is its function? What are the common index types? Mysql indexing principles?
Indexes are special files that contain reference pointers to all records in the data table, which are equivalent to the table of contents in a book. Its function is to speed up data retrieval efficiency. Common index types include primary key, unique index, composite index, and full-text index.
Principles of index creation
Leftmost prefix principle
Choose columns with high differentiation as indexes
Expand the index as much as possible, do not create a new index
How to deal with high concurrency?
Use cache
Optimize the database and improve database usage efficiency
Load balancing
I won’t go into details about the design pattern of PHP, but the SOLID design principle is Every PHPer must master it.
The above is the detailed content of Complete collection of PHP interview questions (worth collecting). For more information, please follow other related articles on the PHP Chinese website!