This article brings you relevant knowledge about PHP, which mainly introduces PHP interview questions and summarizes thirty-nine common There are many types of PHP interview questions, but they are all inseparable from the basic and common PHP interview questions. I hope it will be helpful to everyone.
## Recommended study: "
PHP Tutorial"
Zip: -r Pack the directory : zip file1.zip file1.txtDecompress: unzip file1.zip
Int Integer char Fixed-length character Varchar Variable-length character Datetime Datetime type Text Text type The difference between Varchar and char char is a fixed-length character type. How much space is allocated will occupy as much space. Varchar is a variable-length character type. It takes up as much space as the content is, which can effectively save space. Since the varchar type is variable, the server has to perform additional operations when the data length changes, so the efficiency is lower than that of the char type.
The MyISAM type does not support transactions and table locks, and is prone to fragmentation. It needs to be optimized frequently and has faster reading and writing speeds, while the InnoDB type supports transactions, row locks, and has crash recovery capabilities. Read and write speeds are slower than MyISAM.
Create index: alert table tablename add index (`field name`)
Understanding: When session_start() is turned on, a constant SID is generated. When COOKIE is turned on, this constant is empty. When COOKIE is turned off, the value of PHPSESSID is stored in this constant. By adding a SID parameter after the URL to pass the value of SESSIONID, the client page can use the value in SESSION. When the client opens COOKIE and the server opens SESSION. When the browser makes the first request, the server will send a COOKIE to the browser to store the SESSIONID. When the browser makes the second request, the existing
Isset determines whether the variable exists. You can pass in multiple variables. If one of the variables does not exist, it returns false. empty determines whether the variable is empty and false. Only one variable can be passed. If Returns true if empty or false.
Answer: There are two main ways:
1) Snapshot persistence
has been automatically enabled in the redis configuration file,
The format is: save N M
means that within N seconds, if redis is modified at least M times, redis will take a snapshot to the disk.
Of course we can also manually execute the save or bgsave (asynchronous) command to make a snapshot
2) append only file AOF persistence
There are three modes in total, such as
appendfsync The default of everysec is to force writing to the disk once per second
appendfsync always Force to write to the disk every time a write operation is performed
appendfsync no completely depends on the OS and performance The best but persistence cannot be guaranteed
The third mode is the best. Redis also adopts the third mode by default.
Answer: There are two commonly used ones, one is innodb and the other is myisam. The main difference between the two is
1) myisam does not support transaction processing, but innoDB supports transaction processing
2) myisam does not support foreign keys, innoDB supports foreign keys
3) myisam supports full-text retrieval, and innoDB only supports full-text search after MySQL version 5.6
4) The storage form of data is different. The mysiam table is stored in three files: structure, index, and data. InnoDB storage stores the structure as a file and index. And the data is stored as a file
5) myisam has better performance than innoDB in querying and adding data, and innoDB has higher performance in batch deletion.
6) myisam supports table locks, while innoDB supports row locks
Answer: SQL injection attacks refer to users or hackers passing in special inputs as parameters to our web application. Most of these inputs are some combinations in SQL syntax. By executing The SQL statement then performs the operation desired by the attacker. The main reason is that the programmer did not carefully filter the data entered by the user, causing illegal data to invade the system. Therefore, we must prevent sql injection during the development process, mainly from two aspects:
1) The placeholder method is to preprocess the sql statement and then execute the sql statement
2) Use addslashes or mysql_real_escape_string to escape the values entered by the user and escape some special characters.
Answer: I have used it before. In the PDO class, there is a prepare method that can implement preprocessing. The exclude method in the PDOStament class can perform preprocessing. There are two types of preprocessing parameters. One is :String placeholder, the other is ? placeholder, :string placeholder passes in an associative array when performing preprocessing and passing parameters, while ? placeholder passes in an index array. The two cannot be mixed, but it is generally recommended to use: string placeholder.
Answer: Generally, mature open source frameworks take data security into consideration, but sometimes we When some native SQL statements may be used, we need to consider preprocessing the SQL statements ourselves. Of course, sometimes we don't want to use the filtering method in the framework. For example, when using a text editor, we can use our own filtering method.
Answer: MySQL optimization is mainly achieved from the following aspects:
1) Design perspective: selection of storage engine, field type selection, paradigm
2 ) Functional perspective: You can make use of MySQL's own features, such as indexing, query caching, defragmentation, partitioning, sub-tables, etc.
3) Optimization of SQL statements: Try to simplify the query statement and use as few query fields as possible Reduce query fields, optimize paging statements, grouping statements, etc.
4) Deploy a heavy load architecture system: the database server is separated. When the load is heavy, master-slave replication and read-write separation mechanism can be used for design
5) Upgrade the database server from the hardware.
Pass by value: Any changes to the value within the function scope will be ignored outside the function
Pass by reference: Any change to the value within the function scope will also be ignored outside the function Reflecting these modifications
Pros and Cons: When passing by value, PHP must copy the value. Especially for large strings and objects, this can be a costly operation. Passing by reference does not require copying the value, which is good for improving performance.
Set PHP's error reporting level and return the current level.
Principle: Quick sort uses the divide-and-conquer strategy to divide the data sequence to be sorted into Two subsequences, the specific steps are:
(1) Pick an element from the sequence, call this element "baseline".
(2) Scan the array once, and arrange all the elements smaller than the "base" in front of the base, and all the elements larger than the "base" in the back of the base.
(3) Through recursion, divide each subsequence into smaller sequences until the subarray of elements smaller than the reference value and the subarray of elements greater than the reference value are sorted.
//快速排序(数组排序) function QuickSort($arr){ $num = count($arr); $l=$r=0; for($i=1;$i<$num;$i++){ if($arr[$i] < $arr[0]){ $left[] = $arr[$i]; $l++; }else{ $right[] = $arr[$i]; $r++; } } if($l > 1){ $left = QuickSort($left); } $new_arr = $left; $new_arr[] = $arr[0]; if($r > 1){ $right = QuickSort($right); } for($i=0;$i<$r;$i++){ $new_arr[] = $right[$i]; } return $new_arr; }
//二分查找(数组里查找某个元素) function bin_sch($array, $low, $high, $k){ if ($low <= $high){ $mid = intval(($low+$high)/2); if ($array[$mid] == $k){ return $mid; }elseif ($k < $array[$mid]){ return bin_sch($array, $low, $mid-1, $k); }else{ return bin_sch($array, $mid+1, $high, $k); } } return -1; } //顺序查找(数组里查找某个元素) function seq_sch($array, $n, $k){ $array[$n] = $k; for($i=0; $i<$n; $i++){ if($array[$i]==$k){ break; } } if ($i<$n){ return $i; }else{ return -1; } }
//二维数组排序, $arr是数据,$keys是排序的健值,$order是排序规则,1是升序,0是降序 function array_sort($arr, $keys, $order=0) { if (!is_array($arr)) { return false; } $keysvalue = array(); foreach($arr as $key => $val) { $keysvalue[$key] = $val[$keys]; } if($order == 0){ asort($keysvalue); }else { arsort($keysvalue); } reset($keysvalue); foreach($keysvalue as $key => $vals) { $keysort[$key] = $key; } $new_array = array(); foreach($keysort as $key => $val) { $new_array[$key] = $arr[$val]; } return $new_array; }
class regx { public static function check($str) { if(preg_match("/^([1-9,])+$/",$str)) { return true; } return false; } } $str="12345,6"; if(regx::check($str)) { echo "suc"; } else { echo "fail"; }
class Db { private static $instance; public $handle; Private function __construct($host,$username,$password,$dbname) { $this->handle=NULL; $this->getcon($host,$username,$password,$dbname); } public static function getBb() { self::$instance=new Db(); return self::$instance; } private function getcon($host,$username,$password,$dbname) { if($this->handle!=NULL){ return true; } $this->handle=mysqli_connect($host,$username,$password,$dbname); } }
A ) SQLite Database
B) MySQL Database
C) Shared Memory
D) File System
E) Session Server
Answer: The reason is: Chinese is composed of multi-bytes, and only a single English character in the English system has only one byte, so the system converts each byte of Chinese All have been processed by strtolower(), and the changed Chinese characters will become garbled when spliced together (the characters corresponding to the newly generated encoding map may not be Chinese)
Manual solution: use str_split(string string , intstring, intsplit_length = 1) Cut by each byte, like Chinese can be cut into three bytes. If the recognized bytes are English letters, they will be converted.
<?php function mystrtoupper($a){ $b = str_split($a, 1); $r = ''; foreach($b as $v){ $v = ord($v); if($v >= 97 && $v<= 122){ $v -= 32; } $r .= chr($v); } return $r; } $a = 'a中你继续F@#$%^&*(BMDJFDoalsdkfjasl'; echo 'origin string:'.$a."\n"; echo 'result string:'; $r = mystrtoupper($a); var_dump($r);
Answer: The bug exists in two aspects,
1) In winddowns, when the file only has a read-only attribute, the is_writeable() function returns false. When true is returned, the file is not necessarily writable. of.
If it is a directory, create a new file in the directory and check by opening the file;
If it is a file, you can test whether the file is writable by opening the file (fopen).
2) In Unix, when safe_mode is turned on in the php configuration file (safe_mode=on), is_writeable() is also unavailable.
Read the configuration file to see if safe_mode is enabled.
/** * Tests for file writability * * is_writable() returns TRUE on Windows servers when you really can't write to * the file, based on the read-only attribute. is_writable() is also unreliable * on Unix servers if safe_mode is on. * * @access private * @return void */ if ( ! function_exists('is_really_writable')) { function is_really_writable($file) { // If we're on a Unix server with safe_mode off we call is_writable if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE) { return is_writable($file); } // For windows servers and safe_mode "on" installations we'll actually // write a file then read it. Bah... if (is_dir($file)) { $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100)); if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) { return FALSE; } fclose($fp); @chmod($file, DIR_WRITE_MODE); @unlink($file); return TRUE; } elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) { return FALSE; } fclose($fp); return TRUE; } }
答:用getimagesize来判断上传图片的类型比$_FILES函数的type更可靠
同一个文件,使用不同的浏览器php返回的type类型是不一样的,由浏览器提供type类型的话,
就有可能被黑客利用向服务器提交一个伪装撑图片后缀的可执行文件。
可以通过getimagesize()函数来判断上传的文件类型,如果是头像文件 会返回这样的一个数组
Array ( [0] => 331 [1] => 234 [2] => 3 [3] => width="331" height="234" [bits] => 8 [mime] => image/png );
答:基本原则:不对外界展示服务器或程序设计细节(屏蔽错误),不相信任何用户提交的数据(过滤用户提交)
1)屏蔽错误,将display_errors 设置为off
2)过滤用户提交参数,这里需要注意的是不能仅仅通过浏览器端的验证,还需要经过服务器端的过滤
这里是需要注意最多的地方,因为所有用户提交的数据入口都在这里,这是过滤数据的第一步。 1 考虑是否过滤select,insert,update,delete,drop,create等直接操作数据的命令语句 2 使用addslashes 将所有特殊字符过滤 3 打开magic_quotes_gpc,开启该参数数后自动将sql语句转换,将 ' 转换成 \'
3)可以考虑设置统一入口,只允许用户通过指定的入口访问,不能访问未经许可的文件等内容
4)可以考虑对安全性要求高的文件进行来源验证,比如要想执行b.php必须先执行a.php,可以在b.php中判断来自a.php的referer,避免用户直接执行b.php
答:由于 –enable-cli 和 –enable-cgi 同时默认有效,因此,不必再配置行中加上 –enable-cli 来使得 CLI 在 make install 过程中被拷贝到 {PREFIX}/bin/php
php -f “index.php” php -r “print_r(get_defined_constants());”
说明:
1)如果,你熟悉PHP源码,那么请从源码入手,回答些问题,会获得额外加分
2)如果,你不熟悉PHP源码,那么尽你所能,多写点东西,包括利用自己的编程直觉得到的信息,都可以。
3)对,则有分,错误不扣,不写无分。
答:PHP可以自动进行内存管理,清除不再需要的对象。PHP使用了引用计数(referencecounting)这种单纯的垃圾回收(garbagecollection)机制。每个对象都内含一个引用计数器,每个reference连接到对象,计数器加1。当reference离开生存空间或被设为NULL,计数器减1。当某个对象的引用计数器为零时,PHP知道你将不再需要使用这个对象,释放其所占的内存空间。
1. get是从服务器上获取数据,post是向服务器传送数据。 2. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。 3. get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。 4. get安全性非常低,post安全性较高。但是执行效率却比Post方法好。
一:在php.ini中设置session.gc_maxlifetime = 1440 //默认时间 二:代码实现 $ lifeTime = 24 * 3600; //保存一天 session_set_cookie_params($ lifeTime); 在session_start();
他问的是已经支付成功后,但是回调失败了。
自己可以创建定时任务在每天的凌晨执行,去微信那边对账,然后更新数据库订单状态。
来自PHP技术交流群 群友分享
看看你的服务的访问日志,在防火墙中加过滤,或者在web服务器中加过滤吧。方法有以下几种。
是消耗服务器资源为主还是纯流量攻击?消耗资源的可以通过配置防火墙过滤规则防御中小规模的攻击。如果是纯流量攻击,考虑你用的是linode真心无解。即便你封了IP封了端口也没用,人家不管你接不接受他的请求,他都会塞满你的带宽。linode必然认为你是被流量攻击或者消耗过多资源然后给你挂起。
Groupadd mysql 添加一个用户组mysql Useradd -g mysql mysql 添加一个mysql用户指定分组为mysql Cd /lamp/mysql 进入mysql目录 ./configure –prefix=/usr/local/mysql/ –with-extra-charsets=all Make Make all
优化程序,优化数据库,如果程序和数据库已经最优化,使用以下解决方法:
1)索引的目的是什么?
2) 索引对数据库系统的负面影响是什么?
负面影响:创建索引和维护索引需要耗费时间,这个时间随着数据量的增加而增加;索引需要占用物理空间,不光是表需要占用数据空间,每个索引也需要占用物理空间;当对表进行增、删、改的时候索引也要动态维护,这样就降低了数据的维护速度。
3) 为数据表建立索引的原则有哪些?
4) 什么情况下不宜建立索引?
单引号不能解释变量,而双引号可以解释变量。
单引号不能转义字符,在双引号中可以转义字符。
方法一: <?php class Dtime{ function get_days($date1, $date2){ $time1 = strtotime($date1); $time2 = strtotime($date2); return ($time2-$time1)/86400; } } $Dtime = new Dtime; echo $Dtime->get_days(’2021-2-5′, ’2021-3-6′); ?> 方法二: <?php $temp = explode(‘-’, ’2021-2-5′); $time1 = mktime(0, 0, 0, $temp[1], $temp[2], $temp[0]); $temp = explode(‘-’, ’2021-3-6′); $time2 = mktime(0, 0, 0, $temp[1], $temp[2], $temp[0]); echo ($time2-$time1)/86400; 方法三:echo abs(strtotime(“2021-2-5″)-strtotime(“2021-3-1″))/60/60/24 计算时间差
<?php function BubbleSort(&$arr){ $cnt=count($arr); $flag=1; for($i=0;$i<$cnt;$i++){ if($flag==0){ return; } $flag=0; for($j=0;$j<$cnt-$i-1;$j++){ if($arr[$j]>$arr[$j+1]){ $tmp=$arr[$j]; $arr[$j]=$arr[$j+1]; $arr[$j+1]=$tmp; $flag=1; } } } } $test=array(1,3,6,8,2,7); BubbleSort($test); var_dump($test);
推荐学习:《PHP视频教程》
The above is the detailed content of Summarize and organize 39 PHP interview questions (summary sharing). For more information, please follow other related articles on the PHP Chinese website!