Trying to send a POST request using php, No matter what i do i get “HTTP ERROR 500”

耗尽温柔 提交于 2021-02-05 12:02:56

问题


To make an HTTP request, someone suggested I try using PHP and gave me a piece of code to work on:

$url = 'https://example.com/dashboard/api';
$data = array('to' => PHONE_NUMBER, 'from' => SENDER_ID, 'message' => TEXT, 'email' => EMAIL, 'api_secret' => SECRET, 'unicode' => BOOLEAN, 'id' => IDENTIFIER);

$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);

So I took the code, edited the fields that I needed to, pasted it into a .php file, uploaded on my web server (running PHP 5.6) and then while trying to run the .php file, I get HTTP ERROR 500.

I'm a complete newbie to all this and I'm not even sure if I am doing everything correctly.


回答1:


      $url = 'https://domainname.com/dashboard/api';
      $params = array('to' => PHONE_NUMBER, 'from' => SENDER_ID, 'message' => TEXT, 'email' => EMAIL, 'api_secret' => SECRET, 'unicode' => BOOLEAN, 'id' => IDENTIFIER);      
      $query_content = http_build_query($params);
      $context = stream_context_create([
          'http' => [
              'header'  => [
                   'Content-type: application/x-www-form-urlencoded',
                   'Content-Length: ' . strlen($query_content)
              ],
          'method'  => 'POST',
          'content' => $query_content
        ]
      ]);
      $result = file_get_contents($url, false, $context);



回答2:


$url = 'https://domainname.com/dashboard/api';
$header = [
    'Content-type: application/x-www-form-urlencoded',
];
$params = array('to' => PHONE_NUMBER, 'from' => SENDER_ID, 'message' => TEXT, 'email' => EMAIL, 'api_secret' => SECRET, 'unicode' => BOOLEAN, 'id' => IDENTIFIER);
$c = curl_init();
curl_setopt($c, CURLOPT_URL,$url);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $params);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_HTTPHEADER, $header);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($c);
var_dump($res);


来源:https://stackoverflow.com/questions/60497926/trying-to-send-a-post-request-using-php-no-matter-what-i-do-i-get-http-error-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!