2010-09-01 49 views
2

如何从完全不同的服务器读取文件的内容,然后显示内容。我将稍后更改代码以适当方式使用返回的信息。使用php脚本从其他网站读取文件

+0

这个文件以某种方式保护或者你可以做一个HTTP请求呢? – Jage 2010-09-01 17:44:33

回答

4

您可以使用file_get_contentscURL

下面的例子下载google.com的主页的HTML并在屏幕上显示它。

的file_get_contents方式:

$data = file_get_contents("http://www.google.com/"); 
echo "<pre>" . $data . "</pre>"; 

卷曲方式:

function get_web_page($url) 
{ 
    $options = array(
     CURLOPT_RETURNTRANSFER => true,  // return web page 
     CURLOPT_HEADER   => false, // don't return headers 
     CURLOPT_FOLLOWLOCATION => true,  // follow redirects 
     CURLOPT_ENCODING  => "",  // handle all encodings 
     CURLOPT_AUTOREFERER => true,  // set referer on redirect 
     CURLOPT_CONNECTTIMEOUT => 120,  // timeout on connect 
     CURLOPT_TIMEOUT  => 120,  // timeout on response 
     CURLOPT_MAXREDIRS  => 10,  // stop after 10 redirects 
    ); 

    $ch  = curl_init($url); 
    curl_setopt_array($ch, $options); 
    $content = curl_exec($ch); 
    $err  = curl_errno($ch); 
    $errmsg = curl_error($ch); 
    $header = curl_getinfo($ch); 
    curl_close($ch); 

    $header['errno'] = $err; 
    $header['errmsg'] = $errmsg; 
    $header['content'] = $content; 
    return $header; 
} 

//Now get the webpage 
$data = get_web_page("https://www.google.com/"); 

//Display the data (optional) 
echo "<pre>" . $data['content'] . "</pre>"; 
0

您可以使用卷曲

 
$ch = curl_init("http://www.google.com"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$content_of_page = curl_exec($ch); 
curl_close($ch); 
1

有几种方法我建议:

HTTP:
如果可能的话,使用PHP内置的文件流功能(如file_get_contents())或cURL通过正常HTTP requests到从服务器下载文件。但是,如果你想下载一个PHP文件的源代码,这将不起作用(你会得到它的输出)。举个例子:

<?php 
// Most basic HTTP request 
$file = file_get_contents('http://www.example.com/path/to/file'); 
// HTTP request with a username and password 
$file = file_get_contents('http://user:[email protected]/path/to/file'); 
// HTTPS request 
$file = file_get_contents('https://www.example.com/path/to/file'); 

SSH:
如果您已经安装了SSH2扩展名,您必须将服务器的SSH访问,你可能想通过SFTP(SSH文件传输协议)来下载文件:

<?php 
// Use the SFTP stream wrapper to download files through SFTP: 
$file = file_get_contents('ssh2.sftp://user:[email protected]/path/to/file'); 

FTP:
如果服务器有你要访问的FTP服务器,你可能想使用FTPFTPS(安全FTP,如果支持的话)来下载文件:

<?php 
// Use the FTP stream wrapper to download files through FTP or SFTP 

// Anonymous FTP: 
$file = file_get_contents('ftp://ftp.example.com/path/to/file'); 

// FTP with username and password: 
$file = file_get_contents('ftp://user:[email protected]/path/to/file'); 

// FTPS with username and password: 
$file = file_get_contents('ftps://user:[email protected]/path/to/file');