1

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. Sorry for my first socket confusing php code :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);


?>
Cafekev
  • 11
  • 1
  • 5
  • Possible duplicate of [How to get useful error messages in PHP?](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) – Shira Feb 27 '17 at 21:11
  • (Obvious extra quote error on the `$text = ` line) – Shira Feb 27 '17 at 21:12
  • Also IIRC HTTP headers section is separated from body by double new-line (i.e. an additional empty line finished with a new line) – SergGr Feb 27 '17 at 21:28

1 Answers1

4

Don't use raw sockets to make HTTP requests. There are much better libraries for that, like 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.)