Home Backend Development PHP Tutorial 执行、获取远程代码返回:file_get_contents 超时处理的问题详解_PHP

执行、获取远程代码返回:file_get_contents 超时处理的问题详解_PHP

Jun 01, 2016 pm 12:05 PM
file_get_contents Timeout processing

天气终于晴了,但问题来了。在实现两个站点间用户数据同步,当使用php函数 file_get_contents抓取执行远程页面时,如果连接超时将会输出一个Fatal Error或相当的慢,结果导致下面的代码不能运行。先了解一下PHP file_get_contents() 函数
定义和用法
file_get_contents() 函数把整个文件读入一个字符串中。
和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。
file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。
语法
file_get_contents(path,include_path,context,start,max_length)参数 描述
path 必需。规定要读取的文件。
include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。
context 可选。规定文件句柄的环境。
context 是一套可以修改流的行为的选项。若使用 null,则忽略。
start 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。
max_length 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。
说明
对 context 的支持是 PHP 5.0.0 添加的。
针对超时或页面过慢,一般可采取两个解决方案:

一. 利用file_get_contents()第三个参数
复制代码 代码如下:
$url = "http://zhoz.com/zhoz.php";     
$ctx = stream_context_create(array(     
‘http' => array(‘timeout' => 10)     
    )     
    );     
$result = @file_get_contents($url, 0, $ctx);     
if($result){     
        var_dump($result);     
    }else{     
echo " Buffer is empty";     
    }     
?>  

此方法1,我经测试在本地反映良好,但如果在外网测试(环境:中国→美国服务器间)基本都是超时的情况。
测试了TimeOut基本没有用了,建议以下方式

二. 使用curl扩展库
复制代码 代码如下:
$url = "http://zhoz.com/zhoz.php";     
try {     
echo date(‘Y-m-d h:i:s');     
echo "";     
//$buffer = file_get_contents($url);   
$buffer = zhoz_get_contents($url);     
echo date(‘Y-m-d h:i:s');     
if(emptyempty($buffer)) {     
echo " Buffer is empty";     
        } else {     
echo " Buffer is not empty";     
        }     
    } catch(Exception $e) {     
echo "error ";     
    }     
function zhoz_get_contents($url, $second = 5) {     
$ch = curl_init();     
        curl_setopt($ch,CURLOPT_URL,$url);     
        curl_setopt($ch,CURLOPT_HEADER,0);     
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);     
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);     
$content = curl_exec($ch);     
        curl_close($ch);     
return $content;     
    }     
?>

综述,根据系统环境来选择到底应用哪种方法:
复制代码 代码如下:
function vita_get_url_content($url) {  
if(function_exists(‘file_get_contents')) {  
$file_contents = file_get_contents($url);  
} else {  
$ch = curl_init();  
$timeout = 5;  
curl_setopt ($ch, CURLOPT_URL, $url);  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
$file_contents = curl_exec($ch);  
curl_close($ch);  
}  
return $file_contents;  
}  
?> 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve PHP Warning: file_get_contents(): Filename cannot be empty How to solve PHP Warning: file_get_contents(): Filename cannot be empty Aug 18, 2023 pm 07:30 PM

How to solve PHPWarning: file_get_contents(): Filenamecannotbeempty In the process of PHP development, we often encounter this error message: PHPWarning: file_get_contents(): Filenamecannotbeempty. This error usually occurs when using the file_get_contents function

如何解决PHP Warning: file_get_contents(): failed to open stream: HTTP request failed 如何解决PHP Warning: file_get_contents(): failed to open stream: HTTP request failed Aug 18, 2023 pm 11:34 PM

How to solve PHPWarning:file_get_contents():failedtoopenstream:HTTPrequestfailed During PHP development, we often encounter situations where HTTP requests are initiated to remote servers through the file_get_contents function. However, sometimes we encounter a common error message: PHPWarning: file_get_c

PHP's file_get_contents() function: How to read contents from a file PHP's file_get_contents() function: How to read contents from a file Nov 04, 2023 pm 01:43 PM

PHP's file_get_contents() function: How to read content from a file, specific code example In PHP, file_get_contents() is a very useful function that allows us to read content from a file. Whether reading a text file or reading content from a remote URL, this function can easily complete the task. Syntax The basic syntax of this function is as follows: stringfile_get_contents(string$f

Detailed explanation of PHP file caching functions: file caching processing methods of file_get_contents, file_put_contents, unlink and other functions Detailed explanation of PHP file caching functions: file caching processing methods of file_get_contents, file_put_contents, unlink and other functions Nov 18, 2023 am 09:37 AM

Detailed explanation of PHP file caching functions: file caching processing methods of file_get_contents, file_put_contents, unlink and other functions, which require specific code examples. In web development, we often need to read data from files or write data to files. Moreover, in some cases, we need to cache the contents of files to avoid frequent file read and write operations, thus improving performance. In PHP, there are several commonly used functions that can help us implement file caching, including

PHP function introduction—file_get_contents(): Read the contents of the URL into a string PHP function introduction—file_get_contents(): Read the contents of the URL into a string Jul 24, 2023 pm 02:32 PM

PHP function introduction—file_get_contents(): Read the contents of the URL into a string. In web development, it is often necessary to obtain data from a remote server or read a remote file. PHP provides a very powerful function file_get_contents(), which can conveniently read the contents of a URL and save it to a string. This article will introduce the usage of file_get_contents() function and give some code examples to help readers better

Error handling in Golang: How to handle timeout errors? Error handling in Golang: How to handle timeout errors? Aug 07, 2023 pm 01:17 PM

Error handling in Golang: How to handle timeout errors? Introduction: When writing programs that use network requests or perform time-consuming operations, we often encounter timeouts. These timeout errors may be caused by network connection issues, processing large data volumes, or external service failures. In Golang, we can use some techniques to handle timeout errors and ensure the robustness and reliability of the program. This article will introduce some common timeout error handling methods and give corresponding code examples. 1. Use the time package Go

PHP and WebDriver Extensions: How to Handle Web Page Load Timeouts and Failures PHP and WebDriver Extensions: How to Handle Web Page Load Timeouts and Failures Jul 08, 2023 pm 12:21 PM

PHP and WebDriver Extensions: How to Handle Web Page Load Timeouts and Failures Introduction: Network issues are one of the common challenges when using web automation testing tools. When we use the PHP language combined with the WebDriver extension for automated testing, we often encounter web page loading timeouts or failures. In this article, I'll explain how to use PHP and the WebDriver extension to handle these problems, and provide some code examples. 1. Set the web page loading timeout. In automated testing, we need to

How to read file contents using file_get_contents function in PHP How to read file contents using file_get_contents function in PHP Jun 26, 2023 pm 12:01 PM

In PHP, we often need to read data from files. In this case, we can use the file_get_contents function. This function can simply read everything from a file and return it as a string. This is very useful in many scenarios, such as reading configuration files, reading log files, etc. In this article, we will explain how to read file contents using the file_get_contents function in PHP. Step 1: Open the file using file

See all articles