Home > Software engineering >  Send POST request with PHP
Send POST request with PHP

Time:10-12

For a translation tool i want to use, i need to send my requests per POST. I never done anything like this, and the documentation doesnt mean much to me (it isn't php specific documentation, and not sure how to implement this in php)

The example in the docu would be:

POST /v2/translate HTTP/1.0
Host: api.deepl.com
Accept: */*
User-Agent: YourApp
Content-Type: application/x-www-form-urlencoded
Content-Length: 91

auth_key=MYKEY&text=this is a test&target_lang=de

In another post on stackoverflow i found this solution to use POST in php, So my main issue is, i'm not sure where everything goes I asume Host goes into url and that header is correct. but thats as far i could get with my limited skill

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

any help would be greatly appreciated

CodePudding user response:

You can do a POST request using curl in PHP.

// initiate the curl request
$request = curl_init();

curl_setopt($request, CURLOPT_URL,"http://www.otherDomain.com/getdata");
curl_setopt($request, CURLOPT_POST, 1);
curl_setopt($request, CURLOPT_POSTFIELDS,
        "var1=value1&var2=value2");

// catch the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($request);

curl_close ($request);

// do processing for the $response
  • Related