简体   繁体   English

PHP中的HTTP PUT请求

[英]HTTP PUT Request in PHP

How to make a PUT HTTP REQUEST to ( http://sample.com:8888/folder ) with a Random-Header and REQUEST-BODY with JSON String {"key": "la09823", "content": "jfkdls"} HTTP status code 200 OK would be nice. 如何使用JSON字符串{“ key”:“ la09823”,“ content”:“ jfkdls”}使带有Random-Header和REQUEST-BODY的PUT HTTP REQUEST到( http://sample.com:8888/folder ) HTTP状态码200 OK会很好。 Sorry for my first socket confusing php code :D<3. 对不起,我的第一个套接字令人困惑的php代码:D <3。 thx 谢谢

<?php
$json = "\{\"key\": \"la09823\", \"content\": \"jfkdls\"}";
$hostname="http://sample.com/folder");
$port = 8888;
$timeout = 50;
$socket = socket_create(AF_INET, SOCK_STREAM, tcp);
socket_connect($socket, $hostname, $port);
$text = "PUT /folder/json.txt" HTTP/1.1\n";
$text .= "Host: WhoIAm.com\n";
$text .= "Content-Type: application/json\n";
$text .= "Content-length: " . strlen($json) . "\n";
$finish = $text + $json;
socket_write($socket, $finish, 0);
socket_close($socket);


?>

Don't use raw sockets to make HTTP requests. 不要使用原始套接字发出HTTP请求。 There are much better libraries for that, like cURL: 有很多更好的库,例如cURL:

<?php

$data = [
    "key" => "la09823",
    "content" => "jfkdls",
];

$req = curl_init();
curl_setopt_array($req, [
    CURLOPT_URL            => "https://httpbin.org/put",
    CURLOPT_CUSTOMREQUEST  => "PUT",
    CURLOPT_POSTFIELDS     => json_encode($data),
    CURLOPT_HTTPHEADER     => [ "Content-Type" => "application/json" ],
    CURLOPT_RETURNTRANSFER => true,
]);

$response = curl_exec($req);
print_r($response);

(I've used httpbin for testing this code. Obviously, you'll want to use a different URL here.) (我已经使用httpbin来测试此代码。显然,您将在此处使用其他URL。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM