📅  最后修改于: 2023-12-03 15:03:41.005000             🧑  作者: Mango
在 PHP 中,我们可以使用 file_get_contents()
函数从另一台服务器获取文件。该函数可以读取一个 URL 或本地文件的内容,并返回一个字符串。
string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
$filename
: 要读取的文件的 URL 或本地文件名。$use_include_path
: 是否使用 include_path 查找文件。默认为 false
。$context
: 一个与上下文关联的流参数。可以使用 stream_context_create()
函数创建。$offset
: 读取文件开始的偏移量。默认为 -1
,即从文件开始读取。$maxlen
: 要读取的最大字节数。默认为 NULL
,即读取整个文件。以下示例演示了如何从远程服务器获取一个 PHP 文件的内容。
$url = 'http://example.com/file.php';
$content = file_get_contents($url);
echo $content;
如果需要传递参数,可以使用 http_build_query()
函数将参数编码为 URL 字符串,并拼接到 URL 后面。
$url = 'http://example.com/file.php?' . http_build_query(['id' => 1, 'name' => 'John']);
$content = file_get_contents($url);
echo $content;
file_get_contents()
函数的默认超时时间为 60 秒,可以使用 stream_context_create()
函数设置超时时间。file_get_contents()
函数,可以使用 curl
扩展代替。