从另一个域调用另一个PHP并获得结果

时间:2016-05-27 09:43:42

标签: php wordpress post

我试图从另一个php传递数据到它并获取返回值。这两个php在不同的域名上。

首先是php:

    $url = 'http://myweb.com/custom-php/createCat.php';
    $data = array('name' => $name);

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    echo $result;

第二个php(它在Wordpress网站上):

    header("Access-Control-Allow-Origin: *");
    require('../wp-load.php');

    $name = $_REQUEST['name'];
    echo $name;
    if(isset($name))
    {
        echo wp_create_category($name,0);
    }
    else
    {
        echo false;
    }

我收到以下错误:

file_get_contents(http://myweb.com/custom-php/createCat.php):无法打开流:HTTP请求失败! HTTP / 1.1 500内部服务器错误

但如果我通过http://myweb.com/custom-php/createCat.php?name=test访问它,它就可以了。

2 个答案:

答案 0 :(得分:1)

请求错误可能是因为 allow_url_fopen PHP.ini指令在远程网址中设置为关闭

所以另一种选择可能是使用CURL:

<?php
$url = 'http://myweb.com/custom-php/createCat.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$result= curl_exec($curl);
curl_close($curl);
?>

回答评论&#39; 如何发送我需要的数据(带有文字的变量)&#39;

使用CURLOPT_POSTFIELDS:

curl_setopt($curl, CURLOPT_POSTFIELDS, "name=test&var=" . urlencode($someText));

答案 1 :(得分:0)

当您访问该网址时,您会收到请求。 你应该在你的php中做同样的事情:

  +-----------------------------------------------------------------------+
  | Start_time          | End_time            | Duration  | Event | Agent |
  +-----------------------------------------------------------------------+
  | 2016-05-26 12:50:10 | 2016-05-26 12:52:54 | 00:02:44  | break | user1 |
  | 2016-05-26 12:52:55 | 2016-05-26 12:56:45 | 00:03:50  | break | user1 |
*2| 2016-05-26 12:56:53 | 2016-05-26 13:13:11 | 00:16:18  | break | user1 |
  | 2016-05-26 13:13:12 | 2016-05-26 13:25:25 | 00:12:13  | break | user1 |
  | 2016-05-26 13:25:26 | 2016-05-26 13:26:23 | 00:00:57  | break | user1 |
  | 2016-05-26 13:26:24 | 2016-05-26 13:27:37 | 00:01:13  | break | user1 |
  | 2016-05-26 14:26:50 | 2016-05-26 14:30:57 | 00:04:07  | break | user1 |
  | 2016-05-26 14:30:58 | 2016-05-26 14:46:08 | 00:15:10  | break | user1 |

此外,您需要在使用之前检查$url = 'http://myweb.com/custom-php/createCat.php'; $data = array('name' => $name); $result = file_get_contents($url . '?' . http_build_query($data)); echo $result; 键是否已设置:

$_REQUEST