PHP IF statement testing decoded JSON data

12

I want to send received JSON data to a PHP CURL script I've written on my server to then forward the data to multiple external webhook URLs conditioned on data received in a specific field key/value.

However, either my IF statement is misconfigured or I'm not accessing the field data properly, because my test webhook endpoint isn't being delivered to. If I remove the IF statement, the code delivers the data as expected.

$dataReceive = file_get_contents("php://input");
$dataEncode = json_encode($dataReceive, true);
$headers = array ( 'Content-type: application/json');
print_r($dataEncode);

$curl = curl_init();
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt( $curl, CURLOPT_POST, 1);
curl_setopt( $curl, CURLOPT_POSTFIELDS, $dataEncode);
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers);

if ( $dataEncode ['Field 3'] == 'Test' )  {
    curl_setopt( $curl, CURLOPT_URL, 'http://webhook1.com');
 }
if ($dataEncode ['Field 3'] == 'Test Value 2' ) {
    curl_setopt( $curl, CURLOPT_URL, 'http://webhook2.com');
 }

$results = curl_exec($curl);
echo $results;
curl_close($curl);

The JSON data received in the $dataReceive object is:

{
   "Timestamp": 1568838624687,
   "Object": "Project",
   "UserId": "",
   "ObjectId__PhaseId": 111,
   "Other__PhaseName": "Turndown",
   "ProjectId": 111,
   "OrgId": 111,
   "Event": "PhaseChanged",
   "ObjectId__ProjectTypeId": 1409
 }

I'm testing by using Postman to just send dummy data to my PHP script, but once that works as expected, I'll actually be filtering for the key "Other_PhaseName".

Appreciate the help!

64

Answer

Solution:

I think problem is with the if statements. It should be like this

if ( $dataEncode['Field 3'] == 'Test' )  {
    curl_setopt( $curl, CURLOPT_URL, 'http://webhook1.com');
}
843

Answer

Solution:

There's quite a few errors in there.

Start with your if statements

if ( $dataEncode['Field 3'] == 'Test')  {
    curl_setopt( $curl, CURLOPT_URL, 'http://webhook1.com');
 }

if ($dataEncode['Field 3'] == 'Test Value 2'){
    curl_setopt( $curl, CURLOPT_URL, 'http://webhook2.com');
 }

People are also looking for solutions to the problem: php - Unable to connect to Apache server in XAMPP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.