0

I created a rest APi for my website. The GET methods are working fine. For POST method, api is not getting the data posted back to it. I wrote this code but its giving error due to Notice: Trying to get property of non-object in

$response = file_get_contents('http://myapi.com/object/post.php');
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;
Asad
  • 23
  • 1
  • 7
  • 1
    use CURL for the requests. file_get_contents is not useful. The error you get is because of `$data` being null – Mojtaba Aug 06 '18 at 14:11
  • Its recommended to use a front-end like jquery post requests it will help you in future – azizsagi Aug 06 '18 at 14:13
  • Or better then jQuery use fetch as a built in browser feature :) Let the frontend do it's part... – Domenik Reitzner Aug 06 '18 at 14:15
  • possible duplicate: https://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents – Tom Aug 06 '18 at 14:22

2 Answers2

0

You can simple file_get_contents for a GET URL, but to fetch data from a POST URL, you need to use CURL:

<?php

$post = [
    'postData1' => 'datavalue1',
    'postData2' => 'datavalue2'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://myapi.com/object/post.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;
Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
  • Thanks for your reply. In $post = [ 'postData1' => 'datavalue1', 'postData2' => 'datavalue2' ]; postData1, postData2 will be my variables. How will i get 'datavalue1', 'datavalue2. Will it be $post = [ 'postData1' => $_POST['postData1' ], 'postData2' => $_POST['postData1' ] ]; – Asad Aug 06 '18 at 15:16
  • Yes, those are variables that you might want to send to the URL, and you can assign values to them like you said above. – Sujit Agarwal Aug 07 '18 at 06:19
0

Using POST in file_get_contents is explained in the PHP documentation. From the manual page http://php.net/manual/en/function.file-get-contents.php :

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Tom
  • 2,688
  • 3
  • 29
  • 53