PHP面试题(二)

Jun 23, 2016 pm 02:32 PM

 

 

1. 请对POSIX风格和兼容Perl风格两种正则表达式的主要函数进行类比说明
ereg preg_match
ereg_replace preg_replace

 


2. 请说明在php.ini中safe_mode开启之后对于PHP系统函数的影响
   safe_mode是提供一个基本安全的共享环境。在一个多用户共享的phpweb服务器上,当这台服务器开启了safe_mode模式,有以下函数将会受到影响。首先,一下尝试访问文件系统的函数将会被限制,运行服务器的用户id,如果想要尝试操作某个文件,必须要用户该文件的读取或者写入的访问权限。
   因此,在safe_mode打开的情况下,下列函数将会收到限制:
ckdir,move_uploaded_file,chgrp,parse_ini_file,chown,rmdir,copy,rename,fopen,require,highlight_file,show_source,include,symlink,link,touch,mkdir,unlink
   以上都是跟操作文件系统有关的函数,除此之外,一些php扩展的函数也会受到限制,不能在程序里面直接加载扩展,只能到php.ini里加载,而且php如果需要执行操作系统的程序时,必须在safe_mode_exec_dir中指定程序的路径,否则执行将失败。此外还有exec,shell_exec,pasathru,system,popen等函数会收到限制

 


3. PHP5中魔术方法函数有哪几个,请举例说明各自的用法
__sleep
__wakeup
__toString
__set_state
__construct,
__destruct
__call,
__get,
__set,
__isset,
__unset
__sleep,
__wakeup,
__toString,
__set_state,
__clone
__autoload

 


4. 请写出让,并说明如何在命令行下运行PHP脚本(写出两种方式)同时向PHP脚本传递参数?
$PHP_HOME/bin/php -r 'echo $argv[1];' hello
$PHP_HOME/bin/php hello.php hello

 

   window下,假设php安装目录为c:\program files\php5\,那么使用命令窗口进入到该路径下,敲入php hello.php回车,则会执行当前路径下的hello.php文件,
   如果要指向其他路径下php文件,可以在php 路径/hello.php ,这种形式称为CLI模式,我们平时通过浏览器看到的那种成为CGI模式,至于传递参数,php文件在cli模式下,直接通过在文件名称后面接参数,多个参数中间用空格隔开,在php文件里面是通过两个变量来获取参数的,一个是$argv,一个是$argc,前者是传递参数的数组,默认第一个为php文件的名称;后者为$argv的数组个数。
   linux下,一般程序安装都会安装在/usr/bin/php下面,可以通过man php查看一下,如果有信息说明可以使用,使用方法类似于window下。如果前面这步成立,那么你可以直接 php php文件 来运行php文件,如果man php没有信息,则说明当前php执行文件没有在环境路径里面,可以修改环境路径包含php路径,也可以类似于window进入php路径,在执行 php php文件。其他类似于window下。

 


5. PHP的垃圾收集机制是怎样的
在PHP中,没有任何变量指向这个对象时,这个对象就成为垃圾。PHP会将其在内存中销毁;这是PHP 的GC垃圾处理机制,防止内存溢出。
当一个 PHP线程结束时,当前占用的所有内存空间都会被销毁,当前程序中所有对象同时被销毁。GC进程一般都跟着每起一个SESSION而开始运行的.gc目的是为了在session文件过期以后自动销毁删除这些文件.
执行这些函数也可以起到回收作用
__destruct /unset/mysql_close

 


6.使对象可以像数组一样进行foreach循环,要求属性必须是私有。
(Iterator模式的PHP5实现,写一类实现Iterator接口)
PHP5开始支持了接口, 并且内置了Iterator接口, 所以如果你定义了一个类,并实现了Iterator接口,那么你的这个类对象就是ZEND_ITER_OBJECT,否则就是ZEND_ITER_PLAIN_OBJECT.
对于ZEND_ITER_PLAIN_OBJECT的类,foreach会通过HASH_OF获取该对象的默认属性数组,然后对该数组进行foreach.
而对于ZEND_ITER_OBJECT的类对象,则会通过调用对象实现的Iterator接口相关函数来进行foreach, 所以, 对于这道笔试题, 可以作出如下的答案:
[php]
class sample implements Iterator
{
private $_items = array(1,2,3,4,5,6,7);

 


public function __construct() {
;//void
}
public function rewind() { reset($this->_items); }
public function current() { return current($this->_items); }
public function key() { return key($this->_items); }
public function next() { return next($this->_items); }
public function valid() { return ( $this->current() !== false ); }
}
$sa = new sample();
foreach($sa as $key => $val){
print $key . "=>" .$val;
}[/php]
以上代码在我的php 5.3下运行正常。

 

 

 

7.请写一段PHP代码,确保多个进程同时写入同一个文件成功
function writeData($path, $mode, $data){
$fp = fopen($path, $mode);
$retries = 0;
$max_retries = 100;
do {
if ($retries > 0) {
usleep(rand(1, 10000));
}
$retries += 1;
}while (!flock($fp, LOCK_EX) and $retries

 

if ($retries == $max_retries) {
return false;
}

 

fwrite($fp, "$data\n");
flock($fp, LOCK_UN);
fclose($fp);
return true;
}

 


8. 用PHP实现一个双向队列

 

 

 

9. 使用正则表达式提取一段标识语言(html或xml)代码段中指定标签的指定属性值(需考虑属性值对不规则的情况,如大小写不敏感,属性名值与等号间有空格等)。此处假设需提取test标签的attr属性值,请自行构建包含该标签的串

 


 


 

 

 

10.请使用socket相关函数(非curl)实现如下功能:构造一个post请求,发送到指定http server的指定端口的指定请求路径(如http://www.example.com:8080/test)。请求中包含以下变量:
用户名(username):温柔一刀
密码(pwd):&123=321&321=123&
个人简介(intro):Hello world!
且该http server需要以下cookie来进行简单的用户动作跟踪:

 

cur_query:you&me
last_tm:...(上次请求的unix时间戳,定为当前请求时间前10分钟)
cur_tm:...(当前请求的unix时间戳)
设置超时为10秒,发出请求后,将http server的响应内容输出。

 


function encode($data, $sep = ‘&’){
while (list($k,$v) = each($data)) {
$encoded .= ($encoded ? "$sep" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
Return $encoded;
}

 

function post($url, $post, $cookie){
$url = parse_url($url);
$post = encode($data, ‘&’);
$cookie = encode($cookieArray, ‘;’);
$fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80, $errno, $errstr, 10);
if (!$fp) return "Failed to open socket to $url[host]";
fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Content-length: " . strlen($encoded) . "\n");
fputs($fp, "Cookie: $cookie\n\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, "$post \n");
while (!feof($fp)) {
echo fgets($fp, 128);
}

 

fclose($fp);
}

 

$url = ‘http://www.example.com:8080/test’;
$encoded = username=温柔一刀& pwd=
$post = array(
‘username’=> ‘温柔一刀’,
‘pwd => ‘&123=321&321=123&’,
‘intro => ‘Hello world!’
);

 

$cookie = array(
‘cur_query’ => ‘you&me,
‘last_tm’ => time() - 600,
‘cur_tm ‘=> time()
);

 

Post($url, $post, $cookie);

 

 

 

11.你用什么方法检查PHP脚本的执行效率(通常是脚本执行时间)和数据库SQL的效率(通常是数据库Query时间),并定位和分析脚本执行和数据库查询的瓶颈所在?
1.脚本执行时间,启用xdebug,使用WinCacheGrind分析。
2.数据库查询,mysql使用EXPLAIN分析查询,启用slow query log记录慢查询。
3, xdebug统计函数执行次数和具体时间进行分析。
4, 在线系统用strace跟踪相关进程的具体系统调用。

 

 

 

 

 


PHP LAMP Engineer Test Paper
Question 1
What does echo count ("123") ?> print out?
A) 3
B) False
C) Null
D) 1
E) 0

 


Question 2
Which of the following snippets prints a representation of 42 with two decimal places?
A) printf("%.2d\n", 42);
B) printf("%1.2f\n", 42);
C) printf("%1.2u\n", 42);

 


Question 3
Given
$text = 'Content-Type: text/xml';
Which of the following prints 'text/xml'?
A) print substr($text, strchr($text, ':'));
B) print substr($text, strchr($text, ':') + 1);
C) print substr($text, strpos($text, ':') + 1);
D) print substr($text, strpos($text, ':') + 2);
E) print substr($text, 0, strchr($text, ':')
Question 4
What is the value of $a?
$a = in_array('01', array('1')) == var_dump('01' == 1);
?>
A) True
B) False
Question 5
What is the value of $result in the following PHP code?
function timesTwo($int) {
$int = $int * 2;
}
$int = 2;
$result = timesTwo($int);
?>;
Answer: NULL
Question 6
The code below ___________ because ____________.
class Foo {
?>
function bar() {
print "bar";
}
}
?>
A) will work, class definitions can be split up into multiple PHP blocks.
B) will not work, class definitions must be in a single PHP block.
C) will not work, class definitions must be in a single file but can be in multiple PHP blocks.
D) will work, class definitions can be split up into multiple files and multiple PHP blocks.
Question 7
When turned on, ____________ will _________ your script with different variables from HTML forms and cookies.
A) show_errors, enable
B) show_errors, show
C) register_globals, enhance
D) register_globals, inject
Question 8
What will be the output of the following PHP code:
echo count(strlen("http://php.net"));
?>
Answer: 1
Question 9
What is the best all-purpose way of comparing two strings?
A) Using the strpos function
B) Using the == operator
C) Using strcasecmp()
D) Using strcmp()
Question 10
What is the difference between "print()" and "echo()"?
Answer: print is a function,echo is a language construct

 

 

 

 


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Travailler avec les données de session Flash dans Laravel Travailler avec les données de session Flash dans Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifie la gestion des données de session temporaires à l'aide de ses méthodes de flash intuitives. Ceci est parfait pour afficher de brefs messages, alertes ou notifications dans votre application. Les données ne persistent que pour la demande ultérieure par défaut: $ demande-

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Mar 14, 2025 am 11:42 AM

L'extension PHP Client URL (CURL) est un outil puissant pour les développeurs, permettant une interaction transparente avec des serveurs distants et des API REST. En tirant parti de Libcurl, une bibliothèque de transfert de fichiers multi-protocol très respectée, PHP Curl facilite Efficient Execu

Misque de réponse HTTP simplifié dans les tests Laravel Misque de réponse HTTP simplifié dans les tests Laravel Mar 12, 2025 pm 05:09 PM

Laravel fournit une syntaxe de simulation de réponse HTTP concise, simplifiant les tests d'interaction HTTP. Cette approche réduit considérablement la redondance du code tout en rendant votre simulation de test plus intuitive. L'implémentation de base fournit une variété de raccourcis de type de réponse: Utiliser illuminate \ support \ faades \ http; Http :: faux ([[ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 meilleurs scripts de chat PHP sur Codecanyon 12 meilleurs scripts de chat PHP sur Codecanyon Mar 13, 2025 pm 12:08 PM

Voulez-vous fournir des solutions instantanées en temps réel aux problèmes les plus pressants de vos clients? Le chat en direct vous permet d'avoir des conversations en temps réel avec les clients et de résoudre leurs problèmes instantanément. Il vous permet de fournir un service plus rapide à votre personnalité

Expliquez le concept de liaison statique tardive en PHP. Expliquez le concept de liaison statique tardive en PHP. Mar 21, 2025 pm 01:33 PM

L'article traite de la liaison statique tardive (LSB) dans PHP, introduite dans PHP 5.3, permettant une résolution d'exécution de la méthode statique nécessite un héritage plus flexible. Problème main: LSB vs polymorphisme traditionnel; Applications pratiques de LSB et perfo potentiel

Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Mar 28, 2025 pm 05:12 PM

L'article examine l'ajout de fonctionnalités personnalisées aux cadres, en se concentrant sur la compréhension de l'architecture, l'identification des points d'extension et les meilleures pratiques pour l'intégration et le débogage.

Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Apr 01, 2025 pm 03:12 PM

Envoyant des données JSON à l'aide de la bibliothèque Curl de PHP dans le développement de PHP, il est souvent nécessaire d'interagir avec les API externes. L'une des façons courantes consiste à utiliser la bibliothèque Curl pour envoyer le post� ...

See all articles