Home > Article > Backend Development > Introduction to file_get_contents and curl_get_contents in php_PHP tutorial
Introduction to file_get_contents and curl_get_contents in php. Friends in need can refer to it.
Share an actually used function:
The file_get_contents() function is the preferred method for reading the contents of a file into a string. If supported by the operating system, memory mapping technology is also used to enhance performance.
/*Much more stable than file_get_contents! $timeout is the timeout time, the unit is seconds, and the default is 1s. */
代码如下 | 复制代码 |
function curl_get_contents($url,$timeout=1) { $curlHandle = curl_init(); curl_setopt( $curlHandle , CURLOPT_URL, $url ); curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout ); $result = curl_exec( $curlHandle ); curl_close( $curlHandle ); return $result; } $hx = curl_get_contents('http://www.bKjia.c0m/'); |
I believe friends who have used the file_get_contents function know that when the obtained $url cannot be accessed, it will cause the page to wait for a long time, and even cause the PHP process to occupy 100% of the CPU, so this function was born.
Through the default_socket_timeout setting in php.ini, the default timeout is default_socket_timeout = 60
The code is as follows | Copy code | ||||
max_execution_time = 30
|
Can be set in the following three ways
代码如下 | 复制代码 |
1 直接在php.ini中修改 default_socket_timeout =120 |
The code is as follows | Copy code |
1 Modify directly in php.ini default_socket_timeout =120 2 ini_set('default_socket_timeout', 120); 3 $strm = stream_context_create(array( 'http' => array( 'timeout' => 120 ) ) ); |
Some common sense introduction to curl
The reason for retaining the original file_get_contents function is that when reading local files, it is obviously more appropriate to use the native file_get_contents.
Another optimization of file_get_contnets from Zhang Yan, please see:
First, use the top command to view the php-cgi process with high CPU usage.
The code is as follows | Copy code |
top - 10:34:18 up 724 days, 21:01, 3 users, load average: 17.86, 11.16, 7.69 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 找其中一个 CPU 100% 的 php-cgi 进程的 PID,用以下命令跟踪一下: strace -p 10747 |
如果屏幕显示:
代码如下
|
复制代码
|
||||
select(7, [6], [6], [], {15, 0}) = 1 (out [6], left {15, 0})
|
同样是设置超时时间来解决这个问题。如果没装curl,就必须得用这个方式了。