使用CURL向本地文件发送HTTP请求

6

你好,我需要发送HTTP请求到本地文件,使用的是文件名本身而不是完整的HTTP路径。例如:

    <?php
$url = 'http://localhost/te/fe.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
?>

我需要做这个才能变成这样。
<?php
$url = 'fe.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
?>

当我尝试做第二个例子时,它没有任何反应。是否有使用Curl或其他方法的解决方案?谢谢。

3个回答

5
自 PHP 5.4.0 起,CLI SAPI 提供了一个内置的 Web 服务器。您可以简单地提供您的 fe.php 脚本所在目录并运行您的脚本,然后使用 curl 请求该服务。
从命令行切换到目录并运行:
cd /path/to/script/te/
php -S localhost:8000

现在修改您的代码,使其连接到8000端口:
<?php
$url = 'http://localhost:8000/fe.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
?>

现在运行你的脚本,例如:
php -f /path/to/curl/script.php

0
<?php
$url = 'fe.php';
// The submitted form data, encoded as query-string-style
// name-value pairs

-> USE below <-
$varArr = array(
'monkey' => 'uncle',
'rhino' => 'aunt'
);
$body = http_build_query($varArr); // this will build query string

-> INSTED OF below <-
$body = 'monkey=uncle&rhino=aunt';

$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
?>

0

我已经成功使用file://调用本地URL。不幸的是,我希望能够使用相对路径,以便更容易从项目文件中维护,但你可以这样做:

在这里,我假设我正在使用我的WAMP,但解决方案也适用于服务器: http://te/fe.php 将转换为(假设它在wamp中): file:///c:/wamp/www/te/fe.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接