The latest PHP interview questions in 2022 (with answers)
Mar 23, 2020 pm 02:31 PM[Related recommendations: php interview questions (summary)]
1. What is object-oriented? What are the main features?
Object-oriented is a design method for programs, which helps improve the reusability of programs and makes the program structure clearer. Main features: encapsulation, inheritance, polymorphism.
2. What is the difference between SESSION and COOKIE? Please explain the reasons and functions of the protocol?
1. HTTP stateless protocol cannot distinguish whether the user is They come from the same website. The same user requesting different pages cannot be regarded as the same user.
2. SESSION is stored on the server side, and COOKIE is stored on the client side. Session is relatively secure. Cookies can be modified by certain means and are not safe. Session relies on cookies for delivery.
After disabling cookies, the session cannot be used normally. Disadvantages of Session: It is saved on the server side, and each read is read from the server, which consumes resources on the server. Session is saved in a file or database on the server side. It is saved in a file by default. The file path is specified by session.save_path in the PHP configuration file. Session files are public.
3. What do the 302, 403, and 500 codes in the HTTP status mean?
Principle of one, two, three, four and five: 1. Message series 2, success series 3. Redirect series 4. Request error series 5. Server-side error series
302: Temporary transfer successful , the requested content has been moved to a new location 403: Access Forbidden 500: Server Internal Error 401 represents unauthorized.
4. The command to create a compressed package and decompress the package under Linux
Tar.gz:
Packaging: tar czf file.tar.gz file.txt
Extract: tar xzf file.tar.gz
Bz2:
Package: bzip2 [-k] File
Extract: bunzip2 [ -k] File
Gzip (only files, not original files)
Package: gzip file1.txt
Decompress: gunzip file1.txt.gz
Zip: -r Pack the directory
: zip file1.zip file1.txt
Decompress: unzip file1.zip
5. Please write The meaning of data type (int char varchar datetime text); what is the difference between varchar and char?
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.
6. What are the basic differences between MyISAM and InnoDB? How is the index structure implemented?
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`)
7. Send a cookie to the client without using cookies.
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
8. isset() and empty( ) Difference
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.
9. How to pass variables between pages (at least two ways)? GET, POST, COOKIE, SESSION, hidden form
1. Write out the matching URL Regular expression.
‘/^(https?|ftps?):\/\/(www)\.([^\.\/]+)\.(com|cn|org)(\/[\w-\.\/\?\%\&\=]*)?/i’
2. Please write down a common sorting algorithm, and use PHP to implement bubble sorting, and sort the array $a = array() from small to large.
Common sorting algorithms: bubble sort, quick sort, simple selection sort, heap sort, direct insertion sort, Hill sort, merge sort.
The basic idea of ??the bubble sorting method is: perform multiple scans from back to front (reverse order) on the keywords of the records to be sorted. When it is found that the order of two adjacent keywords does not match the rules required for sorting, Just exchange these two records. In this way, records with smaller keywords will gradually move from back to front, just like bubbles floating upward in water, so this algorithm is also called bubble sorting method.
// 冒泡排序法 Function mysort($arr){ For($i=0; $i<count($arr); $i++){ For($j=0; $j<count($arr)-1-$i; $j++){ If($arr[$j] > $arr[$j+1]){ $tmp=$arr[$j]; $arr[$j]=$arr[$j+1]; $arr[$j+1]=$tmp; } } } Return $arr; } $arr=array(3,2,1); print_r(mysort($arr));
3. Please explain the difference between passing by value and passing by reference in PHP. When to pass by value and when to pass by reference?
Pass by value: Any changes to the value within the function scope will be ignored outside the function
Pass by reference: Any changes to the value within the function scope will also be reflected outside the function Revise
優(yōu)缺點:按值傳遞時,php必須復制值。特別是對于大型的字符串和對象來說,這將會是一個代價很大的操作。按引用傳遞則不需要復制值,對于性能提高很有好處。
在PHP中error_reporting這個函數有什么作用?
設置 PHP 的報錯級別并返回當前級別。
請用正則表達式(Regular Expression)寫一個函數驗證電子郵件的格式是否正確。
if(isset($_POST['action']) && $_POST['action']==’submitted’){ $email=$_POST['email']; if(!preg_match(“/^[0-9a-zA-Z-]+@[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+){1,3}$/”,$email)){ echo “電子郵件檢測失敗”; }else{ echo “電子郵件檢測成功”; } }
使用PHP描述快速排序算法,對象可以是一個數組?
原理:快速排序使用分治策略來把待排序數據序列分為兩個子序列,具體步驟為:
(1)從數列中挑出一個元素,稱該元素為“基準”。
(2)掃描一遍數列,將所有比“基準”小的元素排在基準前面,所有比“基準”大的元素排在基準后面。
(3)通過遞歸,將各子序列劃分為更小的序列,直到把小于基準值元素的子數列和大于基準值元素的子數列排序。
//快速排序(數組排序) 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; }
使用PHP描述順序查找和二分查找(也叫做折半查找)算法,順序查找必須考慮效率,對象可以是一個有序數組
//二分查找(數組里查找某個元素) 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; } }
寫一個二維數組排序算法函數,能夠具有通用性,可以調用php內置函數(array_multisort())
//二維數組排序, $arr是數據,$keys是排序的健值,$order是排序規(guī)則,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; }
請以空格作為間隔,拆分字符串’Apple Orange Banana Strawberry’,組成數組$fruit,
* 數組中所有元素都用小寫字母,并按照字母先后次序排序
class sort { private $str; public function __construct($str) { $this->str=strtolower($str); } private function explodes() { if(empty($this->str)) return array(); $arr=explode(" ",$this->str); return is_array($arr)?$arr:array($arr); } public function sort() { $explode=$this->explodes(); sort($explode); return $explode; } } $str='Apple Orange Banana Strawberry'; $sortob=new sort($str); var_dump($sortob->sort());
對于用戶輸入一串字符串$string,要求$string中只能包含大于0的數字和英文逗號,請用正則 表達式驗證,對于不符合要求的$string返回出錯信息
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"; }
請寫一段程序,在服務器創(chuàng)建一個文件fruit.dat,將試題3中得到的數組寫入到改文件中,然后寫一段程序從文件中讀取并還原數組@author zhuwenqiong
class sort { private $str; public function __construct($str) { $this->str=strtolower($str); } private function explodes(){ if(empty($this->str)) return array(); $arr=explode(" ",$this->str); return is_array($arr)?$arr:array($arr); } public function sort() { $explode=$this->explodes(); sort($explode); return $explode; } } class file { private $sort=null; private $filepath; public function __construct($arrobj,$path) { $this->sort=$arrobj; $this->filepath=$path; } private function getresource($filename,$mode) { return fopen($this->filepath.$filename,$mode); } private function closeresource($resource) { fclose($resource); } public function savefile($filename) { $arr=$this->sort->sort(); $fopen=$this->getresource($filename,"a+"); if(!$fopen){ echo "文件打開失?。?quot;; exit; } var_dump($arr); foreach($arr as $key=>$value) { fwrite($fopen,$value."\n"); } $this->closeresource($fopen); } public function readfile($filename) { $this->savefile($filename); $fopen=$this->getresource($filename,"r"); if(!$fopen){ echo "文件打開失?。?quot;;exit; } $arr=array(); while(!feof($fopen)) { $get=fgets($fopen); if(!empty($get)) $arr[]=str_replace("\n","",$get); } $this->closeresource($fopen); return $arr; } } $file=new file(new sort('Apple Orange Banana Strawberry'),"E:\\"); $arr=$file->readfile("fruit.dat"); var_dump($arr);
單例模式,創(chuàng)建mysqli數據庫鏈接的單例對象
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); } }
windows平臺, Apache Http Server啟動失敗, 排錯思路是什么?
檢查apache使用的80端口是否被占用,如果被占用,先停止占用80端口的服務,然后啟動apache服務器
PHP session擴展默認將session數據儲存在哪里? D
A) SQLite Database B) MySQL Database C) Shared Memory D) File System E) Session Server
如果你想要自動加載類,下面哪種函數聲明是正確的 C
A) function autoload($class_name) B) function __autoload($class_name, $file) C) function __autoload($class_name) D) function _autoload($class_name) E) function autoload($class_name, $file)
PHP程序使用utf-8編碼, 以下程序輸出結果是什么? B
<?php $str = ’hello你好世界’; echo strlen($str); ?>
A) 9 B) 13(gbk) C) 18 D) 17(utf8)
你所知道的php數組相關的函數?
array()----創(chuàng)建數組 array_combine()----通過合并兩個數組來創(chuàng)建一個新數組 range()----創(chuàng)建并返回一個包含指定范圍的元素的數組 compact()----建立一個數組 array_chunk()----將一個數組分割成多個 array_merge()----把兩個或多個數組合并成一個數組 array_slice()----在數組中根據條件取出一段值 array_diff()----返回兩個數組的差集數組 array_intersect()----計算數組的交集 array_search()----在數組中搜索給定的值 array_splice()----移除數組的一部分且替代它 array_key_exists()----判斷某個數組中是否存在指定的key shuffle()----把數組中的元素按隨機順序重新排列 array_flip()----交換數組中的鍵和值 array_reverse()----將原數組中的元素順序翻轉,創(chuàng)建新的數組并返回 array_unique()----移除數組中重復的值
php讀取文件內容的幾種方法和函數?
打開文件,然后讀取。Fopen() fread()
打開讀取一次完成 file_get_contents()
以下程序,變量str什么值的情況下輸入111?
if( ! $str ) { echo 111; }
在$str值為:0,’0′,false,null,”"
你所知道的PHP的一些技術(smarty等)?
Smarty,jquery,ajax,memcache,div+css,js,mysqli,pdo,svn,thinkphp,brophp,yii
你所熟悉的PHP論壇系統 有哪些?
Discuz
你所熟悉的PHP商城系統 有哪些?
Ecshop
你所熟悉的PHP開發(fā)框架 有哪些?
Brophp,thinkphp
說說你對緩存技術的了解?
1、緩存技術是將動態(tài)內容緩存到文件中,在一定時間內訪問動態(tài)頁面直接調用緩存文件,而不必重新訪問數據庫。
2、使用memcache可以做緩存。
你所知道的設計模式有哪些?
工廠模式、策略模式、單元素模式、觀察者模式、命令鏈模式
說說你對代碼管理的了解? 常使用那些代碼版本控制軟件?
通常一個項目是由一個團隊去開發(fā),每個人將自己寫好的代碼提交到版本服務器,由項目負責人按照版本進行管理,方便版本的控制,提高開發(fā)效率,保證需要時可以回到舊版本。
常用的版本控制器:SVN
說說你對SVN的了解?優(yōu)缺點?
SVN是一種版本控制器,程序員開發(fā)的代碼遞交到版本服務器進行集中管理。
SVN的優(yōu)點:代碼進行集中管理,版本控制容易,操作比較簡單,權限控制方便。
缺點:不能隨意修改服務器項目文件夾。
怎么找到PHP.ini的路徑?
一般都在php的安裝目錄下,或者window系統的windows目錄下。
PHP加速模式/擴展? PHP調試模式/工具?
Zend Optimizer加速擴展
調試工具:xdebug
你常用到的mysql命令?
Show databases Show tables Insert into 表名() values() Update 表名 set 字段=值 where ... Delete from 表名 where ... Select * from 表名 where 條件 order by ... Desc/asc limit ... Group by ... Having ...
進入mysql管理命令行的命令?
Mysql -uroot -p 回車 密碼
show databases; 這個命令的作用?
顯示當前mysql服務器中有哪些數據庫
show create database mysql; 這個命令的作用?
顯示創(chuàng)建數據庫的sql語句
show create table user; 這個命令的作用?
顯示創(chuàng)建表的sql語句
desc user; 這個命令的作用?
查詢user表的結構
explain select * from user; 這個命令的作用?
獲取select相關信息
show processlist; 這個命令的作用?
顯示哪些線程正在運行
SHOW VARIABLES; 這個命令的作用?
顯示系統變量和值
SHOW VARIABLES like ’%conn%’; 這個命令的作用?
顯示系統變量名包含conn的值
LEFT JOIN 寫一個SQL語句?
SELECT A.id,A.class FROM A LEFT JOIN B ON A.cid=B.id
in, not ni, exist, not exist的作用和區(qū)別?
in在什么中 Not in 不在什么中 Exists 存在 Not exists 不存在
怎么找到數據庫的配置文件路徑?
在數據庫安裝目錄下,my.ini
簡述Linux下安裝PHP的過程?
安裝軟件之前先安裝編譯工具gcc、gcc-c++
拷貝源碼包,解包解壓縮
Cd /lamp/php進入php目錄
./configure –prefix=/usr/local/php –with-config-file-path=/usr/local/php/etc指定安裝目錄和配置文件目錄
Make 編譯
Make install安裝
簡述Linux下安裝Mysql的過程?
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
簡述Linux下安裝apache的過程?
Cd /lamp/httpd 進去apache軟件目錄
./configure –prefix=/usr/local/apache2/ –sysconfdir=/etc/httpd/ –with-included-apr
Make
Make all
HTML/CSS/DIV/Javascritp:
1. 設計一個頁面(4個 div 第一個div 寬960px 居中;第2-4個div 3等分960px;)
<style> Body{ Text-align:center; Margin:0; Padding:0; } #box{ Width:960px; Margin:0 auto; } .small{ Width:320px; Float:left; } </style> <div id=’box’> <div class=’small’></div> <div class=’small’></div> <div class=’small’></div> </div>
用javascript取得一個input的值?取得一個input的屬性?
document.getElementById(‘name’).value; document.getElementById(‘name’).type;
用Jquery取得一個input的值?取得一個input的屬性?
$(“input[name='aa']“).val(); $(“input[name='aa']“).attr(‘type’);
請您寫一段ajax提交的js代碼,或者寫出ajax提交的過程邏輯。
var xmlhttp; if(window.XMLHttpRquest){ xmlhttp=new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlhttp=new ActiveXObject(‘Microsoft.XMLHTTP’); } xmlhttp.open(‘GET’,’1.php?aa=name’,true); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ var text=xmlhttp.responseText; } } } xmlhttp.send(null);
簡述Cookie的設置及獲取過程
設置COOKIE的值:
Setcookie(名稱,值,保存時間,有效域);
獲取值:$_COOKIE['名稱'];
面向對象中接口和抽象類的區(qū)別及應用場景?
1、有抽象方法的類叫做抽象類,抽象類中不一定只有抽象方法,抽象方法必須使用abstract關鍵字定義。
2、接口中全部是抽象方法,方法不用使用abstract定義。
3、當多個同類的類要設計一個上層,通常設計為抽象類,當多個異構的類要設計一個上層,通常設計為接口。
用面向對象來實現A對象繼承B和C對象
Interface B{ ... } Interface C{ ... } Class A implements B,C{ ... }
寫出Smarty模板引擎中你最常用的關鍵詞
Assign Display Foreach Section Loop Item $smarty Now Const get
l 增加一個字段性別sex,寫出修改語句
Alert table user add sex enum(’0′,’1′);
查詢出年齡介于20歲到30歲之間的用戶
Select * from user where age>20 and age<30
如果是一個Web頻繁訪問的查詢,上題的查詢如何優(yōu)化?
可對where后面的字段 age 建立索引,也可對語句建立存儲過程。
echo(),print(),print_r()的區(qū)別?
Echo,print是PHP語句, print_r是函數,
Print()只能打印出簡單類型變量的值(如int,string),有返回值。
print_r()可以打印出復雜類型變量的值(如數組,對象)
echo 輸出一個或者多個字符串,無返回值
什么是模板技術、能夠使HTML和PHP分離開使用的模板?
模板技術就是使程序的邏輯代碼和界面分開的技術。
能夠使HTML和PHP分開的模板有:Smarty、Template、PHPlib Template、FastTemplate
對于大流量的網站,您采用什么樣的方法來解決訪問量問題?
優(yōu)化程序,優(yōu)化數據庫,如果程序和數據庫已經最優(yōu)化,使用以下解決方法:
1、確定當前服務器設備是否滿足流量需求。
2、使用Memcache緩存技術,把動態(tài)內容緩存到文件中,動態(tài)網頁直接調用這些文件,而不必再訪問數據庫。
3、禁止外部盜鏈,圖片和文件外部盜鏈會給服務器帶來大量的負載壓力,可以通過refer來禁止外部盜鏈,或者使用apache來配置禁止盜鏈。
4、控制大文件的下載,大文件的下載對于非SCSI硬盤來說會占用大量的資源,導致服務器的響應能力下降。
5、使用不同的主機分流主要流量,使服務器均衡負載。
6、使用流量統計軟件統計分析網站流量,可以知道哪些地方耗費了大量的流量,哪些頁面需要再進行優(yōu)化。
mysql_fetch_row() 和mysql_fetch_array之間有什么區(qū)別?
Mysql_fetch_row()是從結果集中取出一行作為枚舉數組,mysql_fetch_array()是從結果集中取出一行作為索引數組或關聯數組或兩種方式都有。
實現中文字串截取無亂碼的方法
Mb_substr();
用PHP寫出顯示客戶端IP與服務器IP的代碼
獲取客戶端IP:$_SERVER(“REMOTE_ADDR”);
獲取服務器端IP:$_SERVER["SERVER_ADDR"];
有一個網頁地址, 比如PHP開發(fā)資源網主頁: http://www.phpres.com/index.html,如何得到它的內容?
獲取網頁內容:
$url=”http://www.phpres.com/index.html“; $str=file_get_contents($url); 或 $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,’’); curl_setopt($ch,CURLOPT_HEADER,0); curl_exec($ch); curl_close($ch);
請寫一個函數驗證電子郵件的格式是否正確
function checkemail($email){ echo preg_match(‘/^[0-9a-zA-Z-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z]+$/’,$email)?’email格式正確‘:’email格式不正確‘; }
簡述如何得到當前執(zhí)行腳本路徑,包括所得到參數
用$_SERVER['SCRIPT_FILENAME'].$_SERVER['REQUEST_URI'];取得當前頁面的完整路徑和參數。
取得參數:$_SERVER['QUERY_STRING'];
JS表單彈出對話框函數是?獲得輸入焦點函數是?
Alert(); focus();
寫一個函數,算出兩個文件的相對路徑
如 $a = ’/a/b/c/d/e.php’;
$b = ’/a/b/12/34/c.php’;
計算出 $b 相對于 $a 的相對路徑應該是 http://www.cnblogs.com/c/d將()添上
$a=”http://www.cnblogs.com/a/b/c/d/e.php”; $b=”http://www.cnblogs.com/a/b/12/34/c.php”; $ainfo=parse_url($a); $binfo=parse_url($b); $apath=ltrim($ainfo['path'],'/'); $bpath=ltrim($binfo['path'],'/'); $arr=explode('/',$apath); $brr=explode('/',$bpath); $flag=false; for($i=0;$i<count($arr);$i++){ if($arr[$i]!==$brr[$i]){ $ab[$i]='..'; if(!$flag){ for($j=$i;$j<count($brr);$j++){ $bb[]=$brr[$j]; } $flag=true; } } } $cha=array_merge($ab,$bb); $cha=implode('/',$cha); print_r($cha);
寫一個函數,能夠遍歷一個文件夾下的所有文件和子文件夾。
function my_scandir($dir){ $files = array(); if ( $handle = opendir($dir) ){ while ( ($file = readdir($handle)) !== false ) { if ( $file != ".." && $file != "." ) { if ( is_dir($dir . "/" . $file) ) { $files[$file] = scandir($dir . "/" . $file); }else { $files[] = $file; } } } closedir($handle); return $files; } }
數據庫索引有幾類,分別是什么?什么時候該用索引?
普通索引、主鍵索引、唯一索引
并非所有的數據庫都以相同的方式使用索引,作為通用規(guī)則,只有當經常查詢列中的數據時才需要在表上創(chuàng)建索引。
寫幾個魔術方法并說明作用?
__call()當調用不存在的方法時會自動調用的方法 __autoload()在實例化一個尚未被定義的類是會自動調用次方法來加載類文件 __set()當給未定義的變量賦值時會自動調用的方法 __get()當獲取未定義變量的值時會自動調用的方法 __construct()構造方法,實例化類時自動調用的方法 __destroy()銷毀對象時自動調用的方法 __unset()當對一個未定義變量調用unset()時自動調用的方法 __isset()當對一個未定義變量調用isset()方法時自動調用的方法 __clone()克隆一個對象 __tostring()當輸出一個對象時自動調用的方法
$_REQUEST、$_POST、$_GET、$_COOKIE、$_SESSION、$_FILES的意思是什么?
它們都是PHP預定義變量 $_REQUEST用來獲取post或get方式提交的值 $_POST用來獲取post方式提交的值 $_GET用來獲取get方式提交的值 $_COOKIE用來獲取cookie存儲的值 $_SESSION用來獲取session存儲的值 $_FILES用來獲取上傳文件表單的值
數組中下標最好是什么類型的,為什么?
數組的下標最好是數字類型的,數字類型的處理速度快。
++i和i++哪一個效率高,為什么?
++i效率比i++的效率更高,因為++i少了一個返回i的過程。
magic_quotes_gpc()、magic_quotes_runtime()的意思是什么?
Magic_quotes_gpc()是php配置文件中的,如果設置為on則會自動POST,GET,COOKIE中的字符串進行轉義,在‘之前加\
Magic_quotes_runtime()是php中的函數,如果參數為true則會數據庫中取出來的單引號、雙引號、反斜線自動加上反斜杠進行轉義。
框架中什么是單一入口和多入口,單一入口的優(yōu)缺點?
1、多入口就是通過訪問不同的文件來完成用戶請求。
單一入口指web程序所有的請求都指向一個腳本文件的。
2、單一入口更容易控制權限,方便對http請求可以進行安全性檢查。
缺點:URL看起來不那么美觀,特別是對搜索引擎來說不友好。
你對Memcach的理解,優(yōu)點有哪些?
Memcache是一種緩存技術,在一定的時間內將動態(tài)網頁經過解析之后保存到文件,下次訪問時動態(tài)網頁就直接調用這個文件,而不必在重新訪問數據庫。使用memcache做緩存的好處是:提高網站的訪問速度,減輕高并發(fā)時服務器的壓力。
Memcache的優(yōu)點:穩(wěn)定、配置簡單、多機分布式存儲、速度快。
對關系型數據庫而言,索引是相當重要的概念,請回答有關索引幾個問題:
a) 索引的目的是什么?
1、快速訪問數據表中的特定信息,提高檢索速度
2、創(chuàng)建唯一性索引,保證數據庫表中每一行數據的唯一性
3、加速表和表之間的連接
4、使用分組和排序子句進行數據檢索時,可以顯著減少查詢中分組和排序的時間
b) 索引對數據庫系統的負面影響是什么?
負面影響:創(chuàng)建索引和維護索引需要耗費時間,這個時間隨著數據量的增加而增加;索引需要占用物理空間,不光是表需要占用數據空間,每個索引也需要占用物理空間;當對表進行增、刪、改的時候索引也要動態(tài)維護,這樣就降低了數據的維護速度。
c) 為數據表建立索引的原則有哪些?
1、在最頻繁使用的、用以縮小查詢范圍的字段上建立索引
2、在平頻繁使用的、需要排序的字段上建立索引
d) 什么情況下不宜建立索引?
1、對于查詢中很少涉及的列或者重復值比較多的列,不宜建立索引
2、對于一些特殊的數據類型,不宜建立索引,比如文本字段(text),值范圍較少的知道等。
web應用中,數據庫的讀取頻率遠高于寫入頻率, 如何優(yōu)化MySQL而應對此種情景?
使用memcache緩存技術,將動態(tài)數據緩存到文件,訪問動態(tài)頁面時直接調用緩存文件,而不必重新訪問數據庫,這樣就減少了查詢數據庫的次數。
如果網站的訪問量很大,可以把數據庫讀寫服務器分開,使用多臺服務器去處理數據庫查詢,使用較少的服務器去處理數據庫的寫入和修改。
include與require的區(qū)別?
1.include()在執(zhí)行文件時每次都要進行讀取和評估
require()文件只處理一次(實際上文件內容替換了require()語句)
2.require()通常放在PHP腳本程序的最前面
include()的使用和require()一樣,一般放在流程控制的處理區(qū)段中,PHP腳本文件讀到include()語句時,才將它包含的文件讀進來,這種方式,可以把程序執(zhí)行時的流程簡單化
3,require()和include()語句是語言結構,不是真正的函數,可以像PHP的其他語言結構一樣
4,include_once()和require_once()語句也是在腳本執(zhí)行期間包括并運行指定文件,與include()require()唯一的區(qū)別是如果文件中的代碼已經被包括了,則不會再次包括.
5,require()包含文件失敗,停止執(zhí)行,給出錯誤(致命的)
include()常用于動態(tài)包含.
通常是自動加載的文件,即使加載出錯,整個程序還是繼續(xù)執(zhí)行
一個頁面聲明,另一個頁面調用
包函文件失敗,繼續(xù)向下執(zhí)行,返回一條警告
PHP字符串中單引號與雙引號的區(qū)別?
單引號不能解釋變量,而雙引號可以解釋變量。
單引號不能轉義字符,在雙引號中可以轉義字符。
php中,模板引擎的目的是什么? 你用過哪些模板引擎?
使用模板引擎的目的是使程序的邏輯代碼和html界面代碼分離開,是程序的結構更清晰。
使用過的模板引擎:Smarty、ThinkPHP的ThinkTemplate
指出以下代碼片段中的SQL注入漏洞以及解決方法(magic_quotes_gpc = off)
mysql_query(“select id,title from content where catid=’{$_GET[catid]}’ and title like ’%$_GET[keywords]%’”, $link);
注入漏洞主要存在用戶提交的數據上,這里的注入漏洞主要是$_GET[catid]和$_GET[keyword]
解決注入漏洞:
$_GET[catid]=intval($_GET[catid]); $sql=”select id,title from content where catid=’{$_GET[catid]}’ and title like ’%$_GET[keywords]%”; $sql=addslashes($sql); Mysql_query($sql);
分別指出php.ini中 magic_quotes_gpc, magic_quotes_runtime兩項參數的作用.
Magic_quotes_gpc的作用是在POST、GET、COOKIE數據上使用addslashes()自動轉義。
Magic_quotes_runtime參數的作用是設置狀態(tài),當狀態(tài)為0時則關閉自動轉義,設置為1則自動轉義,將數據庫中取出來的單引號、雙引號、反斜線這些字符加上反斜杠轉義。
寫出以下php代碼的運行結果:
<?php function foo($i) { $i++; echo $i ; } function bar(&$i) { } $i = 10 ; echo $i++ , ++$i; 輸出:10,12 foo($i); 輸出:13 bar($i); 輸出:無輸出
如何快速下載一個遠程http服務器上的圖片文件到本地?
$file=”"; $fp=fopen($file,’rb’); $img=fread($fp,10000); $dir=”./”; $local=fopen($dir.’/’.basename($file),’w'); Fwrite($local,$img);
什么是時間戳? 如何取得當前時間戳?
時間戳是從1970年1月1日 00:00:00到指定日期的秒數。
獲取當前時間戳:time()
了解XSS攻擊嗎? 如何防止 ?
XSS是跨站腳本攻擊,首先是利用跨站腳本漏洞以一個特權模式去執(zhí)行攻擊者構造的腳本,然后利用不安全的Activex控件執(zhí)行惡意的行為。
使用htmlspecialchars()函數對提交的內容進行過濾,使字符串里面的特殊符號實體化。
SQL注入漏洞產生的原因 ? 如何防止?
SQL注入產生的原因:程序開發(fā)過程中不注意規(guī)范書寫sql語句和對特殊字符進行過濾,導致客戶端可以通過全局變量POST和GET提交一些sql語句正常執(zhí)行。
防止SQL注入:
1、開啟配置文件中的magic_quotes_gpc和magic_quotes_runtime設置
2、執(zhí)行sql語句時使用addslashes進行sql語句轉換
3、Sql語句書寫盡量不要省略小引號和單引號
4、過濾掉sql語句中的一些關鍵字:update、insert、delete、select、*
5、提高數據庫表和字段的命名技巧,對一些重要的字段根據程序的特點命名,取不易被猜到的。
6、Php配置文件中設置register_globals為off,關閉全局變量注冊
7、控制錯誤信息,不要再瀏覽器上輸出錯誤信息,將錯誤信息寫到日志文件中。
一個字節(jié)占多少bit ? 一個IPv4地址占幾個字節(jié)? 一個IPv6地址呢?
一個字節(jié)占8bit,一個IPV4占用4字節(jié),一個IPV6占用16字節(jié)。
142.M ADSL寬帶連接, 理想情況下, 最大下載速度是多少KB/s ?
256KB/s
143.請寫出一個正則表達式,用于匹配一個HTML文件中標記中的圖片地址
$url=”<img src=’11.jpg’/>”; /<img[\s]*src=['|\"](.*)['|\"][\s]*\/>/
145.Fatal error: Call to undefined method ge_user() in /website/index.php on line 39
調用了未定義的方法ge_user(),檢查程序中有沒有定義此方法
146.Fatal error: Class ’client’ not found in /website/index.php on line 173
類client沒有找到,檢查文件中有沒有client類,或者有沒有包含client類文件
Warning: Cannot modify header information - headers already sent by (output started at /website/index.php:1) in /website/index.php on line 3
提示文件前面有輸出,檢查是否有輸出,或者編碼
148.Warning:session_start(): open(/website/tmp/sess_47e067121facf033785f9a1cb16d243b, O_RDWR) failed: No such file or directory (2) in /website/index.php on line 10
沒有找到文件或目錄,檢查文件是否存在
149.Parse error: syntax error, unexpected T_STRING in /website/index.php on line 18
18行語法錯誤,檢查語法
150.Warning:fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in /website/index.php on line 2
沒有找到welcome.txt文件,檢查文件是否存在
1、抓取遠程圖片到本地,你會用什么函數?
fsockopen, A
3、用PHP打印出前一天的時間,打印格式是2007年5月10日22:21:21
Echo date(‘Y-m-d H:i:s’,strtotime(‘-1 day’));
4、javascript能否定義二維數組,如果不能你如何解決?
javascript不支持二維數組定義,可以用arr[0] = new array()來解決
5、假設a.html和b.html在同一個文件夾下面,用javascript實現當打開a.html五秒鐘后,自動跳轉到b.html。
<script> function go2b(){ window.location = “b.html”; window.close(); } setTimeout( “go2b()”,5000 ); //5秒鐘后自動執(zhí)行go2b() </script> //正在瀏覽當前頁面用戶的 IP 地址:127.0.0.1 echo $_SERVER["REMOTE_ADDR"].”<br />”; //查詢(query)的字符串(URL 中第一個問號 ? 之后的內容):id=1&bi=2 echo $_SERVER["QUERY_STRING"].”<br />”; //當前運行腳本所在的文檔根目錄:d:inetpubwwwroot echo $_SERVER["DOCUMENT_ROOT"].”<br />”;
7、在HTTP 1.0中,狀態(tài)碼 401 的含義是未授權____;如果返回“找不到文件”的提示,則可用 header 函數,其語句為header(“HTTP/1.0 404 Not Found”);
401表示未授權;header(“HTTP/1.0 404 Not Found”);
9、把 John 新增到 users 陣列?
$users[] = ‘john’; array_push($users,‘john’);
在PHP中error_reporting這個函數有什么作用?
error_reporting() 設置 PHP 的報錯級別并返回當前級別。
13、如何修改SESSION的生存時間(1分).
方法1:將php.ini中的session.gc_maxlifetime設置為9999重啟apache
方法2:$savePath = “./session_save_dir/”;
$lifeTime = 小時 * 秒;
session_save_path($savePath); session_set_cookie_params($lifeTime); session_start();
方法3:
setcookie() and session_set_cookie_params($lifeTime);
14、有一個網頁地址, 比如PHP開發(fā)資源網主頁: http://www.phpres.com/index.html,如何得到它的內容?($1分)
方法1(對于PHP5及更高版本):
$readcontents = fopen(“http://www.phpres.com/index.html”, “rb”); $contents = stream_get_contents($readcontents); fclose($readcontents); echo $contents;
方法2:
echo file_get_contents(“http://www.phpres.com/index.html”);
16、寫一個函數,盡可能高效的,從一個標準 url 里取出文件的擴展名
例如: http://www.sina.com.cn/abc/de/fg.php?id=1 需要取出 php 或 .php
答案1:
function getExt($url){ $arr = parse_url($url); $file = basename($arr['path']); $ext = explode(“.”,$file); return $ext[1]; }
答案2:
function getExt($url) { $url = basename($url); $pos1 = strpos($url,”.”); $pos2 = strpos($url,”?”); if(strstr($url,”?”)){ Return substr($url,$pos1 + 1,$pos2 – $pos1 – 1); } else { return substr($url,$pos1); } }
使用五種以上方式獲取一個文件的擴展名
要求:dir/upload.image.jpg,找出 .jpg 或者 jpg ,
必須使用PHP自帶的處理函數進行處理,方法不能明顯重復,可以封裝成函數 get_ext1($file_name), get_ext2($file_name)
function get_ext1($file_name){ return strrchr($file_name, ‘.’); } function get_ext2($file_name){ return substr($file_name,strrpos($file_name, ‘.’)); } function get_ext3($file_name){ return array_pop(explode(‘.’, $file_name)); } function get_ext4($file_name){ $p = pathinfo($file_name); return $p['extension']; } function get_ext5($file_name){ return strrev(substr(strrev($file_name), 0, strpos(strrev($file_name), ‘.’))); } 18、<?php $str1 = null; $str2 = false; echo $str1==$str2 ? ‘相等’ : ‘不相等’; $str3 = ”; $str4 = 0; echo $str3==$str4 ? ‘相等’ : ‘不相等’; $str5 = 0; $str6 = ’0′; echo $str5===$str6 ? ‘相等’ : ‘不相等’; ?>
相等 相等 不相等
MySQL數據庫中的字段類型varchar和char的主要區(qū)別是什么?那種字段的查找效率要高,為什么?
Varchar是變長,節(jié)省存儲空間,char是固定長度。查找效率要varchar型快,因為varchar是非定長,必須先查找長度,然后進行數據的提取,比char定長類型多了一個步驟,所以效率低一些
請使用JavaScript寫出三種產生一個Image 標簽的方法(提示:從方法、對象、HTML角度考慮)
(1)var img = new Image(); (2)var img = document.createElement(“image”) (3)img.innerHTML = “<img src=”xxx.jpg” />”
請描述出兩點以上XHTML和HTML最顯著的區(qū)別
(1)XHTML必須強制指定文檔類型DocType,HTML不需要
(2)XHTML所有標簽必須閉合,HTML比較隨意
寫出三種以上MySQL數據庫存儲引擎的名稱(提示:不區(qū)分大小寫)
MyISAM、InnoDB、BDB(Berkeley DB)、Merge、Memory(Heap)、Example、Federated、Archive、CSV、Blackhole、MaxDB 等等十幾個引擎
求兩個日期的差數,例如2007-2-5 ~ 2007-3-6 的日期差數
方法一:
<?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(’2007-2-5′, ’2007-3-6′); ?>
方法二:
<?php $temp = explode(‘-’, ’2007-2-5′); $time1 = mktime(0, 0, 0, $temp[1], $temp[2], $temp[0]); $temp = explode(‘-’, ’2007-3-6′); $time2 = mktime(0, 0, 0, $temp[1], $temp[2], $temp[0]); echo ($time2-$time1)/86400;
方法三:echo abs(strtotime(“2007-2-1″)-strtotime(“2007-3-1″))/60/60/24 計算時間差
請寫一個函數,實現以下功能:
字符串“open_door” 轉換成 “OpenDoor”、”make_by_id” 轉換成 ”MakeById”。
方法:
function str_explode($str){ $str_arr=explode(“_”,$str);$str_implode=implode(” “,$str_arr); $str_implode=implode (“”,explode(” “,ucwords($str_implode))); return $str_implode; } $strexplode=str_explode(“make_by_id”);print_r($strexplode);
方法二:
$str=”make_by_id!”; $expStr=explode(“_”,$str); for($i=0;$i<count($expStr);$i++){ echo ucwords($expStr[$i]); }
方法三:echo str_replace(‘ ‘,”,ucwords(str_replace(‘_’,’ ‘,’open_door’)));
一個表中的Id有多個記錄,把所有這個id的記錄查出來,并顯示共有多少條記錄數,用SQL語句及視圖、存儲過程分別實現。
DELIMITER // create procedure proc_countNum(in columnId int,out rowsNo int) begin select count(*) into rowsNo from member where member_id=columnId; end call proc_countNum(1,@no); select @no;
方法:視圖:
create view v_countNum as select member_id,count(*) as countNum from member group by member_id select countNum from v_countNum where member_id=1
js中網頁前進和后退的代碼
前進: history.forward();=history.go(1);
后退: history.back();=history.go(-1);
echo count(“abc”); 輸出什么?
答案:1
count — 計算數組中的單元數目或對象中的屬性個數
int count ( mixed$var [, int $mode ] ), 如果 var 不是數組類型或者實現了 Countable 接口的對象,將返回1,有一個例外,如果 var 是 NULL 則結果是 0。
對于對象,如果安裝了 SPL,可以通過實現 Countable 接口來調用 count()。該接口只有一個方法 count(),此方法返回 count() 函數的返回值。
有一個一維數組,里面存儲整形數據,請寫一個函數,將他們按從大到小的順序排列。要求執(zhí)行效率高。并說明如何改善執(zhí)行效率。(該函數必須自己實現,不能使用php函數)
<?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);
30、請舉例說明在你的開發(fā)過程中用什么方法來加快頁面的加載速度
要用到服務器資源時才打開,及時關閉服務器資源,數據庫添加索引,頁面可生成靜態(tài),圖片等大文件單獨服務器。使用代碼優(yōu)化工具。
31、.以下的代碼會產生什么?為什么?
$num =10; function multiply(){ $num =$num *10; } multiply(); echo $num;
由于函式 multiply() 沒有指定 $num 為全域變量(例如 global $num 或者 $_GLOBALS['num']),所以 $num 的值是 10。
What are the differences between GET, POST and HEAD in HTTP protocol?
HEAD: Only request the header of the page.
GET: Request the specified page information and return the entity body.
POST: Requests the server to accept the specified document as a new subordinate entity to the identified URI.
(1) HTTP defines different methods for interacting with the server, the most basic methods are GET and POST. In fact GET is suitable for most requests, while POST is reserved only for updating the site.
(2) When submitting a FORM, if Method is not specified, the default is a GET request, and the data submitted in the Form will be appended to the url, separated by ?. Alphanumeric characters are sent as is, but spaces are converted to " " signs and other symbols are converted to %XX, where XX is the ASCII (or ISO Latin-1) value of the symbol in hexadecimal. The data submitted by the GET request is placed in the HTTP request protocol header, while the data submitted by POST is placed in the entity data;
The data submitted by GET can only be up to 1024 bytes, while POST does not have this limit.
(3) GET This is the most commonly used method for browsers to request to the server. The POST method is also used to transmit data, but unlike GET, when using POST, the data is not passed after the URI, but is passed as an independent row. At this time, a Content_length must also be sent. A header to indicate the length of the data, followed by a blank line, and then the actual data transferred. Web forms are usually sent using POST.
Recommended PHP video tutorial: http://ipnx.cn/course/list/29/type/2.html
The above is the detailed content of The latest PHP interview questions in 2022 (with answers). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
