PHP interview collection

1. Similarities and differences between Get and Post in form submission
get request is generally used to obtain data from the server, and post is generally used to submit data to the server
The parameters transmitted by get are in the url. There is a limit on the size of the parameters transmitted, and there is no limit on the size of post,
Get is not secure. post is more secure than get
The get request uses request Querystring accepts, and the post request uses requset Form acceptance

2. What is the base tag of HTML used for
It must be written in the head, and the base tag specifies the default address or default target for all links on the page

3.echo(),print(),print_ What's the difference between R?
echo is a PHP statement, print and print_r is a function, the statement has no return value, and the function can have a return value (even if it is useless)
Print () can only print out the value of simple type variables (such as int,string)
print_r () can print out the values of complex type variables (such as arrays and objects)
echo outputs one or more strings

4. Write a regular expression for email

/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

5. Convert array ['a', 'b', 'c'] into string 'abc'

echo  implode('',['a', 'b', 'c']); 
echo   join(['a', 'b', 'c'],'');

6. Get the position where A first appears in the string 'aAbB'

$str='aAbB';
echo strpos($str,"A");

7. Write a paragraph to realize the complete reverse order of strings with the minimum cost, and e.g. convert "1234567890" into "0987654321" (write and mark simple comments in the language you are most familiar with, instead of using functions,

$s = '1234567890';
$o = '';
$i = 0;
while(isset($s[$i]) && $s[$i] != null) {
    $o = $s[$i++].$o;
}

echo $o;

8. Please recursively implement a factorial evaluation algorithm F(n): n=5;F(n)=5!=54321=120

function F($n){    
 if($n==0){         
 return 1;      
 }else{         
 return $n* F($n-1);      
 }
}
var_dump(F(5));

9. Convert the character length Fang Zhi Gang into the form of hump method: FangZhiGang

//Method 1
function Fun($str){   
 if(isset($str) && !empty($str)){       
  $newStr='';       
  if(strpos($str,'-')>0){          
   $strArray=explode('-',$str);          
    $len=count($strArray);           
    for ($i=0;$i<$len;$i++){               
    $newStr.=ucfirst($strArray[$i]);           
    } 
          }      
           return $newStr;    }
           }
//Method 2 function Fun($str){  
 $arr1=explode('_',$str);   
 $str = implode(' ',$arr1);   
 return ucwords($str);
 }
 var_dump(Fun("fang-zhi-gang")); //FangZhiGang

10. What are the built-in sorting methods for arrays?

sort($array); //Array ascending sort
rsort($array); //Array descending sort

asort($array);  //Sorts the associative array in ascending order based on the value
ksort($array);  //Sort the associative array in ascending order according to the build

arsort($array);   //Sort the associative array in descending order based on the value
krsort($array);  // Sort the associative array in descending order according to the key

11. Write the code showing the client IP and server IP in PHP

$_SERVER["REMOTE_ADDR"]
$_SERVER["SERVER_ADDR"]

12. What is the difference between include and require statements? To avoid including the same file multiple times, use (?) Statements instead of them?

require It is unconditional inclusion, that is, if it is added to a process require,Whether the conditions are established or not, they will be implemented first require
include There is a return value, and require No,(Maybe that's why require Speed ratio of include fast)
When the containing file does not exist or the syntax is wrong require Is a fatal error terminating execution,include no

13. What is the difference between session and cookie?

session:Store globally unique variables accessed by users,Stored on the server php In the specified directory( session_dir)Storage at
cookie:It is used to store the information used when continuously accessing a page. It is stored on the client Cookie For example, it is stored in the user WIN of Temp In the directory.
Both can be set by time

14.PHP does not use the third variable to exchange the values of two variables

//Method 1
$a.=$b;
$b=str_replace($b,"",$a);
$a=str_replace($b,"",$a);

//Method 2
list($b,$a)=array($a,$b);
var_dump($a,$b);

15. Write a method to get the extension of the file

function get_extension($file){
   //Method 1   
   return  substr(strrchr($file,'.'), 1);   
   //Method 2   
   return  end(explode('.', $file));
}
echo  get_extension('fangzhigang.png'); //png

16. Print out the time of the previous day in PHP. The format is 2017-3-22 22:21:21

$a = date("Y-m-d H:i:s", strtotime("-1 days"));

17. What security should SQL statements consider

(1)prevent sql Inject, escape special characters, filter or use precompile sql Statement binding
(2)Use the principle of minimum permission, especially do not use root Account, micro different actions or operations to establish different accounts
(3)When sql In case of error, do not expose the information of database error to the client

18. Methods of optimizing mysql database

(1)Select the appropriate field and set the field to NOT NULL,When querying, the database does not need to be compared NULL;
(2)Use link( join)Replace subquery;
(3)Use union( UNION)Query instead of manually creating temporary tables;
(4)Minimize use( LIKE)Keywords and wildcards
(5)Using transaction and external health

19. For websites with large traffic, what methods will you use to solve the traffic?

(1)First, confirm whether the server hardware can support the current traffic;
(2)Optimize database access;
(3)Prohibit external chain theft;
(4)Control large file download;
(5)Use different hosts for shunting;
(6)Use flow analysis and statistics;

20.mysql_fetch_row() and MySQL_ fetch_ What's the difference between arrays?

These two functions return an array. The difference is that the array returned by the first function only contains values. We can only $row[0],$row[1],In this way, the data is read with the array subscript,

and MySQL_fetch_array()The returned array contains both the first and the form of key value pairs. We can read the data in this way (if the field in the database is username,passwd):$row['username']$row['passwd']

21. Several concepts of MySQL: primary key, foreign key, index and unique index

Primary key(primary key) An attribute or attribute group that uniquely identifies a row in a table. A table can only have one primary key, but can have multiple candidate indexes. Primary keys often form referential integrity constraints with foreign keys to prevent data inconsistency. The primary key can ensure that the record is unique and the primary key field is not empty,The database management system automatically generates a unique index for the primary key, so the primary key is also a special index.

Foreign key( foreign key) It is one or more columns used to establish and strengthen the link between two table data. Foreign key constraints are mainly used to maintain data consistency between two tables. In short, the foreign key of a table is the primary key of another table. The foreign key connects the two tables. In general, to delete the primary key in a table, you must first ensure that there is no same foreign key in other tables (that is, there is no foreign key associated with the primary key in the table).

Indexes(index) Is used to quickly find records with specific values. It is mainly for the convenience of retrieval and to speed up access. It is created according to certain rules and generally plays a sorting role. The so-called unique index is basically the same as the previous "ordinary index", but there is one difference: all values of the index column can only appear once, that is, they must be unique.

Summary:
A primary key must be a unique index. A unique index is not necessarily a primary key.
A table can have multiple unique indexes, but only one primary key.
Null values are not allowed for primary key columns, while null values are allowed for unique index columns.
The primary key can be referenced by other fields as a foreign key, while the index cannot be referenced as a foreign key.

22. What are the MySQL database engines?

MyISAM, ISAM,HEAP,InnoDB,BDB,CVS...

23. What is your understanding of the difference between MyISAM and InnoDB in mysql engine?

InnoDB and MyISAM Many people are using it MySQL The two most commonly used table types, which have their own advantages and disadvantages, depending on the specific application. The basic differences are: MyISAM Type does not support advanced processing such as transaction processing, and InnoDB Type support. MyISAM The type of table emphasizes the performance, and its execution ratio InnoDB Type is faster, but does not provide transaction support, and InnoDB It provides advanced database functions such as transaction support and external keys.

Here are some details and specific implementation differences:

MyISAM And InnoDB What is the difference between?
1, storage structure 
MyISAM: each MyISAM Stored as three files on disk. The name of the first file starts with the name of the table, and the extension indicates the file type..frm File storage table definition. The extension of the data file is.MYD (MYData). The extension of the index file is.MYI (MYIndex). 
InnoDB: All tables are saved in the same data file (or multiple files or independent tablespace files), InnoDB The size of the table is only limited by the size of the operating system file, which is generally 2 GB. 
2, storage space 
MyISAM: It can be compressed and the storage space is small. Three different storage formats are supported: static table(By default, but note that there should be no spaces at the end of the data, which will be removed),Dynamic table, compressed table.
InnoDB: If it needs more memory and storage, it will establish its special buffer pool in main memory for caching data and indexes.
3, Portability, backup and recovery
MyISAM: Data is stored in the form of files, so it will be very convenient in cross platform data transfer. A table can be operated separately during backup and recovery.
InnoDB: The free scheme can be copying data files and backup binlog,Or use mysqldump,When the amount of data reaches dozens G It's relatively painful when.
4, Transaction support
MyISAM: The emphasis is on performance, and each query is atomic,Its execution ratio InnoDB Type is faster, but does not provide transaction support.
InnoDB: Provide transaction support, transaction, external key and other advanced database functions. Have transaction(commit),RollBACK (rollback)And crash repair capability(crash recovery capabilities)Transaction security for(transaction-safe (ACID compliant))Type table.
5, AUTO_INCREMENT
MyISAM: You can create a federated index with other fields. The automatic growth column of the engine must be an index. If it is a combined index, the automatic growth can not be the first column. It can be sorted and incremented according to the previous columns.
InnoDB: InnoDB Must contain an index that has only this field. The auto growth column of the engine must be an index. If it is a composite index, it must also be the first column of the composite index.
6, Table lock difference
MyISAM: Only table level locks are supported. The user is operating myisam When you watch, select,update,delete,insert Statements will automatically lock the table. If the table after locking meets the requirements insert In case of concurrency, new data can be inserted at the end of the table.
InnoDB: Supports transaction and row level locks. Yes innodb The biggest feature of. Row locking greatly improves the new ability of multi-user concurrent operation. however InnoDB Line lock, just in WHERE The primary key of is valid and non primary key WHERE Will lock the whole watch.
7, Full text index
MyISAM: support FULLTEXT Full text index of type
InnoDB: I won't support it FULLTEXT Type, but innodb have access to sphinx The plug-in supports full-text indexing and works better.
8, Table primary key
MyISAM: Tables without any indexes and primary keys are allowed to exist. Indexes are the addresses where rows are saved.
InnoDB: If no primary key or non empty unique index is set, a 6-byte primary key will be automatically generated(User invisible),Data is a part of the primary index, and the additional index saves the value of the primary index.
9, Specific rows of the table
MyISAM: The total number of rows of the saved table, if select count(*) from table;The value will be taken out directly.
InnoDB: The total row number of the table is not saved, if used select count(*) from table;It will traverse the whole table, which consumes a lot, but it is added wehre After conditions, myisam and innodb It's handled the same way.
10, CURD operation
MyISAM: If a large number of SELECT,MyISAM Is a better choice.
InnoDB: If your data performs a lot of INSERT or UPDATE,For performance reasons, it should be used InnoDB Watch. DELETE In terms of performance InnoDB Better, but DELETE FROM table When, InnoDB The table will not be re created, but deleted row by row innodb If you want to empty a table with a large amount of data, it is best to use truncate table This command.
11, Foreign key
MyISAM: I won't support it
InnoDB: support
 Through the above analysis, it can basically be considered to use InnoDB To replace MyISAM The engine failed because InnoDB It has many good characteristics, such as transaction support, stored procedures, views, row level locking, etc. in the case of a lot of concurrency, I believe InnoDB You must be better than me MyISAM Much better. In addition, any kind of table is not omnipotent. Only by selecting the appropriate table type according to the business type can it be brought into full play MySQL Performance advantages. If it's not very complicated Web Applications, non critical applications, can still be considered MyISAM Yes, the specific situation can be considered by yourself.

24. Differences between redis and memache cache

Summary I:

1.data type

Redis Rich data types and support set list Equal type
memcache It supports simple data types and requires the client to handle complex objects by itself

2.persistence

redis Support data persistent storage
memcache Persistent data storage is not supported

3.Distributed storage

redis support master-slave Copy mode
memcache Consistency can be used hash Do distributed

value Different sizes

memcache Is a memory cache, key The length of is less than 250 characters, single item Storage should be less than 1 M,Not suitable for virtual machines

4.Different data consistency

redis The single thread model is used to ensure that the data is submitted in order.
memcache Need to use cas Ensure data consistency. CAS(Check and Set)It is a mechanism to ensure concurrency consistency, which belongs to the category of "optimistic lock"; The principle is very simple: take the version number, operate, compare the version number, operate if it is consistent, and give up any operation if it is inconsistent

5.cpu utilize

redis The single threaded model can only use one cpu,Can open multiple redis process

Summary 2:

1.Redis In, not all data is always stored in memory, which is the same as Memcached Compared to one of the biggest differences.
2.Redis Not just simple k/v Also provide the type of data at the same time list,set,hash And other data structures.
3.Redis Support data backup, i.e master-slave Mode data backup.
4.Redis Data persistence is supported. The data in memory can be kept on disk and can be loaded again for use when restarting.
Personally, I think the most essential difference is Redis It has the characteristics of database in many aspects, or it is a database system, and Memcached It's just simple K/V cache

Summary 3:

redis and memecache The differences are:

1,Storage method:
memecache Store all the data in the memory. It will hang up after power failure. The data cannot exceed the size of the memory
redis Some of them are stored on the hard disk, which can ensure the persistence of data.
2,Data support type:
redis In terms of data support memecache More.
3,Using the underlying model is different:
New version redis Directly build it yourself VM Mechanism, because if the general system calls the system function, it will waste some time to move and request.
4,Different operating environments:
redis At present, the official only supports Linux Go up, so as to save the support for other systems. In this way, you can better focus on the optimization of the system environment, although a team from Microsoft later wrote a patch for it. But not on the trunk

memcache It can only be used as a cache, cache
redis The content of can be landed, that is to say, with MongoDB Something similar, and then redis It can also be used as a cache and can be set master-slave

25. There are three columns a, B and C in the table, which are realized by SQL statement: select column a when column A is greater than column B, otherwise select column B, select column B when column B is greater than column C, otherwise select column C.

drop table table1  create table table1(  
    a int,  
    b int,  
    c int  )  insert into table1 values(22,24,23)  
  select * from table1  
  select (case when a>b then a else b end),(case when b>c then b else c end)  from table1  
  select (case when a>b then a  
             when a>c then a  
             when b>c then b else c  
             end)  from table1

26. When installing Linux system, use netconfig program to configure the network. What should be input?

Will let the user enter the host name, domain name, domain name server IP Address, gateway address, subnet mask and other necessary information

27. How does PHP write an interface for others to call?

public function  authenticationApi($data,$url){       
  $ch  = curl_init();       
  curl_setopt($ch, CURLOPT_URL, $url);        
  curl_setopt($ch, CURLOPT_POST, 1);        
  curl_setopt($ch, CURLOPT_HEADER, 0);        
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
  //The output format can be converted to json format in the form of array        
  $tmpInfo = curl_exec($ch);        
  curl_close($ch);        
  return $tmpInfo;    
}

28. Use PHP header() function to realize the error prompt function of page 404

Header("HTTP/1.1 404 Not Found");

29.heredoc structure and usage

echo <<<EOT
   <html>
   <head><title>homepage</title></head>
   <body>Home page content</body>
   </html>
EOT;

Note: the line containing the end identifier cannot contain any other characters except";"

30. Structure and usage of nowdoc

$str = <<<'EOD'
       Example of string
       spanning multiple lines
       using nowdoc syntax.
EOD;

31.javascript program code to judge whether the pop-up window is shielded

var wroxWin = window.open("http://www.111cn.net", "_blank");if (wroxWin == null) {
    alert("too bad! Pop ups are blocked");}

32. Functions for PHP serialization and deserialization

serialize() serialize
unserialize() Deserialization

33. Use the structure in the table below to write the SQL statements (members(id,username,posts,pass,email) of the names of the ten people with the largest number of posts

select memebers.username from members group by posts desc limit 10

34,. Install PHP as an Apache module in the file http The statement (?) should be used first in conf Dynamically load the PHP module, and then use the statement (?) Make Apache treat all files with PHP extension as PHP scripts.

1.LoadModule php5_module "c:/php/php5apache2.dll")
2.AddType application/x-httpd-php .php

35. What are the transactions in the database?

A transaction is a series of operations,These operations complete a task. As long as one of these operations fails,The transaction operation failed,A rollback event occurred. That is, undo the previous operation,This ensures data consistency. And you can temporarily put the operation in the cache,When all operations are successful, the database is submitted,This ensures that time-consuming operations are effective.

36. Advantages and disadvantages of Apache and nginx

nginx Lightweight, better than apache Occupy less memory and resources, anti concurrency, nginx Processing requests is asynchronous and non blocking, and apache It is blocking type, which is issued in high parallel nginx It can maintain low resource consumption and high performance. apache be relative to nginx Advantages: rewrite than nginx of rewrite Strong, less bug,stable. (performance required) nginx,Seek stability apache). 

37. Calculate the difference between two dates, such as the date difference from February 5, 2007 to March 6, 2007

// Method 1: use DateTime class
$day1 = '2003-09-16';
$day2 = '2011-11-23';
$d1 = new dateTime($day1);
$d2 = new dateTime($day2);
echo $d1->diff($d2)->days;

// Method 2: time stamp calculation
echo (strtotime($day2) - strtotime($day1))/(24*3600);

38. What is the following code for? Please explain``$ date``=``'08/26/2003'``;

print ereg_replace("([0-9]+)/([0-9]+)/([0-9]+)","\\2/\\1/\\3",$date);

This is to convert a date from MM/DD/YYYY format to DD/MM/YYYY format. A good friend of mine told me that this regular expression can be disassembled into the following statements. For such a simple expression, there is no need to disassemble it, just for the convenience of explanation:

//Corresponds to one or more 0-9, followed by a slash $regExpression = "([0-9] +) /";

//One or more 0-9 should be followed by another slash $regexpression= "([0-9]+)/";

//Once again, it corresponds to one or more 0-9 $regexpressions= "([0-9]+)"; As for \ \ 2 / \ \ 1 / \ \ 3, it is used to correspond to parentheses. The first parenthesis is for the month

39. In PHP, the name of the current script (excluding path and query string) is recorded in the predefined variable (?) Medium; The URL linked to the current page is recorded in the predefined variable (?) Yes.

(1) echo $_SERVER['PHP_SELF']; 
(2) echo $_SERVER["HTTP_REFERER"];

40. The parameter of a function cannot be a reference to a variable, unless in PHP Ini (?) Set to on ​​​​​​​

allow_call_time_pass_reference

Keywords: PHP

Added by tuneout on Mon, 07 Feb 2022 22:53:51 +0200