PHP Pen Questions Collection

Source: Internet
Author: User
Tags array sort php print print format
PHP Pen Questions Summary

1, crawl the remote image to the local, you will use what function?

Fsockopen, A

2. Write a function that asks for the maximum value of 3 with the least amount of code.

function ($a, $b, $c) {
* W0 z* U6 k + E. L A:}5} return $a > $b? ($a > $c? $a: $c): ($b > $c? $b: $c);
5 O:f6 v1 w# U}

3, in PHP print out the day before, the print format is May 10, 2007 22:21:21

Echo date (' y-m-d h:i:s ', Strtotime ('-1 day '));

4, JavaScript can define a two-dimensional array, if not you how to solve?

JavaScript does not support two-dimensional array definitions and can be resolved with arr[0] = new Array ()

5, assume that a.html and b.html under the same folder, with JavaScript implementation when the a.html opened for five seconds, automatically jump to b.html.


function go2b () {
window.location = "b.html";
Window.close ();
}

SetTimeout ("go2b ()", 5000); Auto-execute go2b after 5 seconds ()




6,//Is browsing the current page user's IP address: 127.0.0.1
echo $_server["REMOTE_ADDR"]. "
”;
(query) string (the first question mark in the URL?) Later content): id=1&bi=2
echo $_server["Query_string"]. "
”;
The document root directory where the currently running script is located: D:inetpubwwwroot
echo $_server["Document_root"]. "
”;
7, in HTTP 1.0, the meaning of status Code 401 is not authorized ____; If you return the prompt "file not found", the header function is available, and the statement is the header ("http/1.0 404 Not Found");
Answer: 401 means unauthorized; header ("http/1.0 404 Not Found");

8. Write a function that can traverse all the files and subfolders under a folder.
function My_scandir ($dir)
{
$files =array ();
if (Is_dir ($dir))
{
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 []= $dir.] /". $file;
}
}
}
Closedir ($handle);
return $files;
}
}
}
Print_r (My_scandir ("D:program filesinternet Explorermui"));
?>



9. Add John to the users array?

$users [] = ' John '; Array_push ($users, ' John ');



10. What is the function of error_reporting in PHP?
Answer: error_reporting () sets the error level of PHP and returns the current level.



11. Use regular Expressions (Regular expression) to write a function to verify that the e-mail message is in the correct format.
For:

$email =$_post[' email '];
if (!preg_match ('/^[\w. +@ ([\w.] +)\. [A-z] {2,6}$/i ', $email)) {
echo "e-mail detection failed";
}else{
echo "e-mail detection success";
}

?>

12. Write code showing client IP and server IP in PHP

Answer: Print client Ip:echo $_server[' REMOTE_ADDR '; Or: getenv (' remote_addr ');

Print server Ip:echo gethostbyname ("www.bolaiwu.com")



13, how to modify the session's survival time (1 points).

Answer: Method 1: Set session.gc_maxlifetime in php.ini to 9999 restart Apache

Method 2: $savePath = "./session_save_dir/";

$lifeTime = Hour * SECOND;

Session_save_path ($savePath);

Session_set_cookie_params ($lifeTime);

Session_Start ();

Method 3:setcookie () and Session_set_cookie_params ($lifeTime);



14, there is a web address, such as the PHP Development Resource Network homepage: http://www.phpres.com/index.html, how to get its content? ($/min)

Answer: Method 1 (for PHP5 and later versions):

$readcontents = fopen ("http://www.phpres.com/index.html", "RB");

$contents = Stream_get_contents ($readcontents);

Fclose ($readcontents);

Echo $contents;

Method 2:

Echo file_get_contents ("http://www.phpres.com/index.html");



15, please explain the difference between the value and the reference in PHP. When is the value passed? (2 points)

A: Passing by value: Any changes to values within the function scope are ignored outside the function

Pass by reference: Any changes to values within a function can also reflect these changes outside of the function

Pros and Cons: When passing by value, PHP must copy the value. This can be a costly operation, especially for large strings and objects.

Passing by reference does not require copying values, which is good for performance gains.



16, write a function, as efficiently as possible, remove the file extension from a standard URL

For example: http://www.sina.com.cn/abc/de/fg.php?id=1 need to remove PHP or. php

Answer 1:

function Getext ($url) {

$arr = Parse_url ($url);

$file = basename ($arr [' path ']);

$ext = Explode (".", $file);

return $ext [1];

}

Answer 2:

function Getext ($url) {

$url = basename ($url);

$pos 1 = strpos ($url, ".");

$pos 2 = Strpos ($url, "?");

if (Strstr ($url, "?")) {

Return substr ($url, $pos 1 + 1, $pos-$pos 1–1);

} else {

Return substr ($url, $pos 1);

}

}



17, use more than five ways to get a file extension

Requirements: dir/upload.image.jpg, find. jpg or JPG,
Must be handled using PHP's own processing function, which cannot be significantly duplicated and can be encapsulated into functions such as 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. $STR 1 = null;
$str 2 = false;
echo $str 1== $str 2? ' Equal ': ' Not equal ';

$str 3 = ";
$str 4 = 0;
Echo $str 3== $str 4? ' Equal ': ' Not equal ';

$str 5 = 0;
$str 6 = ' 0′;
echo $str 5=== $str 6? ' Equal ': ' Not equal ';
?>

Equal equality Unequal



19. What is the main difference between a field type varchar and char in a MySQL database? That field is more efficient to find, why?
VARCHAR is a variable length, saving storage space, char is fixed. Find efficiency to char type fast, because varchar is not fixed length, you must first find the length, then the data extraction, more than the char fixed-length type one more step, so less efficient



20. Use JavaScript to write out three ways to produce an image tag (hint: From method, object, HTML angle)

(1) var img = new Image ();
(2) var img = Document.createelementbyid ("image")
(3) img.innerhtml = ""



21, 16. Please describe the most significant difference between XHTML and HTML over two points
(1) XHTML must force the specified document type doctype,html not required
(2) XHTML All tags must be closed, HTML is more casual

22, write a sorting algorithm, can be a bubble sort or a quick sort, assuming the object to be sorted is a dimensional array.

Bubble sort (Array sort)
function Bubble_sort ($array)
{
$count = count ($array);
if ($count <= 0) return false;
for ($i =0; $i < $count; $i + +) {
for ($j = $count-1; $j > $i; $j –) {
if ($array [$j] < $array [$j-1]) {
$tmp = $array [$j];
$array [$j] = $array [$j-1];
$array [$j-1] = $tmp;
}
}
}
return $array;
}
Quick sort (Array sort)
function Quicksort ($array) {
if (count ($array) <= 1) return $array;
$key = $array [0];
$left _arr = Array ();
$right _arr = Array ();
for ($i =1; $i
if ($array [$i] <= $key)
$left _arr[] = $array [$i];
Else
$right _arr[] = $array [$i];
}
$left _arr = quicksort ($left _arr);
$right _arr = quicksort ($right _arr);
Return Array_merge ($left _arr, Array ($key), $right _arr);
}



23, write out three kinds of MySQL database storage engine name (hint: case-insensitive)
MyISAM, InnoDB, BDB (Berkeley DB), Merge, Memory (Heap), Example, Federated, Archive, CSV, blackhole, MaxDB, etc. more than 10 engines



24, the difference of two dates, for example, 2007-2-5 ~ 2007-3-6 Date Differential
Method One:
Class Dtime
{
function Get_days ($date 1, $date 2)
{
$time 1 = strtotime ($date 1);
$time 2 = strtotime ($date 2);
Return ($time 2-$time 1)/86400;
}
}
$Dtime = new Dtime;
echo $Dtime->get_days (' 2007-2-5′, ' 2007-3-6′);
?>
Method Two:
$temp = Explode ('-', ' 2007-2-5′ ');
$time 1 = mktime (0, 0, 0, $temp [1], $temp [2], $temp [0]);
$temp = Explode ('-', ' 2007-3-6′ ');
$time 2 = mktime (0, 0, 0, $temp [1], $temp [2], $temp [0]);
Echo ($time 2-$time 1)/86400;
Method Three: Echo ABS (Strtotime ("2007-2-1″)-strtotime (" 2007-3-1″) "/60/60/24 Calculate time difference



25, please write a function, to achieve the following functions:
The string "Open_door" is converted to "Opendoor", "make_by_id" to "Makebyid".
Method:
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");p Rint_r ($strexplode);
Method Two: $str = "make_by_id!";
$expStr =explode ("_", $str);
for ($i =0; $i <>
{
Echo ucwords ($expStr [$i]);
} Method Three: Echo str_replace (', ', ' Ucwords (Str_replace (' _ ', ' ', ' Open_door '));



26, the ID of a table has multiple records, the record of all this ID, and show the total number of records, with SQL statements and views,
Stored procedures are implemented separately.
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;
Method: View:
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



27, JS in the page forward and backward code (forward: History.forward (); =history.go (1); Back: History.back
(); =history.go (-1); )



28, Echo Count ("abc"); Output what?
Answer: 1

count-count the number of cells in an array or the number of properties in an object

int count (mixed$var [, int $mode]), if Var is not an array type or an object that implements the countable interface, returns 1, with one exception, if Var is NULL then the result is 0.

For an object, if SPL is installed, you can invoke count () by implementing the countable interface. The interface has only one method count (), and this method returns the return value of the count () function.



29, there is a one-dimensional array, which stores shaping data, please write a function, they are in order from large to small. Requires high efficiency of execution. and explain how to improve the efficiency of execution. (The function must be implemented by itself and cannot use PHP functions)

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, please give an example of how to use in your development process to speed up the page loading speed
A: To use the server resources to open, timely shut down the server resources, database Add index, the page can generate static, pictures and other large files separate server. Using the Code optimization tool



31. What does the following code produce?
$num = 10;
function Multiply () {
$num = $num *10;
}
Multiply ();
Echo $num;
The value of the $num is 10 because the function multiply () does not specify $num to be a global variable (for example, $num or $_globals[' num ').



What is the difference between static,public,private,protected in PHP class?

Static statically, the class name can be accessed

Public represents the global, and the inner and outer subclasses of the class can be accessed;

Private means that only this class can be used internally;

Protected is protected and is accessible only in this class or subclass or in the parent class;



What is the difference between get, post, and head in the HTTP protocol?

HEAD: Only the header of the page is requested.

GET: Requests the specified page information and returns the entity principal.

POST: The requesting server accepts the specified document as a new subordinate entity for the identified URI.

(1) HTTP defines different ways to interact with the server, with the most basic approach being GET and POST. In fact GET applies to most requests, while retaining POST is only used to update the site.

(2) When the form is submitted, if you do not specify method, the default is a GET request, the data submitted in the form will be appended to the URL, separated from the URL. The alphanumeric character is sent as is, but the space is converted to the "+" sign, and the other symbol is converted to%XX, where XX is the ASCII (or ISO Latin-1) value that the symbol is represented in 16 binary. The GET request submits the data to be placed in the HTTP request protocol header, and the data submitted by the post is placed in the Entity data;

The Get method submits only 1024 bytes of data, while Post does not have this limit.

(3) GET This is the most common method that the browser uses to request the server. Post This method is also used to transfer data, but unlike get, when using post, the data is not appended to the URI, but rather as a separate line to pass, at this time must also send a CONTENT_LENGTH title to indicate the length of the data, followed by a blank line, Then the data is actually transferred. Web forms are usually sent by post.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.