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); ?> 
3
  • Possible duplicate of How to get useful error messages in PHP? Commented Feb 27, 2017 at 21:11
  • (Obvious extra quote error on the $text = line) Commented Feb 27, 2017 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) Commented Feb 27, 2017 at 21:28

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.