【发布时间】:2018-06-25 22:15:30
【问题描述】:
我想在我的脚本中使用 fsockopen 将一些发布数据传递给我服务器上的另一个 php 脚本。我已经对其进行了测试,除非您的网站上有路由,否则实现起来非常简单。
这是我的工作示例(在服务器上没有路由):
socket_post.php
<?php
header('Content-type: text/plain');
$fp = fsockopen('example.com', 80, $errno, $errstr, 30);
$vars = array(
'filename' => 'article.txt',
'data' => 'Hello world'
);
$content = http_build_query($vars);
fwrite($fp, "POST /sockets/receive_data.php HTTP/1.1\r\n");
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
//fclose($fp); // Closes socket immediately without waiting for response
//echo "Done\r\n";
while (!feof($fp)) {
echo fgets($fp, 1024);
}
receive_data.php
<?php
extract($_POST);
sleep(10);
file_put_contents($filename, $data);
因此,它在我的测试服务器上运行良好,但是当我尝试使用 OpenCart CMS 实现此脚本时,由于 OpenCart 的控制器路由而失败。
这是 OpenCart 脚本的一个版本:
socket_post.php
<?php
class ControllerSocketsSocketPost extends Controller {
public function index() {
header('Content-type: text/plain');
$fp = fsockopen("example.com", 80, $errno, $errstr, 30);
$vars = array(
'filename' => 'article.txt',
'data' => 'Hello world'
);
$content = http_build_query($vars);
fwrite($fp, "POST https://example.com/index.php?route=sockets/receive_data HTTP/1.1\r\n"); // !!!THE MAIN PROBLEM HERE!!!
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
//fclose($fp); // Closes socket immediately without waiting for response
//echo 'Done';
while (!feof($fp)) {
echo fgets($fp, 1024);
}
}
}
receive_data.php
<?php
class ControllerSocketsReceiveData extends Controller {
public function index() {
extract($this->request->post);
sleep(10);
file_put_contents($filename, $data);
}
}
因此,它应该在同一目录中创建"article.txt" 文件并在页面上呈现HTTP/1.1 200 OK 状态,但由于路由和html 输出<p>The document has moved <a href="https://www.example.com/index.php?route=sockets/receive_data">here</a>.</p>,它会获得HTTP/1.1 302 Found 状态。
在这种情况下如何处理 OpenCart 的路由?任何建议将不胜感激,谢谢!
【问题讨论】:
-
你在用 apache 做 opencart 吗?
-
是的,Apache 2.2.31,PHP 5.3.29
-
在POST URL中直接使用php文件路径即/server/xxx/filename.php
-
我刚刚将其更改为
fwrite($fp, "POST https://example.com/catalog/controller/sockets/receive_data.php HTTP/1.1\r\n");,但结果与以前相同。 -
那不行,你为什么要在这里扩展控制器?将这个 index.php 代码放在服务器根目录 (server_root/recieve.php) 内的一个简单 php 文件中,然后 POST 到 example.com/recieve.php
标签: php .htaccess sockets post fsockopen