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)缺點(diǎn):按值傳遞時(shí),php必須復(fù)制值。特別是對(duì)于大型的字符串和對(duì)象來說,這將會(huì)是一個(gè)代價(jià)很大的操作。按引用傳遞則不需要復(fù)制值,對(duì)于性能提高很有好處。
在PHP中error_reporting這個(gè)函數(shù)有什么作用?
設(shè)置 PHP 的報(bào)錯(cuò)級(jí)別并返回當(dāng)前級(jí)別。
請(qǐng)用正則表達(dá)式(Regular Expression)寫一個(gè)函數(shù)驗(yàn)證電子郵件的格式是否正確。
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 “電子郵件檢測(cè)失敗”; }else{ echo “電子郵件檢測(cè)成功”; } }
使用PHP描述快速排序算法,對(duì)象可以是一個(gè)數(shù)組?
原理:快速排序使用分治策略來把待排序數(shù)據(jù)序列分為兩個(gè)子序列,具體步驟為:
(1)從數(shù)列中挑出一個(gè)元素,稱該元素為“基準(zhǔn)”。
(2)掃描一遍數(shù)列,將所有比“基準(zhǔn)”小的元素排在基準(zhǔn)前面,所有比“基準(zhǔn)”大的元素排在基準(zhǔn)后面。
(3)通過遞歸,將各子序列劃分為更小的序列,直到把小于基準(zhǔn)值元素的子數(shù)列和大于基準(zhǔn)值元素的子數(shù)列排序。
//快速排序(數(shù)組排序) 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描述順序查找和二分查找(也叫做折半查找)算法,順序查找必須考慮效率,對(duì)象可以是一個(gè)有序數(shù)組
//二分查找(數(shù)組里查找某個(gè)元素) 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; } //順序查找(數(shù)組里查找某個(gè)元素) 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; } }
寫一個(gè)二維數(shù)組排序算法函數(shù),能夠具有通用性,可以調(diào)用php內(nèi)置函數(shù)(array_multisort())
//二維數(shù)組排序, $arr是數(shù)據(jù),$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; }
請(qǐng)以空格作為間隔,拆分字符串’Apple Orange Banana Strawberry’,組成數(shù)組$fruit,
* 數(shù)組中所有元素都用小寫字母,并按照字母先后次序排序
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());
對(duì)于用戶輸入一串字符串$string,要求$string中只能包含大于0的數(shù)字和英文逗號(hào),請(qǐng)用正則 表達(dá)式驗(yàn)證,對(duì)于不符合要求的$string返回出錯(cuò)信息
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"; }
請(qǐng)寫一段程序,在服務(wù)器創(chuàng)建一個(gè)文件fruit.dat,將試題3中得到的數(shù)組寫入到改文件中,然后寫一段程序從文件中讀取并還原數(shù)組@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 "文件打開失??!"; 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 "文件打開失??!";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數(shù)據(jù)庫鏈接的單例對(duì)象
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平臺(tái), Apache Http Server啟動(dòng)失敗, 排錯(cuò)思路是什么?
檢查apache使用的80端口是否被占用,如果被占用,先停止占用80端口的服務(wù),然后啟動(dòng)apache服務(wù)器
PHP session擴(kuò)展默認(rèn)將session數(shù)據(jù)儲(chǔ)存在哪里? D
A) SQLite Database B) MySQL Database C) Shared Memory D) File System E) Session Server
如果你想要自動(dòng)加載類,下面哪種函數(shù)聲明是正確的 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編碼, 以下程序輸出結(jié)果是什么? B
<?php $str = ’hello你好世界’; echo strlen($str); ?>
A) 9 B) 13(gbk) C) 18 D) 17(utf8)
你所知道的php數(shù)組相關(guān)的函數(shù)?
array()----創(chuàng)建數(shù)組 array_combine()----通過合并兩個(gè)數(shù)組來創(chuàng)建一個(gè)新數(shù)組 range()----創(chuàng)建并返回一個(gè)包含指定范圍的元素的數(shù)組 compact()----建立一個(gè)數(shù)組 array_chunk()----將一個(gè)數(shù)組分割成多個(gè) array_merge()----把兩個(gè)或多個(gè)數(shù)組合并成一個(gè)數(shù)組 array_slice()----在數(shù)組中根據(jù)條件取出一段值 array_diff()----返回兩個(gè)數(shù)組的差集數(shù)組 array_intersect()----計(jì)算數(shù)組的交集 array_search()----在數(shù)組中搜索給定的值 array_splice()----移除數(shù)組的一部分且替代它 array_key_exists()----判斷某個(gè)數(shù)組中是否存在指定的key shuffle()----把數(shù)組中的元素按隨機(jī)順序重新排列 array_flip()----交換數(shù)組中的鍵和值 array_reverse()----將原數(shù)組中的元素順序翻轉(zhuǎn),創(chuàng)建新的數(shù)組并返回 array_unique()----移除數(shù)組中重復(fù)的值
php讀取文件內(nèi)容的幾種方法和函數(shù)?
打開文件,然后讀取。Fopen() fread()
打開讀取一次完成 file_get_contents()
以下程序,變量str什么值的情況下輸入111?
if( ! $str ) { echo 111; }
在$str值為:0,’0′,false,null,”"
你所知道的PHP的一些技術(shù)(smarty等)?
Smarty,jquery,ajax,memcache,div+css,js,mysqli,pdo,svn,thinkphp,brophp,yii
你所熟悉的PHP論壇系統(tǒng) 有哪些?
Discuz
你所熟悉的PHP商城系統(tǒng) 有哪些?
Ecshop
你所熟悉的PHP開發(fā)框架 有哪些?
Brophp,thinkphp
說說你對(duì)緩存技術(shù)的了解?
1、緩存技術(shù)是將動(dòng)態(tài)內(nèi)容緩存到文件中,在一定時(shí)間內(nèi)訪問動(dòng)態(tài)頁面直接調(diào)用緩存文件,而不必重新訪問數(shù)據(jù)庫。
2、使用memcache可以做緩存。
你所知道的設(shè)計(jì)模式有哪些?
工廠模式、策略模式、單元素模式、觀察者模式、命令鏈模式
說說你對(duì)代碼管理的了解? 常使用那些代碼版本控制軟件?
通常一個(gè)項(xiàng)目是由一個(gè)團(tuán)隊(duì)去開發(fā),每個(gè)人將自己寫好的代碼提交到版本服務(wù)器,由項(xiàng)目負(fù)責(zé)人按照版本進(jìn)行管理,方便版本的控制,提高開發(fā)效率,保證需要時(shí)可以回到舊版本。
常用的版本控制器:SVN
說說你對(duì)SVN的了解??jī)?yōu)缺點(diǎn)?
SVN是一種版本控制器,程序員開發(fā)的代碼遞交到版本服務(wù)器進(jìn)行集中管理。
SVN的優(yōu)點(diǎn):代碼進(jìn)行集中管理,版本控制容易,操作比較簡(jiǎn)單,權(quán)限控制方便。
缺點(diǎn):不能隨意修改服務(wù)器項(xiàng)目文件夾。
怎么找到PHP.ini的路徑?
一般都在php的安裝目錄下,或者window系統(tǒng)的windows目錄下。
PHP加速模式/擴(kuò)展? PHP調(diào)試模式/工具?
Zend Optimizer加速擴(kuò)展
調(diào)試工具: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 ...
進(jìn)入mysql管理命令行的命令?
Mysql -uroot -p 回車 密碼
show databases; 這個(gè)命令的作用?
顯示當(dāng)前mysql服務(wù)器中有哪些數(shù)據(jù)庫
show create database mysql; 這個(gè)命令的作用?
顯示創(chuàng)建數(shù)據(jù)庫的sql語句
show create table user; 這個(gè)命令的作用?
顯示創(chuàng)建表的sql語句
desc user; 這個(gè)命令的作用?
查詢user表的結(jié)構(gòu)
explain select * from user; 這個(gè)命令的作用?
獲取select相關(guān)信息
show processlist; 這個(gè)命令的作用?
顯示哪些線程正在運(yùn)行
SHOW VARIABLES; 這個(gè)命令的作用?
顯示系統(tǒng)變量和值
SHOW VARIABLES like ’%conn%’; 這個(gè)命令的作用?
顯示系統(tǒng)變量名包含conn的值
LEFT JOIN 寫一個(gè)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 不存在
怎么找到數(shù)據(jù)庫的配置文件路徑?
在數(shù)據(jù)庫安裝目錄下,my.ini
簡(jiǎn)述Linux下安裝PHP的過程?
安裝軟件之前先安裝編譯工具gcc、gcc-c++
拷貝源碼包,解包解壓縮
Cd /lamp/php進(jìn)入php目錄
./configure –prefix=/usr/local/php –with-config-file-path=/usr/local/php/etc指定安裝目錄和配置文件目錄
Make 編譯
Make install安裝
簡(jiǎn)述Linux下安裝Mysql的過程?
Groupadd mysql 添加一個(gè)用戶組mysql
Useradd -g mysql mysql 添加一個(gè)mysql用戶指定分組為mysql
Cd /lamp/mysql 進(jìn)入mysql目錄
./configure –prefix=/usr/local/mysql/ –with-extra-charsets=all
Make
Make all
簡(jiǎn)述Linux下安裝apache的過程?
Cd /lamp/httpd 進(jìn)去apache軟件目錄
./configure –prefix=/usr/local/apache2/ –sysconfdir=/etc/httpd/ –with-included-apr
Make
Make all
HTML/CSS/DIV/Javascritp:
1. 設(shè)計(jì)一個(gè)頁面(4個(gè) div 第一個(gè)div 寬960px 居中;第2-4個(gè)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取得一個(gè)input的值?取得一個(gè)input的屬性?
document.getElementById(‘name’).value; document.getElementById(‘name’).type;
用Jquery取得一個(gè)input的值?取得一個(gè)input的屬性?
$(“input[name='aa']“).val(); $(“input[name='aa']“).attr(‘type’);
請(qǐng)您寫一段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);
簡(jiǎn)述Cookie的設(shè)置及獲取過程
設(shè)置COOKIE的值:
Setcookie(名稱,值,保存時(shí)間,有效域);
獲取值:$_COOKIE['名稱'];
面向?qū)ο笾薪涌诤统橄箢惖膮^(qū)別及應(yīng)用場(chǎng)景?
1、有抽象方法的類叫做抽象類,抽象類中不一定只有抽象方法,抽象方法必須使用abstract關(guān)鍵字定義。
2、接口中全部是抽象方法,方法不用使用abstract定義。
3、當(dāng)多個(gè)同類的類要設(shè)計(jì)一個(gè)上層,通常設(shè)計(jì)為抽象類,當(dāng)多個(gè)異構(gòu)的類要設(shè)計(jì)一個(gè)上層,通常設(shè)計(jì)為接口。
用面向?qū)ο髞韺?shí)現(xiàn)A對(duì)象繼承B和C對(duì)象
Interface B{ ... } Interface C{ ... } Class A implements B,C{ ... }
寫出Smarty模板引擎中你最常用的關(guān)鍵詞
Assign Display Foreach Section Loop Item $smarty Now Const get
l 增加一個(gè)字段性別sex,寫出修改語句
Alert table user add sex enum(’0′,’1′);
查詢出年齡介于20歲到30歲之間的用戶
Select * from user where age>20 and age<30
如果是一個(gè)Web頻繁訪問的查詢,上題的查詢?nèi)绾蝺?yōu)化?
可對(duì)where后面的字段 age 建立索引,也可對(duì)語句建立存儲(chǔ)過程。
echo(),print(),print_r()的區(qū)別?
Echo,print是PHP語句, print_r是函數(shù),
Print()只能打印出簡(jiǎn)單類型變量的值(如int,string),有返回值。
print_r()可以打印出復(fù)雜類型變量的值(如數(shù)組,對(duì)象)
echo 輸出一個(gè)或者多個(gè)字符串,無返回值
什么是模板技術(shù)、能夠使HTML和PHP分離開使用的模板?
模板技術(shù)就是使程序的邏輯代碼和界面分開的技術(shù)。
能夠使HTML和PHP分開的模板有:Smarty、Template、PHPlib Template、FastTemplate
對(duì)于大流量的網(wǎng)站,您采用什么樣的方法來解決訪問量問題?
優(yōu)化程序,優(yōu)化數(shù)據(jù)庫,如果程序和數(shù)據(jù)庫已經(jīng)最優(yōu)化,使用以下解決方法:
1、確定當(dāng)前服務(wù)器設(shè)備是否滿足流量需求。
2、使用Memcache緩存技術(shù),把動(dòng)態(tài)內(nèi)容緩存到文件中,動(dòng)態(tài)網(wǎng)頁直接調(diào)用這些文件,而不必再訪問數(shù)據(jù)庫。
3、禁止外部盜鏈,圖片和文件外部盜鏈會(huì)給服務(wù)器帶來大量的負(fù)載壓力,可以通過refer來禁止外部盜鏈,或者使用apache來配置禁止盜鏈。
4、控制大文件的下載,大文件的下載對(duì)于非SCSI硬盤來說會(huì)占用大量的資源,導(dǎo)致服務(wù)器的響應(yīng)能力下降。
5、使用不同的主機(jī)分流主要流量,使服務(wù)器均衡負(fù)載。
6、使用流量統(tǒng)計(jì)軟件統(tǒng)計(jì)分析網(wǎng)站流量,可以知道哪些地方耗費(fèi)了大量的流量,哪些頁面需要再進(jìn)行優(yōu)化。
mysql_fetch_row() 和mysql_fetch_array之間有什么區(qū)別?
Mysql_fetch_row()是從結(jié)果集中取出一行作為枚舉數(shù)組,mysql_fetch_array()是從結(jié)果集中取出一行作為索引數(shù)組或關(guān)聯(lián)數(shù)組或兩種方式都有。
實(shí)現(xiàn)中文字串截取無亂碼的方法
Mb_substr();
用PHP寫出顯示客戶端IP與服務(wù)器IP的代碼
獲取客戶端IP:$_SERVER(“REMOTE_ADDR”);
獲取服務(wù)器端IP:$_SERVER["SERVER_ADDR"];
有一個(gè)網(wǎng)頁地址, 比如PHP開發(fā)資源網(wǎng)主頁: http://www.phpres.com/index.html,如何得到它的內(nèi)容?
獲取網(wǎng)頁內(nèi)容:
$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);
請(qǐng)寫一個(gè)函數(shù)驗(yàn)證電子郵件的格式是否正確
function checkemail($email){ echo preg_match(‘/^[0-9a-zA-Z-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z]+$/’,$email)?’email格式正確‘:’email格式不正確‘; }
簡(jiǎn)述如何得到當(dāng)前執(zhí)行腳本路徑,包括所得到參數(shù)
用$_SERVER['SCRIPT_FILENAME'].$_SERVER['REQUEST_URI'];取得當(dāng)前頁面的完整路徑和參數(shù)。
取得參數(shù):$_SERVER['QUERY_STRING'];
JS表單彈出對(duì)話框函數(shù)是?獲得輸入焦點(diǎn)函數(shù)是?
Alert(); focus();
寫一個(gè)函數(shù),算出兩個(gè)文件的相對(duì)路徑
如 $a = ’/a/b/c/d/e.php’;
$b = ’/a/b/12/34/c.php’;
計(jì)算出 $b 相對(duì)于 $a 的相對(duì)路徑應(yīng)該是 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);
寫一個(gè)函數(shù),能夠遍歷一個(gè)文件夾下的所有文件和子文件夾。
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; } }
數(shù)據(jù)庫索引有幾類,分別是什么?什么時(shí)候該用索引?
普通索引、主鍵索引、唯一索引
并非所有的數(shù)據(jù)庫都以相同的方式使用索引,作為通用規(guī)則,只有當(dāng)經(jīng)常查詢列中的數(shù)據(jù)時(shí)才需要在表上創(chuàng)建索引。
寫幾個(gè)魔術(shù)方法并說明作用?
__call()當(dāng)調(diào)用不存在的方法時(shí)會(huì)自動(dòng)調(diào)用的方法 __autoload()在實(shí)例化一個(gè)尚未被定義的類是會(huì)自動(dòng)調(diào)用次方法來加載類文件 __set()當(dāng)給未定義的變量賦值時(shí)會(huì)自動(dòng)調(diào)用的方法 __get()當(dāng)獲取未定義變量的值時(shí)會(huì)自動(dòng)調(diào)用的方法 __construct()構(gòu)造方法,實(shí)例化類時(shí)自動(dòng)調(diào)用的方法 __destroy()銷毀對(duì)象時(shí)自動(dòng)調(diào)用的方法 __unset()當(dāng)對(duì)一個(gè)未定義變量調(diào)用unset()時(shí)自動(dòng)調(diào)用的方法 __isset()當(dāng)對(duì)一個(gè)未定義變量調(diào)用isset()方法時(shí)自動(dòng)調(diào)用的方法 __clone()克隆一個(gè)對(duì)象 __tostring()當(dāng)輸出一個(gè)對(duì)象時(shí)自動(dòng)調(diào)用的方法
$_REQUEST、$_POST、$_GET、$_COOKIE、$_SESSION、$_FILES的意思是什么?
它們都是PHP預(yù)定義變量 $_REQUEST用來獲取post或get方式提交的值 $_POST用來獲取post方式提交的值 $_GET用來獲取get方式提交的值 $_COOKIE用來獲取cookie存儲(chǔ)的值 $_SESSION用來獲取session存儲(chǔ)的值 $_FILES用來獲取上傳文件表單的值
數(shù)組中下標(biāo)最好是什么類型的,為什么?
數(shù)組的下標(biāo)最好是數(shù)字類型的,數(shù)字類型的處理速度快。
++i和i++哪一個(gè)效率高,為什么?
++i效率比i++的效率更高,因?yàn)?+i少了一個(gè)返回i的過程。
magic_quotes_gpc()、magic_quotes_runtime()的意思是什么?
Magic_quotes_gpc()是php配置文件中的,如果設(shè)置為on則會(huì)自動(dòng)POST,GET,COOKIE中的字符串進(jìn)行轉(zhuǎn)義,在‘之前加\
Magic_quotes_runtime()是php中的函數(shù),如果參數(shù)為true則會(huì)數(shù)據(jù)庫中取出來的單引號(hào)、雙引號(hào)、反斜線自動(dòng)加上反斜杠進(jìn)行轉(zhuǎn)義。
框架中什么是單一入口和多入口,單一入口的優(yōu)缺點(diǎn)?
1、多入口就是通過訪問不同的文件來完成用戶請(qǐng)求。
單一入口指web程序所有的請(qǐng)求都指向一個(gè)腳本文件的。
2、單一入口更容易控制權(quán)限,方便對(duì)http請(qǐng)求可以進(jìn)行安全性檢查。
缺點(diǎn):URL看起來不那么美觀,特別是對(duì)搜索引擎來說不友好。
你對(duì)Memcach的理解,優(yōu)點(diǎn)有哪些?
Memcache是一種緩存技術(shù),在一定的時(shí)間內(nèi)將動(dòng)態(tài)網(wǎng)頁經(jīng)過解析之后保存到文件,下次訪問時(shí)動(dòng)態(tài)網(wǎng)頁就直接調(diào)用這個(gè)文件,而不必在重新訪問數(shù)據(jù)庫。使用memcache做緩存的好處是:提高網(wǎng)站的訪問速度,減輕高并發(fā)時(shí)服務(wù)器的壓力。
Memcache的優(yōu)點(diǎn):穩(wěn)定、配置簡(jiǎn)單、多機(jī)分布式存儲(chǔ)、速度快。
對(duì)關(guān)系型數(shù)據(jù)庫而言,索引是相當(dāng)重要的概念,請(qǐng)回答有關(guān)索引幾個(gè)問題:
a) 索引的目的是什么?
1、快速訪問數(shù)據(jù)表中的特定信息,提高檢索速度
2、創(chuàng)建唯一性索引,保證數(shù)據(jù)庫表中每一行數(shù)據(jù)的唯一性
3、加速表和表之間的連接
4、使用分組和排序子句進(jìn)行數(shù)據(jù)檢索時(shí),可以顯著減少查詢中分組和排序的時(shí)間
b) 索引對(duì)數(shù)據(jù)庫系統(tǒng)的負(fù)面影響是什么?
負(fù)面影響:創(chuàng)建索引和維護(hù)索引需要耗費(fèi)時(shí)間,這個(gè)時(shí)間隨著數(shù)據(jù)量的增加而增加;索引需要占用物理空間,不光是表需要占用數(shù)據(jù)空間,每個(gè)索引也需要占用物理空間;當(dāng)對(duì)表進(jìn)行增、刪、改的時(shí)候索引也要?jiǎng)討B(tài)維護(hù),這樣就降低了數(shù)據(jù)的維護(hù)速度。
c) 為數(shù)據(jù)表建立索引的原則有哪些?
1、在最頻繁使用的、用以縮小查詢范圍的字段上建立索引
2、在平頻繁使用的、需要排序的字段上建立索引
d) 什么情況下不宜建立索引?
1、對(duì)于查詢中很少涉及的列或者重復(fù)值比較多的列,不宜建立索引
2、對(duì)于一些特殊的數(shù)據(jù)類型,不宜建立索引,比如文本字段(text),值范圍較少的知道等。
web應(yīng)用中,數(shù)據(jù)庫的讀取頻率遠(yuǎn)高于寫入頻率, 如何優(yōu)化MySQL而應(yīng)對(duì)此種情景?
使用memcache緩存技術(shù),將動(dòng)態(tài)數(shù)據(jù)緩存到文件,訪問動(dòng)態(tài)頁面時(shí)直接調(diào)用緩存文件,而不必重新訪問數(shù)據(jù)庫,這樣就減少了查詢數(shù)據(jù)庫的次數(shù)。
如果網(wǎng)站的訪問量很大,可以把數(shù)據(jù)庫讀寫服務(wù)器分開,使用多臺(tái)服務(wù)器去處理數(shù)據(jù)庫查詢,使用較少的服務(wù)器去處理數(shù)據(jù)庫的寫入和修改。
include與require的區(qū)別?
1.include()在執(zhí)行文件時(shí)每次都要進(jìn)行讀取和評(píng)估
require()文件只處理一次(實(shí)際上文件內(nèi)容替換了require()語句)
2.require()通常放在PHP腳本程序的最前面
include()的使用和require()一樣,一般放在流程控制的處理區(qū)段中,PHP腳本文件讀到include()語句時(shí),才將它包含的文件讀進(jìn)來,這種方式,可以把程序執(zhí)行時(shí)的流程簡(jiǎn)單化
3,require()和include()語句是語言結(jié)構(gòu),不是真正的函數(shù),可以像PHP的其他語言結(jié)構(gòu)一樣
4,include_once()和require_once()語句也是在腳本執(zhí)行期間包括并運(yùn)行指定文件,與include()require()唯一的區(qū)別是如果文件中的代碼已經(jīng)被包括了,則不會(huì)再次包括.
5,require()包含文件失敗,停止執(zhí)行,給出錯(cuò)誤(致命的)
include()常用于動(dòng)態(tài)包含.
通常是自動(dòng)加載的文件,即使加載出錯(cuò),整個(gè)程序還是繼續(xù)執(zhí)行
一個(gè)頁面聲明,另一個(gè)頁面調(diào)用
包函文件失敗,繼續(xù)向下執(zhí)行,返回一條警告
PHP字符串中單引號(hào)與雙引號(hào)的區(qū)別?
單引號(hào)不能解釋變量,而雙引號(hào)可以解釋變量。
單引號(hào)不能轉(zhuǎn)義字符,在雙引號(hào)中可以轉(zhuǎn)義字符。
php中,模板引擎的目的是什么? 你用過哪些模板引擎?
使用模板引擎的目的是使程序的邏輯代碼和html界面代碼分離開,是程序的結(jié)構(gòu)更清晰。
使用過的模板引擎: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);
注入漏洞主要存在用戶提交的數(shù)據(jù)上,這里的注入漏洞主要是$_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兩項(xiàng)參數(shù)的作用.
Magic_quotes_gpc的作用是在POST、GET、COOKIE數(shù)據(jù)上使用addslashes()自動(dòng)轉(zhuǎn)義。
Magic_quotes_runtime參數(shù)的作用是設(shè)置狀態(tài),當(dāng)狀態(tài)為0時(shí)則關(guān)閉自動(dòng)轉(zhuǎn)義,設(shè)置為1則自動(dòng)轉(zhuǎn)義,將數(shù)據(jù)庫中取出來的單引號(hào)、雙引號(hào)、反斜線這些字符加上反斜杠轉(zhuǎn)義。
寫出以下php代碼的運(yùn)行結(jié)果:
<?php function foo($i) { $i++; echo $i ; } function bar(&$i) { } $i = 10 ; echo $i++ , ++$i; 輸出:10,12 foo($i); 輸出:13 bar($i); 輸出:無輸出
如何快速下載一個(gè)遠(yuǎn)程http服務(wù)器上的圖片文件到本地?
$file=”"; $fp=fopen($file,’rb’); $img=fread($fp,10000); $dir=”./”; $local=fopen($dir.’/’.basename($file),’w'); Fwrite($local,$img);
什么是時(shí)間戳? 如何取得當(dāng)前時(shí)間戳?
時(shí)間戳是從1970年1月1日 00:00:00到指定日期的秒數(shù)。
獲取當(dāng)前時(shí)間戳:time()
了解XSS攻擊嗎? 如何防止 ?
XSS是跨站腳本攻擊,首先是利用跨站腳本漏洞以一個(gè)特權(quán)模式去執(zhí)行攻擊者構(gòu)造的腳本,然后利用不安全的Activex控件執(zhí)行惡意的行為。
使用htmlspecialchars()函數(shù)對(duì)提交的內(nèi)容進(jìn)行過濾,使字符串里面的特殊符號(hào)實(shí)體化。
SQL注入漏洞產(chǎn)生的原因 ? 如何防止?
SQL注入產(chǎn)生的原因:程序開發(fā)過程中不注意規(guī)范書寫sql語句和對(duì)特殊字符進(jìn)行過濾,導(dǎo)致客戶端可以通過全局變量POST和GET提交一些sql語句正常執(zhí)行。
防止SQL注入:
1、開啟配置文件中的magic_quotes_gpc和magic_quotes_runtime設(shè)置
2、執(zhí)行sql語句時(shí)使用addslashes進(jìn)行sql語句轉(zhuǎn)換
3、Sql語句書寫盡量不要省略小引號(hào)和單引號(hào)
4、過濾掉sql語句中的一些關(guān)鍵字:update、insert、delete、select、*
5、提高數(shù)據(jù)庫表和字段的命名技巧,對(duì)一些重要的字段根據(jù)程序的特點(diǎn)命名,取不易被猜到的。
6、Php配置文件中設(shè)置register_globals為off,關(guān)閉全局變量注冊(cè)
7、控制錯(cuò)誤信息,不要再瀏覽器上輸出錯(cuò)誤信息,將錯(cuò)誤信息寫到日志文件中。
一個(gè)字節(jié)占多少bit ? 一個(gè)IPv4地址占幾個(gè)字節(jié)? 一個(gè)IPv6地址呢?
一個(gè)字節(jié)占8bit,一個(gè)IPV4占用4字節(jié),一個(gè)IPV6占用16字節(jié)。
142.M ADSL寬帶連接, 理想情況下, 最大下載速度是多少KB/s ?
256KB/s
143.請(qǐng)寫出一個(gè)正則表達(dá)式,用于匹配一個(gè)HTML文件中標(biāo)記中的圖片地址
$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
調(diào)用了未定義的方法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行語法錯(cuò)誤,檢查語法
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、抓取遠(yuǎn)程圖片到本地,你會(huì)用什么函數(shù)?
fsockopen, A
3、用PHP打印出前一天的時(shí)間,打印格式是2007年5月10日22:21:21
Echo date(‘Y-m-d H:i:s’,strtotime(‘-1 day’));
4、javascript能否定義二維數(shù)組,如果不能你如何解決?
javascript不支持二維數(shù)組定義,可以用arr[0] = new array()來解決
5、假設(shè)a.html和b.html在同一個(gè)文件夾下面,用javascript實(shí)現(xiàn)當(dāng)打開a.html五秒鐘后,自動(dòng)跳轉(zhuǎn)到b.html。
<script> function go2b(){ window.location = “b.html”; window.close(); } setTimeout( “go2b()”,5000 ); //5秒鐘后自動(dòng)執(zhí)行g(shù)o2b() </script> //正在瀏覽當(dāng)前頁面用戶的 IP 地址:127.0.0.1 echo $_SERVER["REMOTE_ADDR"].”<br />”; //查詢(query)的字符串(URL 中第一個(gè)問號(hào) ? 之后的內(nèi)容):id=1&bi=2 echo $_SERVER["QUERY_STRING"].”<br />”; //當(dāng)前運(yùn)行腳本所在的文檔根目錄:d:inetpubwwwroot echo $_SERVER["DOCUMENT_ROOT"].”<br />”;
7、在HTTP 1.0中,狀態(tài)碼 401 的含義是未授權(quán)____;如果返回“找不到文件”的提示,則可用 header 函數(shù),其語句為header(“HTTP/1.0 404 Not Found”);
401表示未授權(quán);header(“HTTP/1.0 404 Not Found”);
9、把 John 新增到 users 陣列?
$users[] = ‘john’; array_push($users,‘john’);
在PHP中error_reporting這個(gè)函數(shù)有什么作用?
error_reporting() 設(shè)置 PHP 的報(bào)錯(cuò)級(jí)別并返回當(dāng)前級(jí)別。
13、如何修改SESSION的生存時(shí)間(1分).
方法1:將php.ini中的session.gc_maxlifetime設(shè)置為9999重啟apache
方法2:$savePath = “./session_save_dir/”;
$lifeTime = 小時(shí) * 秒;
session_save_path($savePath); session_set_cookie_params($lifeTime); session_start();
方法3:
setcookie() and session_set_cookie_params($lifeTime);
14、有一個(gè)網(wǎng)頁地址, 比如PHP開發(fā)資源網(wǎng)主頁: http://www.phpres.com/index.html,如何得到它的內(nèi)容?($1分)
方法1(對(duì)于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、寫一個(gè)函數(shù),盡可能高效的,從一個(gè)標(biāo)準(zhǔn) url 里取出文件的擴(kuò)展名
例如: 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); } }
使用五種以上方式獲取一個(gè)文件的擴(kuò)展名
要求:dir/upload.image.jpg,找出 .jpg 或者 jpg ,
必須使用PHP自帶的處理函數(shù)進(jìn)行處理,方法不能明顯重復(fù),可以封裝成函數(shù) 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數(shù)據(jù)庫中的字段類型varchar和char的主要區(qū)別是什么?那種字段的查找效率要高,為什么?
Varchar是變長(zhǎng),節(jié)省存儲(chǔ)空間,char是固定長(zhǎng)度。查找效率要varchar型快,因?yàn)関archar是非定長(zhǎng),必須先查找長(zhǎng)度,然后進(jìn)行數(shù)據(jù)的提取,比char定長(zhǎng)類型多了一個(gè)步驟,所以效率低一些
請(qǐng)使用JavaScript寫出三種產(chǎn)生一個(gè)Image 標(biāo)簽的方法(提示:從方法、對(duì)象、HTML角度考慮)
(1)var img = new Image(); (2)var img = document.createElement(“image”) (3)img.innerHTML = “<img src=”xxx.jpg” />”
請(qǐng)描述出兩點(diǎn)以上XHTML和HTML最顯著的區(qū)別
(1)XHTML必須強(qiáng)制指定文檔類型DocType,HTML不需要
(2)XHTML所有標(biāo)簽必須閉合,HTML比較隨意
寫出三種以上MySQL數(shù)據(jù)庫存儲(chǔ)引擎的名稱(提示:不區(qū)分大小寫)
MyISAM、InnoDB、BDB(Berkeley DB)、Merge、Memory(Heap)、Example、Federated、Archive、CSV、Blackhole、MaxDB 等等十幾個(gè)引擎
求兩個(gè)日期的差數(shù),例如2007-2-5 ~ 2007-3-6 的日期差數(shù)
方法一:
<?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 計(jì)算時(shí)間差
請(qǐng)寫一個(gè)函數(shù),實(shí)現(xiàn)以下功能:
字符串“open_door” 轉(zhuǎn)換成 “OpenDoor”、”make_by_id” 轉(zhuǎn)換成 ”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’)));
一個(gè)表中的Id有多個(gè)記錄,把所有這個(gè)id的記錄查出來,并顯示共有多少條記錄數(shù),用SQL語句及視圖、存儲(chǔ)過程分別實(shí)現(xiàn)。
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中網(wǎng)頁前進(jìn)和后退的代碼
前進(jìn): history.forward();=history.go(1);
后退: history.back();=history.go(-1);
echo count(“abc”); 輸出什么?
答案:1
count — 計(jì)算數(shù)組中的單元數(shù)目或?qū)ο笾械膶傩詡€(gè)數(shù)
int count ( mixed$var [, int $mode ] ), 如果 var 不是數(shù)組類型或者實(shí)現(xiàn)了 Countable 接口的對(duì)象,將返回1,有一個(gè)例外,如果 var 是 NULL 則結(jié)果是 0。
對(duì)于對(duì)象,如果安裝了 SPL,可以通過實(shí)現(xiàn) Countable 接口來調(diào)用 count()。該接口只有一個(gè)方法 count(),此方法返回 count() 函數(shù)的返回值。
有一個(gè)一維數(shù)組,里面存儲(chǔ)整形數(shù)據(jù),請(qǐng)寫一個(gè)函數(shù),將他們按從大到小的順序排列。要求執(zhí)行效率高。并說明如何改善執(zhí)行效率。(該函數(shù)必須自己實(shí)現(xiàn),不能使用php函數(shù))
<?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、請(qǐng)舉例說明在你的開發(fā)過程中用什么方法來加快頁面的加載速度
要用到服務(wù)器資源時(shí)才打開,及時(shí)關(guān)閉服務(wù)器資源,數(shù)據(jù)庫添加索引,頁面可生成靜態(tài),圖片等大文件單獨(dú)服務(wù)器。使用代碼優(yōu)化工具。
31、.以下的代碼會(huì)產(chǎn)生什么?為什么?
$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://m.miracleart.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)

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.

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.

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

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

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

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.
