1. What are the differences between echo(), print(), and print_r()?
echo() is a language construct with no return value.
print() is functionally similar to echo() and is also a language construct, but unlike echo, print has a return value and always returns 1.
print_r prints recursively and is used to output arrays and objects.
2. What are the differences between the GET and POST submission methods in a form?
The GET method is the default way for HTML forms to submit data. It passes user data through URL requests. The amount of data transmitted by GET is very small, generally limited to around 2KB, but its execution efficiency is higher than that of the POST method. Because the data transmitted using GET is transparent to the user, it may introduce certain security issues. The POST method uses the HTTP POST mechanism to pass the data within the form to the server via the HTML header. Unlike the GET method, data passed by POST is invisible to the user, and the volume of data transmitted by POST can be much larger.
3. What is the difference between session and cookie?
Cookies are saved on the client side, while sessions are saved on the server side, and the session ID is saved on the client side.
4. What is a transaction in a database?
A transaction is a unit of operation where all operations within it either all succeed or all fail. If all operations succeed, the transaction is committed. Even if one operation fails, the transaction will roll back, and all affected data will be restored to its previous state.
5. How do you reverse a string?
<?php
$a = ‘abcde’;
$b = ”;
for ($i=strlen($a)-1;$i>=0;$i–) {
$b .= $a{$i};
}
// 或者
$c = strrev($a);
?>6. What are the methods to optimize a MySQL database?
Optimize queries, such as using indexes and replacing subqueries with join queries.
Optimize database structure, such as splitting tables, adding intermediate tables, adding redundant fields, analyzing tables, checking tables, and optimizing tables.
Optimize the speed of inserting records, such as disabling indexes before inserting records and inserting multiple records with a single INSERT statement.
Optimize MySQL server hardware configuration, such as increasing memory, adding disks, and improving disk read/write speed.
Optimize MySQL server parameter configuration.
7. Please explain the difference between passing by value and passing by reference in PHP. When should you pass by value, and when should you pass by reference?
Pass by value: Variables are assigned by value by default. When the value of one variable is assigned to another variable, changing the value of one variable will not affect the other variable.
Pass by reference: Modifying the new variable will affect the original variable, and vice versa.
When passing by value, the value must be copied, which incurs a certain performance overhead for large strings and objects. Passing by reference does not require copying the value, which is beneficial for performance improvement.
8. What is the difference between mysql_fetch_row and mysql_fetch_array?
mysql_fetch_row() fetches a row from the result set as an enumerated array.
mysql_fetch_array() fetches a row from the result set as an associative array, a numeric array, or both.
9. Please describe the meaning of the data types (int, char, varchar, datetime, text); what is the difference between char and varchar?
int: numeric type; char: fixed-length string; varchar: variable-length string; datetime: date/time type, a combination of date and time; text: text string.
The length of char is fixed to the length declared when the table is created. When saving a char value, it is padded with spaces on the right to reach the specified length. varchar is a variable-length string, and varchar values are not padded when saved.
10. Please write down the PHP 5 access control modifiers.
public (public), protected (protected), private (private).
11. Please write down the constructor and destructor in PHP 5.
__construct __destruct
12. Find the maximum and minimum values among three numbers: $a, $b, and $c.
<?php
$a = 3;
$b = 44;
$c = 40;
echo max($a,$b,$c);
echo min($a,$b,$c);
?>13. Write a simple query in PHP to find all records with the name “Zhang San” and print them out.
Table name: user
name tel content date
Zhang San 13333663366 College graduate 2006-10-11
Zhang San 13612312331 College graduate 2006-10-15
Zhang Si 021-55665566 College graduate 2006-10-15
Please complete the code based on the problem above:
<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); /* check connection */ if ($mysqli->connect_errno) {
echo("Connect failed: ", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM user WHERE name='张三'";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['name'].' ';
echo $row['tel'].' ';
echo $row['content'].' ';
echo $row['date']. '
’;
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
14. How do you use the following class, and explain what it means?
<?php class test { function Get_test($num) { $num = md5(md5($num)."En"); return $num; } } $test = new test(); $num = 1; $test->Get_test($num);
?>
15. Write the format for SQL statements: insert, update, delete.
Table name: User
Name Tel Content Date
Zhang San 13333663366 College graduate 2006-10-11
Zhang San 13612312331 Bachelor’s degree 2006-10-15
Zhang Si 021-55665566 Vocational high school graduate 2006-10-15
(a) There is a new record (Xiao Wang 13254748547 High school graduate 2007-05-06). Please use an SQL statement to add it to the table.
(b) Please use an SQL statement to update Zhang San’s date to the current system time.
(c) Please write a statement to delete all records with the name Zhang Si.
(a)
INSERT INTO User(‘Name’,’Tel’,’Content’,’Date’) VALUES(‘Xiao Wang’,’13254748547′,’High school graduate’,’2007-05-06′)
(b)
UPDATE User SET Date=DATE_FORMAT(NOW(),’%Y-%m-%d’) WHERE Name=’Zhang San’
(c)
DELETE FROM User WHERE Name=’Zhang Si’
16. Write the output result of the following program.
<?php
$b = 201;
$c = 40;
$a = $b>$c?4:5;
echo $a;
?>
4
17. Which functions can be used to prevent SQL injection?
intval(), htmlspecialchars()
18. What is PHP’s garbage collection mechanism?
In PHP, when no variables point to an object, it becomes garbage. PHP will destroy it in memory; this is PHP’s GC (garbage collection) mechanism, which prevents memory overflow.
19. What methods do you use to check the execution efficiency of a PHP script (usually script execution time) and the efficiency of database SQL (usually database query time), and to locate and analyze the bottlenecks in script execution and database queries?
<?php
$begin = microtime(true); //获取程序执行开始的时间
// some code here 待执行的代码
$stop = microtime(true); //获取程序执行结束的时间
echo $begin;
echo '
';
echo $stop;
list($m0, $s0) = explode(" ", $begin);
list($m1, $s1) = explode(" ", $stop);
$runtime = ($s1 + $m1 - $s0 - $m0) * 1000;
echo '
当前脚本执行时间:' . $runtime . '微秒';
?>
explain
20. Please give examples of methods you use during development to speed up page loading.
Backend:
Generate static HTML
Generate XML
Use acceleration software, such as Zend
Frontend:
Compression and merging of JS, CSS, and images
21. For high-traffic websites, what methods do you use to solve traffic volume issues?
1. Use traffic analysis and statistics software;
2. Confirm whether the server hardware is sufficient to support current traffic;
3. Optimize database access;
4. Prevent external hotlinking;
5. Control the downloading of large files;
6. Use different hosts to distribute the main traffic load;
7. Squid [reverse proxy], the best choice;
8. Increase bandwidth;
22. What are the three main characteristics of object-oriented programming?
Encapsulation, Inheritance, Polymorphism
23. Please talk about MVC.
The goal of MVC is to separate business logic from user interface considerations. In MVC, the model represents information (data) and business rules; the view contains user interface elements, such as text, forms, etc.; the controller manages the communication between the model and the view.
24. Have you used design patterns? Please list them.
Factory pattern, Singleton pattern, Observer pattern, Chain of command pattern, Strategy pattern
25. Write a bubble sort algorithm.
<?php
$arr = array(45,56,67,32,33,23,37,455,223,223,23);
for ($i=1;$i<count($arr);$i++) { for ($j=count($arr)-1;$j>=$i;$j–) {
if ($arr[$j]<$arr[$j-1]) { $temp = $arr[$j-1]; $arr[$j-1] = $arr[$j]; $arr[$j] = $temp; } } }
?>26. Write a function as efficiently as possible to extract the file extension from a standard URL.
<?php
$url = 'http://www.sina.com.cn/abc/de/fg.php?id=1';
function getext($url) {
//解析url,返回其组成部分,返回值为一数组
$arr = parse_url($url);
//print_r($arr);
$file = basename($arr['path']);
$ext = explode(".", $file);
return $ext[1];
}
echo getext($url);
?>
27. What are the differences between sort(), asort(), and ksort()? Under what circumstances are they used respectively?
sort() sorts an array; when this function ends, the array elements will be rearranged from lowest to highest.
asort() sorts an array and maintains index association.
ksort() sorts an array by its keys.
28. What is the output of the following code? Why?
<?php
$num = 10;
function multiply() {
$num = $num * 10;
}
multiply();
echo $num;
?>
Because $num inside the function is undefined, and its scope is limited to within the function.
29. What will be the output of executing the code snippet <?php echo 8%(-2) ?>?
0
30. What is the difference between a reference and a regular variable? How do you pass by reference? Under what circumstances do we need to do this?
A reference passes the address of the variable rather than its value.
<?php
$var = ‘aad’;
//myfunction(&$var); //pass by reference
?>
Passing a parameter to a function by reference allows the function’s modifications to the variable to persist even after the function ends.
31. What is the difference between foo() and @foo()?
foo() will display an error message when an error occurs.
@foo() will suppress the error message when an error occurs.
32. Explain “===” and “==”.
== checks if the values are equal.
=== checks if the values are equal and requires the types to be identical.
33. What is the difference between include and include_once? What about require?
include_once will not include the file again if it has already been included.
require_once will not include the file again if it has already been included.
<?php
define(‘__ROOT__’, dirname(dirname(__FILE__)));
//require_once(__ROOT__.’/1.php’);
//require_once(__ROOT__.’/1.php’);
?>
34. Among redir(), herder(), location(), and redirect(), which function can redirect the browser to another page?
header()
35. Among fget(), file_open(), fopen(), and open_file(), which function can be used to open a file for reading/writing?
fopen()
36. How do you use PHP to solve the stateless nature of HTTP?
session, cookie
37. What is the GD function library used for?
Processing images
38. A function’s parameter cannot be a reference to a variable unless ____ is set to on in php.ini?
allow_call_time_pass_reference
39. Write a function as efficiently as possible to traverse all subfolders in the ‘home’ directory and return an array of subfolder names.
<?php
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] = my_scandir($dir . ‘/’ . $file);
} else {
$files[] = $file;
}
}
}
}
return $files;
}
$result = my_scandir(‘E:\php\home’);
print_r($result);
?>
40. Print the time exactly one day ago in the format: “Year-Month-Day Hour:Minute:Second”.
<?php
echo date(‘Y-m-d H:i:s’,strtotime(‘-1 day’,time()));
?>
41. The meaning of several status codes in the HTTP protocol: 503, 500, 401, 200, 301, 302.
503 Request timeout
500 Internal server error, usually caused by a PHP program
401 Unauthorized access
200 OK (correct response)
301 Permanent redirect
302 Temporary redirect
41. Implement a function to convert the string “action_test” to “ActionTest” and “my_book” to “MyBook”.
<?php
$a = ‘action_test’;
$b = str_replace(‘_’,’ ‘,$a);
$c = ucwords($b);
$d = str_replace(‘ ‘,”,$c);
echo $d;
?>
43. What are the magic methods in PHP 5? Please give examples to explain their usage.
__sleep: serialization
__wakeup: unserialization
__toString: called when printing an object
__invoke: automatically called when attempting to call an object as a function
__set_state
__construct: constructor
__destruct: destructor
__call: automatically called when invoking an inaccessible method in a class
__get: automatically called when accessing an inaccessible property in a class
__set: automatically called when assigning a value to an inaccessible property in a class
__isset: automatically called when using the isset function on an inaccessible property in a class
__unset: automatically called when using the unset function on an inaccessible property in a class
__clone: automatically called when cloning an object
__autoload: automatically called when instantiating a class if the corresponding class does not exist
44. What PHP function can be used to reset configurations in php.ini?
ini_set()
45. Write down the names of at least two MySQL storage engines and briefly describe their differences.
MyISAM is MySQL’s default storage engine. It supports full-text indexing but is not transaction-safe and does not support foreign keys.
InnoDB does not support full-text indexing but is transaction-safe.
46. List some open-source databases.
mysql, memcached, MariaDB, PostgreSQL
47. List some commonly used PHP extensions, such as GD.
mysql, mysqli, pdo, sockets, zip, openssl, xmlrpc
48. Please convert “2014-2-17 00:00:00” to a Unix timestamp (the number of seconds from Greenwich Mean Time to the current time), and format 1392612299 into a Year-Month-Day format.
<?php
echo strtotime(‘2014-2-17 00:00:00′).'<br />’;
echo date(‘Ymd’,1392612299);
?>
49. Use PHP to calculate the difference in days between 2014-2-17 and 2008-8-8.
<?php
$startdate = strtotime(‘2014-2-17’);
$enddate = mktime(‘0′,’0′,’0′,’8′,’8′,’2008’);
echo round(($startdate-$enddate)/3600/24);
?>
50. Please convert $aa=’12,32,11,11′ into an array array(12,32,11,11), and write the code to restore it back to $aa=’12,32,11,11′.
<?php
$aa = ‘12,32,11,11’;
$aa_array = explode(‘,’,’12,32,11,11′);
print_r($aa_array);
$bb = implode(‘,’,$aa_array);
echo $bb;
?>
51.
<?php
$b = 13;
6 + $a = $b;
echo(abs($a));
?>
13
52.
<?php
echo 1+2+”a+4+5″;
?>
3
53.
<?php
echo 1+2+”3+a+5″;
?>
6
54.
<?php
echo 1+2+”1+1+2″;
?>
4
55. Display result:
<?php
$a = 12;
$b = 012;
$c = 0*12;
echo $a,”\n”,$b,”\n”,$c;
?>
12 10 0
56. When the output is Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0, the possible output statement is:
<?php
echo $_SERVER[‘HTTP_USER_AGENT’];
?>
57. Which of the following statements is incorrect? D
A. PHP has four scalar types: boolean, integer, float, and string.
B. Float and double are the same type.
C. Composite types include: array, object, and resource.
D. Pseudo-types: mixed, number, callback.
58. After executing the following code,
<?php
echo function_exists(‘print’);
?>
The output obtained is: empty
59. The function that is not part of PHP syntax is: A
A. array; it is a language construct, not a regular function.
B. eval; the eval() function evaluates a string as PHP code.
C. each; returns the current key/value pair in an array and advances the array pointer by one step.
D. list; list — assigns values from an array to some variables.
60. The correct description of echo and print is: C
A. Both echo and print can print multiple parameters.
B. print can print multiple parameters, but echo cannot.
C. echo can print multiple parameters, but print cannot.
D. Neither echo nor print can print multiple parameters.
61. The correct output of the following code is: C
<?php
$a = array(1=>5,5=>8,22,2=>’8′,81);
echo $a[7];
echo $a[6];
echo $a[3];
?>
A. empty 22 81
B. empty 81 22
C. 81 22 empty
D. empty empty empty
62. The output result of the following code is: D
<?php
$a[bar] = ‘hello’;
echo $a[bar];
//Note: If quotes are not added, PHP can automatically convert the constant to a string, but efficiency decreases by about 8 times.
echo $a[‘bar’];
?>
A. hello
B. empty empty
C. Error
D. hellohello
63. What is the result of executing the following code? A
<?php
$bool = TRUE;
echo gettype($bool);
echo is_string($bool);
?>
A. boolean
B. boolean0
C. booleanFALSE
D. booleanfalse
Note: gettype gets the variable’s type; is_string checks whether the variable is a string.
64. Write the result of the following code: C
<?php
echo 1>>0;
echo 2>>1;
echo 3<<2;
//Note: Left shift by one bit multiplies by 2, right shift divides by 2.
?>
A. 012
B. 106
C. 1112
D. 123
65. The execution result of the following code is: A
<?php
for($i=0;$i<10;$i++){
//Note: The second parameter is missing $, so it is a constant, not a variable. The constant is converted to a string and then to the number 0. Since 0<10, it loops continuously.
print $i;
}
?>
A. 0123456789
B. 012345678910
C. No output
D. Infinite loop
66. For the following code,
<?php
$fruits = array(‘strawberry’=>’red’,’banana’=>’yellow’);
?>
The code that can correctly obtain the result ‘yellow’ is: ACD
<?php
echo “A banana is {$fruits[‘banana’]}”;
//Test point: embedding variables in double quotes, braces act as a scope delimiter.
//echo “A banana is $fruits[‘banana’]”;
echo “A banana is {$fruits[banana]}”;
//Type conversion occurs, so it is slower, but it is correct.
echo “A banana is $fruits[banana]”;
//Variables inside double quotes stop at special characters. [ is not a special character, so it continues reading forward.
?>
67. C
<?php
$foo = ‘test’;
$bar = <<< EOT
$foo bar
EOT;
echo $bar;
?>
The output of the above statement is:
A. $foo bar;
B. ‘EOT’ $foo bar EOT;
C. test bar;
D. ‘EOT’ test bar EOT
68. A
<?php
$a = 3;
$b = 4;
if($a||$b=5){
echo ‘todo’;
}
?>
The value of $b is ():
A. 4;
$a=3; 3 is a boolean true, so the execution does not proceed further, meaning $b remains 4.
B. 5;
C. 3;
D. false
69. What is the difference between preg_replace and preg_replace_callback?
preg_replace performs a regular expression search and replace.
preg_replace_callback performs a regular expression search and replaces using a callback function.
70. How do you use CSS to show/hide a DOM element? If there are multiple ways, please point out their differences.
display:block;
display:none;
71. Please write down commonly used methods to clear floats.
Add an empty tag after all floating elements inside the parent element that needs float clearing to clear the float, .clear{clear:both;}
overflow:auto;zoom:1;
:after
72. If a div uses the following styles respectively, what characteristics will it have? display:inline; display:block; display:inline-block;
display:inline; The element will be displayed as an inline element, with no line breaks before and after the element.
display:block; The element will be displayed as a block-level element, with line breaks before and after the element.
display:inline-block; Inline-block element.
73. How does the IE6 double margin bug occur, and how can it be resolved?
float, margin
display:inline;
74. Given a div style: width:100px; height:100px; margin:50px 20px; padding:50px 20px; what is the actual height of this div?
200px
75. For a container with known width and height, how do you center it horizontally and vertically on the page?
text-align:center; vertical:middle;
76. Check if a string is composed as follows: the first character must be a letter, followed by letters, numbers, or underscores, with a total length of 5-20 (using regex).
<script>
var reg = /^[a-zA-Z][a-zA-Z_0-9]{4,19}$/;
reg.test(“aeu3_di876”);
</script>
77. Please point out the phenomena and solutions of script compatibility issues between IE and FF.
(1) window.event;
Represents the current event object. IE has this object, but FF does not; FF passes the event object to the event handler function.
(2) Getting the event source
IE uses srcElement to get the event source, while FF uses target.
(3) Adding and removing events
IE: element.attach(“onclick”,function); element.detach(“onclick”,function);
FF: element.addEventListener(“onclick”,function,true); element.removeEventListener(“onclick”,function,true);
(4) Getting custom attributes of a tag
IE: div.value, div[“value”]
FF: div.getAttribute[“value”]
(5) document.getElementByName() and document.all[name]
IE: Neither can get elements.
FF: Both can.
(6) input.type attribute
IE: Read-only.
FF: Read/write.
(7) innerText, textContent, outerHTML
IE: Supports innerText and outerHTML.
FF: Supports textContent.
78. Implementation of inheritance in JavaScript object-oriented programming.
<script>
function Animal(name){
this.name = name;
}
Animal.prototype.getName = function(){
alert(this.name)
}
function Dog(){};
Dog.prototype = new Animal(“Buddy”);
Dog.prototype.constructor = Dog;
var dog = new Dog();
</script>
79. Write a method to remove duplicate elements from an array.
<script>
var arr = [1,1,2,3,3,2,1];
Array.prototype.unique = function(){
var ret = [];
var o = {};
var len = this.length;
for (var i=0;i<len;i++){
var v = this[i];
if (!o[v]){
o[v] = 1;
ret.push(v);
}
}
return ret;
};
//alert(arr.unique());
</script>
80. How do you check if a variable is a String type in JavaScript? Please write the function implementation.
<script>
//There are two ways to generate a String type
//var str = “hello world”;
var str2 = new String(“hello world”);
function IsString(str){
return (typeof str == “string” || str.constructor == String);
}
var str = “”;
//alert(IsString(1));
//alert(IsString(str2));
</script>
81. Complete the code so that after clicking Button1 with the mouse, Button1 is moved behind Button2.
<div>
<input type=”button” id=”button1″ value=”1″ onclick=”moveBtn(this);” />
<input type=”button” id=”button2″ value=”2″ />
</div>
<script>
function moveBtn(obj) {
var clone = obj.cloneNode(true);
var parent = obj.parentNode;
parent.appendChild(clone);
parent.removeChild(obj);
}
</script>
82. How should the following CSS properties be spelled when called in JavaScript: border-left-color, -moz-viewport?
borderLeftColor
mozViewport
83. Please write a JavaScript function parseQueryString, which is used to parse URL parameters into an object.
<script>
function parseQueryString(url){
var params = {};
var arr = url.split(“?”);
if (arr.length <= 1) return params;
arr = arr[1].split(“&”);
for(var i=0,l=arr.length; i<l; i++){
var a = arr[i].split(“=”);
params[a[0]] = a[1];
}
return params;
}
var url = “http://witmax.cn/index.php?key0=0&key1=1&key2=2”;
var ps = parseQueryString(url);
//alert(ps[“key2”]);
</script>

