Home > Article > Backend Development > PHP Chinese Manual 2,_PHP Tutorial
Users can extend PHP’s built-in exception handling classes with custom exception handling classes. The following code illustrates which properties and methods in the built-in exception handling class are accessible and inheritable in subclasses. Translator's Note: The following code is only to illustrate the structure of the built-in exception handling class. It is not a usable code with practical significance.
<code>172d05cc14f2a03492c3d09fbbcba2ca<code>9e418cca9e6f533aeea2153772ec65a5If you use a custom class to extend the built-in exception handling class and redefine the constructor, it is recommended to call parent::__construct() at the same time to check whether all variables have been assigned values. When the object wants to output a string, you can overload __toString() and customize the output style.
Extend PHP’s built-in exception handling class
<code>ebf59540eec94d4301e03426506bd7a9code}]: {$this->message}n";<br>}<br>public function customFunction() {<br> echo "A Custom function for this type of exceptionn";<br> }<br>}<br><span>//</span>创建一个用于测试异常处理机制的类<br>class TestException{<br>public $var;<br>const THROW_NONE = 0;<br>const THROW_CUSTOM = 1;<br>const THROW_DEFAULT = 2;<br>function __construct($avalue = self::THROW_NONE) {<br>switch ($avalue) {<br>case self::THROW_CUSTOM:<br>// 抛出自定义异常<br>throw new MyException('1 is an invalid parameter', 5);<br>break;<br>case self::THROW_DEFAULT:<br>// 抛出默认的异常<br>throw new Exception('2 isnt allowed as a parameter', 6);<br>break;<br>default:<br>// 没有异常的情况下,创建一个对象<br>$this->var = $avalue;<br>break;<br>}<br>}<br>}<br>// 例子 1<br>try {<br>$o = new TestException(TestException::THROW_CUSTOM);<br>} catch (MyException $e) { // 捕获异常<br>echo "Caught my exceptionn", $e;<br>$e->customFunction();<br>} catch (Exception $e) { // 被忽略<br>echo "Caught Default Exceptionn", $e;<br>}<br>// 执行后续代码<br>var_dump($o);<br>echo "nn";<br>// 例子 2<br>try {<br>$o = new TestException(TestException::THROW_DEFAULT);<br>} catch (MyException $e) { // 不能匹配异常的种类,被忽略<br>echo "Caught my exceptionn", $e;<br>$e->customFunction();<br>} catch (Exception $e) { // 捕获异常<br>echo "Caught Default Exceptionn", $e;<br>}<br>// 执行后续代码<br>var_dump($o);<br>echo "nn";<br>// 例子 3<br>try {<br>$o = new TestException(TestException::THROW_CUSTOM);<br>} catch (Exception $e) { // 捕获异常<br>echo "Default Exception caughtn", $e;<br>}<br>// 执行后续代码<br>var_dump($o);<br>echo "nn";<br>// 例子 4<br>try {<br>$o = new TestException();<br>} catch (Exception $e) { // 没有异常,被忽略<br>echo "Default Exception caughtn", $e;<br>}<br>// 执行后续代码<br>var_dump($o);<br>echo "nn";<br>?> 12. Generator <code><code>Generators allow you to write code in a foreach block to iterate over a set of data without creating an array in memory, which would hit your memory limit or take up considerable processing time. Instead, you can write a generator function, just like a normal custom function, and instead of a normal function returning only once, the generator can yield as many times as needed in order to generate values that need to be iterated over.
<code>f9a4cdb6b0258524a4e17a87e3801022= 0) {<br> throw new LogicException('Step must be -ve');<br> }<br> for ($i = $start; $i >= $limit; $i = $step) {<br> yield $i;<br> }<br> }<br>}<br>/* Note that both range() and xrange() result in the same<br>* output below. */<br>echo 'Single digit odd numbers from range(): ';<br>foreach (range(1, 9, 2) as $number) {<br> echo "$number ";<br>}<br>echo "n";<br>echo 'Single digit odd numbers from xrange(): ';<br>foreach (xrange(1, 9, 2) as $number) {<br> echo "$number ";<br>}<br>?>Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9
The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing anIterator class, and the code is generally much more readable. For example, the following function and class are equivalent:
<code>29017561920f9f8fb1b9a7a2a12d3f11fileHandle = fopen($fileName, 'r')) {<br> throw new RuntimeException('Couldn't open file "' . $fileName . '"');<br> }<br> }<br> public function rewind() {<br> fseek($this->fileHandle, 0);<br> $this->line = fgets($this->fileHandle);<br> $this->i = 0;<br> }<br> public function valid() {<br> return false !== $this->line;<br> }<br> public function current() {<br> return $this->line;<br> }<br> public function key() {<br> return $this->i;<br> }<br> public function next() {<br> if (false !== $this->line) {<br> $this->line = fgets($this->fileHandle);<br> $this->i ;<br> }<br> }<br> public function __destruct() {<br> fclose($this->fileHandle);<br> }<br> }<br>?> 13. Quote <code><code> <code>fa808a56c4bf9bfcf2fdc13c440c3e5f<code>$aand
$bpoints to the same variable.
$aand
$bare exactly the same here, which is not the case with
$apoints to
$bor· // Instead, it is
$aand
$b points to the same place.
?>
<code>
If an array with a reference is copied, its value will not be dereferenced. The same is true for passing array values to functions. If an undefined variable is assigned by reference, passed by reference, or returned by reference, the variable is automatically created.
d936be75bddd2a03755e226fccd051ff
foo($b['b']); var_dump(array_key_exists('b', $b)); // bool(true)
$c = new StdClass; foo($c->d); var_dump(property_exists($c, 'd')); // bool(true) ?> The same syntax can be used in functions, which return references, and in the new operator (PHP 4.0.4 and later): <code>e6dfdd2754cc796be41f486d404b57e3 If a reference is assigned to a variable declared as global inside a function, the reference is only visible inside the function. This can be avoided by using the $GLOBALS array. Reference global variables within a function: <code>85bda31e85e71fb27daf68d8878d1b62 Think of global $var; as the abbreviation of $var =& $GLOBALS['var']; . Thus assigning other references to $var only changes the reference of the local variable.If a variable with a reference is assigned a value in a foreach statement, the referenced object is also changed.
bf9698bfcfe06d20f49046ed1a07bd5f
The second thing a reference does is pass a variable by reference. This is accomplished by creating a local variable within the function and that variable references the same content in the calling scope. For example:
<code><code>4be1a8ed38c67d5284bafdfde51e3b33954ea66123244d69ab788fa2ea1eb77f will make $a become 6. This is because the variable $var in the foo function points to and $a points to the same content. See Passing by Reference for a more detailed explanation. The third thing a reference does is reference return. References are not pointers.You can pass a variable by reference to a function so that the function can modify the value of its argument.
<code><span>8f314bc2738e9f10801c5cb66f252488</span> <code><span>9c62da65ff7a3aa4746926eb65fd808e</span>Note that there are no reference symbols in function calls - only in function definitions. The function definition alone is enough for parameters to be passed correctly by reference
The following can be passed by reference:Variables, such as foo($a); New statements, such as foo(new foobar());
References returned from functionsAny other expression cannot be passed by reference, and the result is undefined. <code><span>0f8176a1b59124c1b92cdda034fa2bde</span>
<code><span>23d9a7a2037bfa130e5f81cfed92d7fa<em></em></span> Reference return is used when you want to use a function to find which variable the reference should be bound to.
Don't use return references to increase performance, the engine is smart enough to optimize it itself. Only return references if there is a valid technical reason! To return a reference, use this syntax: <code><span>d25be20ce66db377dba0b35ac60bbe78value;<br> }<br>}<br>$obj = new foo;<br>$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.<br>$obj->value = 2;<br>echo $myValue; // prints the new value of $obj->value, i.e. 2.<br>?></span> In this example, the properties of the object returned by the getValue function will be assigned values instead of copied, just like no reference syntax is used. Unlike parameter passing, the ampersand must be used in both places here - indicating that a reference is returned, not a usual copy, and also indicating that $myValue is bound as a reference, not a usual assignment. When you unset a reference, you just break the binding between the variable name and the variable's contents. This does not mean that the variable contents are destroyed. <code><code>13ba7f3a3d58531104876d0414453eaaa7b2e973802d993a340b1a8ad71f8c09 will not unset $b, just $a. Reference positioning: global reference: When declaring a variable with global $var a reference to the global variable is actually established. That is the same as doing this: <code><span>db26164e18dff323d4bdc442c592c374</span> <code><span>a766bb4978ee35615fef30fb8feb0e10</span>$this: In a method of an object, $this is always a reference to the object that calls it.
14. Predefined variables
Superglobal variables — Superglobal variables are built-in variables that are always available in all scopes. Many predefined variables in PHP are "superglobal", which means that they are in all scopes of a script. Available in all. They can be accessed within a function or method without executingglobal $variable; . These superglobal variables are:
$GLOBALS;$_SERVER;$_GET;$_POST;$_FILES;$_COOKIE;$_SESSION;$_REQUEST;$_ENV
By default, all superglobal variables are available. However, there are some directives that affect this availability. <code><span>d1aa754b54fe6dbda53e54117f5ecb86</span>$GLOBALS — refers to all variables available in the global scope. A global combined array containing all variables. The name of the variable is the key of the array. <code><var>687b9562a6503ed4f83fc894b9ab0ab2</var> "Superglobal" is also called the global variable of automation. This means that it is available in all scopes of the script. There is no need to use
global $variable;in a function or method to access it. Unlike all other superglobal variables, $GLOBALS is always available in PHP.
$_SERVER
is an array containing information such as header, path, and script locations. The items in this array are represented by
Web server creation. You may or may not be able to find the following elements in $_SERVER. List:
'PHP_SELF': The file name of the currently executing script, related to the document root. For example, use in a script at http://example.com/test.php/foo.bar
$_SERVER['PHP_SELF'] will get /test.php/foo.bar.
'SERVER_ADDR': The IP address of the server where the script is currently running.
'SERVER_NAME': The host name of the server where the script is currently running. If the script is running on a virtual host, the name is determined by the value set for that virtual host.
'SERVER_PROTOCOL': The name and version of the communication protocol when requesting the page. For example, "HTTP/1.0".
'REQUEST_METHOD': The request method used to access the page; for example, "GET", "HEAD", "POST", "PUT". 'REQUEST_TIME': The timestamp when the request started. Available since PHP 5.1.0.'QUERY_STRING': query string (query string), if any, through which page access is performed.
'HTTP_HOST': The content of the Host: item in the current request header, if it exists.
'HTTP_REFERER': Directs the user agent to the address of the previous page of the current page (if one exists). Determined by user agent settings. Not all user agents will set this item, and some also provide the function of modifying HTTP_REFERER. In short, the value is not trustworthy.
'HTTP_USER_AGENT': The content of the User-Agent: item in the current request header, if it exists. This string indicates information about the user agent accessing this page.
'REMOTE_ADDR': The IP address of the user browsing the current page.
'REMOTE_HOST': The host name of the user browsing the current page. DNS reverse resolution does not depend on the user's REMOTE_ADDR.
'SERVER_PORT': The port used by the web server. The default value is "80". If using SSL secure connection, this value is the HTTP port set by the user.
$_GET: Array of variables passed to the current script via URL parameters. GET is passed via urldecode().
$_POST: Array of variables passed to the current script via the HTTP POST method.
$_FILES: An array of items uploaded to the current script via HTTP POST.
$_REQUEST — HTTP Request variable, when run in command line mode, will not contain argv and argc information; they will exist in $_SERVERArray.
Since the variables in $_REQUEST are passed to the script file through the GET, POST and COOKIE input mechanisms, they can be tampered with by remote users and are not trustworthy. The items of this array and their order depend on the configuration of PHP's variables_order directive.
$_SESSION: An array of SESSION variables available in the current script.
move_uploaded_file() - Move the uploaded file to a new location; import_request_variables() - Import GET/POST/Cookie variables into the global scope; session_start() - Start a new session or reuse an existing session; getenv() - Get the value of an environment variable;$_ENV: An array of variables passed to the current script through the environment. These variables are imported from the PHP parser's runtime environment into PHP's global namespace. Many are provided by shells that support PHP running, and different systems are likely to run different kinds of shells, so a definitive list is impossible. Check your shell documentation for a list of defined environment variables. Other environment variables include CGI variables, regardless of whether PHP is running as a server module or a CGI processor.
$_COOKIE: Array of variables passed to the current script through HTTP Cookies. setcookie() - Send a cookie
$php_errormsg — Previous error message; $php_errormsg variable contains the latest error message generated by PHP. This variable is only available in the scope where the error occurred, and requires the track_errors configuration item to be turned on (the default is turned off). If the user defines an error handler (set_error_handler()) and returns <code>FALSE, $php_errormsg will be set.
<code><code>3166a3b1a9077b181d330448073b8cf92777bfbfa175241e88144701ea62c6b7 $HTTP_RAW_POST_DATA — Raw POST data. $HTTP_RAW_POST_DATA Contains the raw data submitted by POST. See always_populate_raw_post_data In general, use php://input instead of $HTTP_RAW_POST_DATA.$http_response_header — HTTP response header: $http_response_headerThe array is similar to the get_headers() function. When using an HTTP wrapper, $http_response_header will be populated with HTTP response headers. $http_response_header will be created in the local scope.
<code><span>c98c70a333d62bea105971178a0c74e7</span>$argc — 传递给脚本的参数数目:包含当运行于命令行下时传递给当前脚本的参数的数目。脚本的文件名总是作为参数传递给当前脚本,因此 $argc 的最小值为 1。这个变量仅在 register_argc_argv 打开时可用。
$argv — 传递给脚本的参数数组:包含当运行于命令行下时传递给当前脚本的参数的数组。第一个参数总是当前脚本的文件名,因此 $argv[0] 就是脚本文件名。这个变量仅在 register_argc_argv 打开时可用。
Exception是所有异常的基类。类摘要:
Exception { /* 属性 */ protectedstring$message ; protectedint$code ; protectedstring$file ; protectedint$line ; /* 方法 */ public__construct ([ string<code>$message = "" [, int<code>$code = 0 [, Exception<code>$previous = <code>NULL ]]] ) finalpublicstringgetMessage ( void ) finalpublicExceptiongetPrevious ( void ) finalpublicintgetCode ( void ) finalpublicstringgetFile ( void ) finalpublicintgetLine ( void ) finalpublicarraygetTrace ( void ) finalpublicstringgetTraceAsString ( void ) publicstring__toString ( void ) finalprivatevoid__clone ( void ) } 属性:message:异常消息内容;code:异常代码;file:抛出异常的文件名;line:抛出异常在该文件中的行号Exception::__construct — 异常构造函数
参数:message:抛出的异常消息内容。code:异常代码。previous:异常链中的前一个异常。Exception::getMessage — 获取异常消息内容
参数:此函数没有参数。Exception::getPrevious — 返回异常链中的前一个异常
参数:Exception::getPrevious — 返回异常链中的前一个异常。追踪异常,并循环打印。 <code><span>c061ab83ec7ae04cd75df121a850deb0getFile(), $e->getLine(), $e->getMessage(), $e- >getCode(), get_class($e));<br> } while($e = $e->getPrevious());<br> }<br>?></span>以上例程的输出类似于:
<span>/home/bjori/ex.php:8 Something happend (911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException] </span>
Exception::getCode — 获取异常代码
参数:此函数没有参数。Exception::getFile — 获取发生异常的程序文件名称
参数:此函数没有参数。Exception::getLine — 获取发生异常的代码在文件中的行号
Parameters: This function has no parameters.Exception::getTrace — Get exception tracing information
Parameters: This function has no parameters.Exception::getTraceAsString — Get exception tracing information of string type
Parameters: This function has no parameters.Exception::__toString — Convert exception object to string
Parameters: This function has no parameters.Exception::__clone — Exception clone
Parameters: This function has no parameters. There is no return value, and exceptions are not allowed to be cloned.ErrorException::__construct — Exception constructor
Parameters: message: The thrown exception message content. code: exception code. severity: The severity level of the exception. filename: The file name where the exception was thrown. lineno: The line number where the exception was thrown. previous: The previous exception in the exception chain.ErrorException::getSeverity — Get the severity of the exception
Parameters: This function has no parameters. <code><code>850f8ddcc0132d93fb705b652f61b84bgetSeverity();An interface to detect whether a class can be traversed using foreach. A basic abstract interface that cannot be implemented alone. Instead it must be implemented by the IteratorAggregate or Iterator interface. Built-in classes that implement this interface can use foreach for iteration without implementing the IteratorAggregate or Iterator interface. This is an internal engine interface that cannot be implemented in PHP scripts. The IteratorAggregate or Iterator interface can be used instead.
Traversable { } This interface does not have any methods. Its function is only as the basic interface for all traversable classes. Iterator interface:An interface that can iterate internally via its own external iterator or class.
IteratorextendsTraversable { /* Method */ abstractpublicmixedcurrent (void) abstractpublicscalarkey (void) abstractpublicvoidnext (void) abstractpublicvoidrewind (void) abstractpublicbooleanvalid (void) }Iterator::current — Returns the current element: no parameters, any type can be returned.
Iterator::key — Returns the key of the current element: no parameters, returns a scalar on success, returns null on failure.
Iterator::next — Move forward to the next element: no parameters, any returns will be ignored. This method is called after the foreach loop .
Iterator::rewind — Returns the first element of the iterator: this is the first method called when starting a foreach loop. It will not be called after the foreach loop . Without parameters, any returns will be ignored.
Iterator::valid — Check whether the current position is valid: This method is called after the Iterator::rewind() and Iterator::next() methods to check whether the current position is valid. Without parameters, the return will be converted to boolean. Returns <code>TRUE on success, or <code>FALSE on failure.
IteratorAggregate::getIterator — Gets an external iterator: no parameters, an instance of a class that implements the Iterator or Traversable interface.
ArrayAccess (array access) interface:An interface that provides the ability to access objects like arrays.
ArrayAccess { /* 方法 */ abstractpublicbooleanoffsetExists ( mixed<code>$offset ) abstractpublicmixedoffsetGet ( mixed<code>$offset ) abstractpublicvoidoffsetSet ( mixed<code>$offset , mixed<code>$value ) abstractpublicvoidoffsetUnset ( mixed<code>$offset ) }ArrayAccess::offsetExists — 检查一个偏移位置是否存在:对一个实现了 ArrayAccess 接口的对象使用 isset() 或 empty() 时,此方法将执行。当使用 empty() 并且仅当 ArrayAccess::offsetExists() 返回 <code>TRUE 时,ArrayAccess::offsetGet() 将被调用以检查是为否空。参数:offset 需要检查的偏移位置。成功时返回 <code>TRUE, 或者在失败时返回 <code>FALSE。如果一个非布尔型返回值被返回,将被转换为布尔型。
<code><span>ec0e9a591b9978a317f5a2e322a474c6</span>以上例程的输出类似于:
<span>Runs obj::offsetExists() string(17) "obj::offsetExists" bool(true) Runs obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get string(17) "obj::offsetExists" bool(true) </span>
ArrayAccess::offsetGet — 获取一个偏移位置的值:当检查一个偏移位置是否为 empty() 时,此方法被执行。
参数:offset 需要获取的偏移位置。返回值:可返回任何类型。ArrayAccess::offsetSet — 设置一个偏移位置的值:参数:offset 待设置的偏移位置。value 需要设置的值。没有返回值。
如果另一个值不可用,那么 <code>offset 参数将被设置为 <code>NULL。
ArrayAccess::offsetUnset — 复位一个偏移位置的值:当使用 (unset) 进行类型转换时,该方法不会被调用。
<code>参数:offset 待复位的偏移位置。没有返回值。
序列化接口:
Serializable::serialize — 对象的字符串表示。这个方法担当着对象析构器的角色。在此方法之后,__destruct() 方法将不会被调用。此函数没有参数,返回值:返回对象的字符串表示或者 <code>NULL 。
Serializable::unserialize — 构造对象。这个方法担当着对象构造器的角色。在此方法之后,__construct() 将不会被调用。参数:serialized 对象的字符串表示。
Closure::__construct — 用于禁止实例化的构造函数。这个方法仅用于禁止实例化一个 Closure 类的对象。这个类的对象的创建方法写在 匿名函数 页。此函数没有参数,没有返回值。
Closure::bind — 复制一个闭包,绑定指定的$this对象和类作用域。这个方法是 Closure::bindTo() 的静态版本。
Parameter: closure Anonymous function that needs to be bound. newthis requires an object bound to an anonymous function, or <code>NULL creates an unbound closure. newscope is the class scope you want to bind to the closure, or 'static' means unchanged. If an object is passed in, the type name of the object is used. Class scope is used to determine the visibility of private, protected methods of the $this object within the closure. Returns a new Closure object or <code>FALSE on failure
<code><code>107c48fee7460ef69f0d5547c8744550ifoo;
on failure
<code><span>34c13ada93c593594cff4343a8f13595val = $val;<br> }<br> function getClosure() {<br> //returns closure bound to this object and scope<br> return function() { return $this->val; };<br> }<br>}<br>$ob1 = new A(1);<br>$ob2 = new A(2);<br>$cl = $ob1->getClosure();<br>echo $cl(), "n"; //1<br>$cl = $cl->bindTo($ob2);<br>echo $cl(), "n"; //2<br>?></span> <code><strong>19cc855940e37978e2c9b188753e850fval = $val;<br> }<br> function getClosure() {<br> //returns closure bound to this object and scope<br> return function() { return $this->val; };<br> }<br>}$ob1 = new A(1);<br>$ob2 = new A(2);<br>$cl = $ob1->getClosure();<br>echo $cl() , "n"; //1<br>$cl = $cl->bindTo($ob2);<br>echo $cl(), "n"; //2<br>?> <span></span></strong> 17. Context options and parameters
The socket context option is available for all wrapper protocols that work over sockets, like tcp, http and ftp
.<code><span>36cd22448be314f919758b3ed42c29e9 array(<br> 'bindto' => '192.168.0.100:0',<br> ),<br>);<br>// connect to the internet using the '192.168.0.100' IP and port '7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => '192.168.0.100:7000',<br> ),<br>);<br>// connect to the internet using port '7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => '0:7000',<br> ),<br>);<br>// create the context...<br>$context = stream_context_create($opts);<br>// ...and use it to fetch the data<br>echo file_get_contents('http://www.example.com', false, $context);<br>?></span><code><span>455bb1750fd2e7fe8e392c285d408397 array( 'bindto' => '192.168.0.100:0',<br> ),<br>);<br>// connect to the internet using the '192.168.0.100' IP and port ' 7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => '192.168.0.100:7000',<br> ),<br>);<br>// connect to the internet using port '7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => ' 0:7000',<br> ),<br>);<br>// create the context...<br>$context = stream_context_create($opts);<br>// .. .and use it to fetch the data<br>echo file_get_contents('http://www.example.com', false, $context);<br>?><em></em></span> HTTP context options — A list of options for the HTTP context. Context options provided for the http:// and
https:// transport protocols. transports. Optional options:
FTP context options — FTP context option listing
SSL Context Options — List of SSL context options. ssl:// and tls:// transport protocol context options list. Options: Many.
CURL context options — CURL context options list. CURL context options are available when the CURL extension is compiled (via the --with-curlwrappers configure option). Optional options:
<code><span>edbedf38cd1f649f1f3f9c4abce0e960 'some content',<br> 'var2' => 'doh'<br> )<br>);<br>$opts = array('http' =><br> array(<br> 'method' => 'POST',<br> 'header' => 'Content-type: application/x-www-form-urlencoded',<br> 'content' => $postdata<br> )<br>);<br>$context = stream_context_create($opts);<br>$result = file_get_contents('http://example.com/submit.php', false, $context);<br>?></span>
Phar context options — List of Phar context options. phar:// Context options for the wrapper. Optional: <code>compressint One of Phar compression constants. <code>metadatamixed Phar metadata. See Phar::setMetadata().
Context parameter — Context parameter list. These parameters (parameters) can be set to the context returned by the function stream_context_set_params(). Parameters: <code>notificationcallable When an event occurs on a stream, the callable will be called.
18. Supported protocols and encapsulation protocols
file:// — access the local file system. Filesystem is the default wrapper protocol used by PHP and exposes the local filesystem. When a relative path is specified (a path that does not begin with /, , \, or a Windows drive letter) the path provided will be based on the current working directory. In many cases this is the directory where the script resides, unless it has been modified. When using the CLI, the directory defaults to the directory where the script is called.
In certain functions, such as fopen() and file_get_contents(), include_path is optionally searched, also as a relative path.
属性 | 支持 |
---|---|
受 allow_url_fopen 影响 | No |
允许读取 | Yes |
允许写入 | Yes |
允许添加 | Yes |
允许同时读和写 | Yes |
支持 stat() | Yes |
支持 unlink() | Yes |
支持 rename() | Yes |
支持 mkdir() | Yes |
支持 rmdir() | Yes |
http:// -- https:// — Access HTTP(s) URL. Allows read-only access to a file or resource via the HTTP 1.0 GET method. HTTP requests will be accompanied by a Host: header for compatibility with domain name-based virtual hosts. If the user_agent string is configured in your php.ini file or byte stream context, it will also be included in the request. The data stream allows reading the body of the resource, and the headers are stored in the $http_response_header variable.
If you need to know which URL the document resource comes from (after processing all redirects), you need to process the series of response headers returned by the data flow.
属性 | 支持 |
---|---|
受 allow_url_fopen 限制 | Yes |
允许读取 | Yes |
允许写入 | No |
允许添加 | No |
允许同时读和写 | N/A |
支持 stat() | No |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
属性 | PHP 4 | PHP 5 |
---|---|---|
受 allow_url_fopen 影响 | Yes | Yes |
允许读取 | Yes | Yes |
允许写入 | Yes (仅支持新文件) | Yes (新文件/启用 <code>overwrite 后已存在的文件) |
允许添加 | No | Yes |
允许同时读和写 | No | No |
支持 stat() | No | 自 5.0.0 起:仅仅 filesize()、 filetype()、 file_exists()、 is_file() 和 is_dir()。 自 PHP 5.1.0 起: filemtime()。 |
支持 unlink() | No | Yes |
支持 rename() | No | Yes |
支持 mkdir() | No | Yes |
支持 rmdir() | No | Yes |
Properties | PHP 4 | PHP 5 |
---|---|---|
Affected by allow_url_fopen | Yes | Yes |
Allow reading | Yes | Yes |
Allow writing | Yes (only supports new files) | Yes (new file/existing file after enabling <code>overwrite) |
Allow adding | No | Yes |
Allow simultaneous reading and writing | No | No |
Support stat() | No | Since 5.0.0: only filesize(), filetype(), file_exists(), is_file() and is_dir(). Since PHP 5.1.0: filemtime(). |
Support unlink() | No | Yes |
Support rename() | No | Yes |
Support mkdir() | No | Yes |
Support rmdir() | No | Yes |
php:// — Access various input/output streams (I/O streams). PHP provides a number of miscellaneous input/output (IO) streams that allow access to PHP's input and output streams, standard input, output, and error descriptors, in-memory, disk-backed temporary file streams, and filters that can operate on other read-write file resources. device.
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input of the PHP process or Output stream. The data stream references the copied file descriptor, so if you open php://stdin and then close it, you only close the copy and the real referenced <code>STDIN Not affected. Note that PHP's behavior in this area was buggy until PHP 5.2.1. It is recommended that you simply use the constants <code>STDIN, <code>STDOUT and <code>STDERR instead of opening these wrappers manually.
php://stdin is read-only, php://stdout and php://stderr are write-only.
php://input is a read-only stream that provides access to the requested raw data. In the case of POST requests, it is better to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on the specific php.ini command. Moreover, in this case $HTTP_RAW_POST_DATA is not populated by default, potentially requiring less memory than activating always_populate_raw_post_data. enctype="multipart/form-data" When php://input is invalid.
php://output is a write-only data stream that allows you to write to the output buffer in the same way as print and echo.
php://fd allows direct access to the specified file descriptor. For example, php://fd/3 refers to file descriptor 3.
php://memory and php://temp is a file-like wrapper data stream that allows reading and writing temporary data. The only difference between the two is that php://memory always stores data in memory, while php://temp will store data after the amount of memory reaches a predefined limit (default is 2MB) and stored in a temporary file. The temporary file location is determined in the same way as sys_get_temp_dir(). The memory limit of php://temp can be controlled by adding /maxmemory:NN. NN is the maximum data in bytes retained in memory. If the amount is exceeded, a temporary file will be used.
php://filter is a meta-wrapper designed for filtering applications when a data stream is opened. This is useful for all-in-one file functions like readfile(), file(), and file_get_contents(), where there is no opportunity to apply additional filters before the stream contents are read. The php://filter target uses the following parameters as part of its path. Composite filter chains can be specified on a path.
属性 | 支持 |
---|---|
首先于 allow_url_fopen | No |
首先于 allow_url_include | 仅 php://input、 php://stdin、 php://memory 和 php://temp。 |
允许读取 | 仅 php://stdin、 php://input、 php://fd、 php://memory 和 php://temp。 |
允许写入 | 仅 php://stdout、 php://stderr、 php://output、 php://fd、 php://memory 和php://temp。 |
允许追加 | 仅 php://stdout、 php://stderr、 php://output、 php://fd、 php://memory 和php://temp(等于写入) |
允许同时读写 | 仅 php://fd、 php://memory 和 php://temp。 |
支持 stat() | 仅 php://memory 和 php://temp。 |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
仅仅支持 stream_select() | php://stdin、 php://stdout、 php://stderr、 php://fd 和 php://temp。 |
zlib:// -- bzip2:// -- zip:// — Compressed stream. zlib: PHP 4.0.4 - PHP 4.2.3 (only supports systems with fopencookie)
compress.zlib:// and compress.bzip2:// PHP 4.3.0 and above
zlib: functions like gzopen(), but its data stream can also be used by fread() and other file system functions. This is deprecated since PHP 4.3.0 as it will be confused with other file names with ":" characters; please use compress.zlib:// instead.
compress.zlib://, compress.bzip2:// are equal to gzopen() and bzopen(). And can be used on systems that don't support fopencookie.
ZIP extension registered zip: encapsulation protocol. Optional options
data:// — data (RFC 2397). Usage: data://text/plain;base64,
属性 | 支持 |
---|---|
受限于 allow_url_fopen | No |
受限于 allow_url_include | Yes |
允许读取 | Yes |
允许写入 | No |
允许追加 | No |
允许同时读写 | No |
支持 stat() | No |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
Print the contents of data://:
<code><code>a20f89f12e38dfa151b344490b85d79bbd7cae4f186bbd94591c5d96d7549097 Get media type: <code><span>6711ab814b25f342be240325df996ddf</span> <code><p>8937c3807a0f92a5ee3172059bac6c7d<span></span></p> glob:// — Find matching file path patterns. Usage: glob://Attributes | Supported |
---|---|
Subject to allow_url_fopen | No |
Subject to allow_url_include | No |
Allow reading | No |
Allow writing | No |
Allow appending | No |
Allow simultaneous reading and writing | No |
Support stat() | No |
Support unlink() | No |