使用PHP cURL将JSON数组从一台机器发送到另一台机器-如何从目标IP地址构造目标URL
我在VMWare工作站中安装了两台虚拟机,它们都有不同的IP地址。我想将一个JSON数组从一个虚拟机发送到另一个虚拟机。因此,我使用PHP cURL库发送数据,并遵循了以下步骤。下面是我的代码片段。为了解决这个问题,我们假设使用PHP cURL将JSON数组从一台机器发送到另一台机器-如何从目标IP地址构造目标URL,php,json,curl,networking,wireshark,Php,Json,Curl,Networking,Wireshark,我在VMWare工作站中安装了两台虚拟机,它们都有不同的IP地址。我想将一个JSON数组从一个虚拟机发送到另一个虚拟机。因此,我使用PHP cURL库发送数据,并遵循了以下步骤。下面是我的代码片段。为了解决这个问题,我们假设AAA.BBB.CCC.DDD是我要发送JSON数据的目标主机的IP地址 我有两个问题: 我只知道目标主机的IP地址。目标计算机上确实有一个XAMPP本地服务器。现在我如何为目的地构建URL?请看下面片段中的第一行,我是否正确创建了URL 2.当我在本地主机上执行此脚本并同时
AAA.BBB.CCC.DDD
是我要发送JSON数据的目标主机的IP地址
我有两个问题:
<?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://localhost/curl-req.php
是您自己的本地服务器中的目标。我需要在两台不同的机器之间发送JSON数据。这是一个简单的问题,您只需复制更改url即可。你给我写信息的时间比更改url的时间长。