1

I am new to PHP development. I am working on CURL to call my WEB API. As a newbie I found very hard to understand things.

How my API is working

API_URL is http://localhost:14909/api/meters/GetByMsn/002999000077/2017-10-11T12:16:20

It takes a meter serial number and a data time and gives the response by authorizing the URL. The response I get is

{
"data": {
    "Response": "No"
  }
}

What I want to do

Now In PHP I am using CURL to make the request. The request is simple as it takes the current selected meter serial number and a current date time also it should take authorization key.

What I have done till now

Below is the code so far i have done

    if( isset($_REQUEST['selected_meters']))
    {
        $m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);

        $msn = $m->meter_serial; // current selected meter serial number is saved

        $date_time =  str_replace(' ','T',date('Y-m-d H:i:s')); // current date time

        $api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL

        $curl = curl_init($api_url);

        curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.


        exit();

    }

Now I want to send the meter serial number and date time parameters. For this I have searched many articles but all I found a way to pass parameters as query and related link.

One method I am thinking of is passing parameters direct to the URL Like:

$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/[$msn]/[$date_time]';

OR

$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/' + $msn + '/'+$date_time;

But I don't know will it works or not

Any help would be highly appreciated.

Moeez
  • 494
  • 9
  • 55
  • 147

2 Answers2

0

Try this out and see if it works:

$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/${msn}/${date_time}';

or

$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/{$msn}/{$date_time}';
popeye
  • 481
  • 1
  • 4
  • 16
0

So after a lot of searching I manage to get a response. Concatenate both of the parameters in the URL and changing the curl_setopt.

Changes:

From

 $api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL

To

 $api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'.$msn . '/' . $date_time; // my base URL

And

curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.

To

curl_setopt($curl CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // Removed the CURLOPT_RETURNTRANSFER

And then

$curl_response = curl_exec($curl);
         print_r($curl_response);
       /* print_r($msn);
        echo $date_time;*/
        //echo date('Y-m-d H:i:s');
        exit();
Moeez
  • 494
  • 9
  • 55
  • 147