0

I am trying to send JSON to an API url. I am sending the json from test.php and I am receiving the data from api.php. I want to log the data into a text file, but nothing is logged, I assume that $data is returning null? In my test.php file it keeps returning "Sent BAD, request terminated." What am I doing wrong? How would I fix this?

test.php

<?php

$ch = curl_init();

$array = array('foo' => 'bar');

curl_setopt($ch, CURLOPT_URL,"https://dropchat.net/api.php");
curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($array));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

if ($server_output == "OK") { 
    echo "Sent OK";
} else { 
    echo "Sent BAD, request terminated.";
}

?>

api.php

<?php

$data = json_decode(file_get_contents('php://input'), true);

$fp = fopen("myText.txt","wb");
fwrite($fp, $data);
fclose($fp);

?>
13
  • I assume...don't assume, test. And configure PHP to log errors and warnings to a file. Commented Feb 2, 2021 at 20:38
  • if ($server_output == "OK") { will never be true because api.php doesn't echo "OK" (or anything else, for that matter). So that doesn't prove anything one way or another. Commented Feb 2, 2021 at 20:38
  • Should test.php be api.php? Commented Feb 2, 2021 at 20:40
  • @Barmar Yes, I will fix that Commented Feb 2, 2021 at 20:41
  • 1
    The 2nd argument to fwrite() should be a string. $data is an array. Commented Feb 2, 2021 at 20:41

1 Answer 1

1

Add error checking to api.php so you'll know what happened.

You can't write an array to a file, you can only write a string. So write the foo element of the array.

<?php
$data = json_decode(file_get_contents('php://input'), true);
if ($data === null) {
    echo json_last_error_msg();
} else {
    file_put_contents("myText.txt", $data['foo']);
    echo "OK";
?>

Then change the caller to print the error message:

$server_output = curl_exec($ch);

curl_close ($ch);

if ($server_output == "OK") { 
    echo "Sent OK";
} else { 
    echo "Sent BAD, reason: $server_output";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.