Search code examples
phpposttokenfile-get-contents

PHP post request with file_get_content


Please someone to help me

I'm trying to POST a request with file_get_contents and I receive a 415 code error message. I'm not a pro dev and I want to know what is wrong in my source code. Here is my problem:

  1. I generate a token which is a parameter of the second request
  2. the generated token must be used for the POST request

I receive a 415 Error code message. I don't know how to correct that source

$tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
$toke =json_decode($tok, true);
$token=$toke['token'];

$data = json_encode(
    array(
        'from' => 'TEST',
        'to' => '335546821546',
        'type'=> 'Text',
        'content'=> 'Test',
        'sendDateTime'=> '2020/07/07'
        )
);

$options = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Authorization Token " . base64_encode("$token"),
        'content' => $data
    )
);

$context = stream_context_create($options);

$url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';

$result = file_get_contents($url,false,$context);

Solution

  • If you are getting token and facing issue in post call only then i have noticed that you have missed a few Request Headers:

    like Content-type, Content-length, I have check with the different URLs, It is working for me try it

    <?php
        $tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
        $toke =json_decode($tok, true);
        $token=$toke['token'];
    
        $data = json_encode(
            array(
                'from' => 'TEST',
                'to' => '335546821546',
                'type'=> 'Text',
                'content'=> 'Test',
                'sendDateTime'=> '2020/07/07'
                )
        );
    
        $options = array('http' =>
            array(
                'method'  => 'POST',
                'header' => "Content-type: application/json\r\n" .
                            "Content-length: " . strlen($data) . "\r\n" .
                            "Authorization Token: " . base64_encode("$token") . "\r\n",
                'content' => $data
            )
        );
    
        $context = stream_context_create($options);
    
        $url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';
    
        $result = file_get_contents($url,false,$context);
        var_dump($result);