PHP 文件和 fopen 函数不起作用


php file and fopen functions not working

我正在尝试学习如何创建网络机器人,我正在阅读迈克尔·施伦克(Michael Schrenk)的一本名为《网络机器人,蜘蛛和屏幕抓取器》的书。在书中,他给出了下载网页的基本机器人的示例代码。我已经完全按照书中的代码复制了代码(没有评论):

<? 
$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
$downloaded_page_array = file($target); 
for($xx=0; $xx<count($downloaded_page_array); $xx++) 
echo $downloaded_page_array[$xx]; 
?>

我把这段代码放在一个php文件中,然后上传到我的网站。但是,当我在浏览器中导航到它时,没有任何反应。它只是加载一个空白页。没有内容。

早些时候我尝试了作者提供的另一个片段,同样,这个片段完全是从书中复制的,只是有了这个,我并没有真正得到一个空白页,页面只是试图加载,直到它最终超时。从未获得正确的内容:

$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
$file_handle = fopen($target, "r");
while (!feof($file_handle))
echo fgets($file_handle, 4096);
fclose($file_handle);

我已经检查了 URL 以确保该文件存在并且确实存在。我不知道为什么这行不通。我已经通读了如何使用文件();和 fopen();PHP 中的函数,但据我所知,它们都被正确使用。我在这里做错了什么?

通过fopen()访问URL是一个坏主意。它要求您在PHP配置中启用allow_url_fopen,这为大量漏洞打开了大门(主机出于某种原因禁用它)。

尝试改用cURL函数:它们将为您提供更大的灵活性和控制力。PHP 文档为您提供了一些很好的示例。

不是fgets($file_handle, 4096)而是fread($file_handle, 4096) ;

$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
$file_handle = fopen($target, "r");
while (!feof($file_handle))
echo  fread($file_handle, 4096);
fclose($file_handle);

然后,如果您想从提取的文本创建一个新文件:

  // extracting text operation
$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
$file_handle = fopen($target, "r");
$getText =  fread($file_handle, 4096);
fclose($file_handle);
// writing file operation
$writeHandle = fopen ("folder/text.txt","w"); // file will be created if not existed
$writeFile = fwrite($writeHandle,$getText );
fclose($writeHandle );

首先,您应该error_reporting(E_ALL); ini_set('display_errors', '1');脚本中,以便在脚本中显示错误,正如AbraCadaver在他的评论中提到的那样。

原因可能是您的主机上禁用了allow_url_fopen

此选项启用 URL 感知的 fopen 包装器,这些包装器允许访问 URL 对象(如文件)。默认包装器用于使用 ftp 或 http 协议访问远程文件,一些扩展(如 zlib)可能会注册额外的包装器。

请参阅:http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

您可以通过以下方式进行检查:

var_dump(ini_get('allow_url_fopen'));

脚本需要true才能正确运行。

如果allow_url_fopen不是true1您可以尝试使用file_get_contents()来加载网址。

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

参见:http://php.net/manual/en/function.file-get-contents.php