使用PHP cURL从一台机器发送JSON数组到另一台机器 - 如何从目标IP地址构造目标URL
我在VMWare工作站中安装了两台虚拟机器,它们都有不同的IP地址。我想从一个虚拟机发送JSON数组到另一个虚拟机。所以我使用PHP cURL库来发送数据,并且已经遵循this tutorial。以下是我的代码片段。为了这个问题,我们假设AAA.BBB.CCC.DDD
是我想要发送JSON数据的目标主机的IP地址。使用PHP cURL从一台机器发送JSON数组到另一台机器 - 如何从目标IP地址构造目标URL
我有两个问题:
- 我所知道的是目标主机的IP地址。该目标计算机上有一个XAMPP本地服务器。现在我该如何构建目的地的URL?请参阅下面的代码片段中的第一行,我是否正确填写了网址?
2.当我在本地主机上执行此脚本,同时运行Wireshark时,三个数据包似乎被发送到特定的目标IP地址。但我不知道如何接收目标机器中的特定JSON数据?如果有人能够给我指导一个教程或给我一个提示,这将是非常棒的吗?
<?php
$url = "http://AAA.BBB.CCC.DDD"; // AAA.BBB.CCC.DDD is replaced by the IP address of destination host.
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'name' => 'Jeremy',
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
我的简单测试例如:
<?php
$url = 'http://localhost/curl-req.php';
$data = array("name" => "Heniek", "age" => "125", "rozmiar" => "M");
$data = json_encode($data);
// Send post data Json format
echo CurlSendPostJson($url,$data);
// send curl post
function CurlSendPostJson($url='http://localhost/curl-req.php',$datajson){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $datajson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($datajson)));
//curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
return $result = curl_exec($ch);
}
?>
<?php
// save belove to: curl-req.php
// GET JSON CONTENT FROM CURL
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
//echo $json = json_decode($jsonStr);
if (!empty($jsonStr)) {
echo $jsonStr;
}
// POST DATA FROM CURL
if (empty($jsonStr)) {
echo serialize($_POST);
}
// GET DATA FROM CURL
if (!empty($_GET)) {
echo serialize($_GET);
}
?>
'的http://本地主机/卷曲req.php'是您自己的本地服务器中的目的地。我需要在两台不同的机器之间发送JSON数据。 – Sie
更改网址,因为你希望男人!!!! – 2017-04-06 08:52:07
这是一个简单的问题,您只需复制更改网址即可。你更长时间写信给我,而不是更改网址。 – 2017-04-06 08:55:49
http://php.net/manual/en/function.gethostbyaddr.php – 2017-04-06 07:15:40