PHP IF statement testing decoded JSON data - php

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!

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');
}

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');
}

Related

eBay api search item

I want to get items by keyword search.
<?php
error_reporting(E_ALL);
require_once("includes/config.php");
// Construct the HTTP GET call
$apicall = "https://api.ebay.com/buy/browse/v1/item_summary/search?"; //
URL to call
$apicall .= "q=GTR"; //search keyword
$apicall .= "limit=3";
// Create headers to send with CURL request.
$headers = array
(
'X-EBAY-API-APP-ID: ' . $sapp_id,
'X-EBAY-API-DEV-NAME: ' . $dev_id,
'X-EBAY-API-CERT-NAME: ' . $cert_id,
'X-EBAY-C-ENDUSERCTX: 5337984774'
);
// Send request to eBay and load response in $response
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL,
"https://api.ebay.com/buy/browse/v1/item_summary/search?");
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $apicall);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
// Load the call and capture the document returned by eBay API
$resp = $response;
// Output response
echo("<pre>");
print_r($resp);
//To retrieve specific values of the array in PHP, you will need to use
object operator
// $value = $resp->Item->ConvertedCurrentPrice;
// $value = $resp->Item->ConvertedCurrentPrice;
// print $xml->Product->Title;
echo("</pre>");
?>
i got this error when i run.
{
"errors": [
{
"errorId": 3001,
"domain": "ROUTING",
"category": "REQUEST",
"message": "Request Rejected",
"longMessage": "The Request has errors. For help, see the documentation for this API."
}
]
}
Since i am beginner i don't know what to do.
i tried xml request method and it's work fine but i want to do it with REST API method.
i follow this docs - Official eBay search api documentation
i like to know why i am getting this error and what's the correct way to achieve this search query ?
Not tested as I don't have an eBay developer account but perhaps the following might help. The code below will issue a GET request with the querystring as part of the url as the documentation suggests
<?php
error_reporting( E_ALL );
require_once("includes/config.php");
/*
you can download from https://curl.haxx.se/docs/caextract.html
*/
$cacert='c:/wwwroot/cacert.pem'; # edit as appropriate to point to valid `cacert.pem` file
$verbose=true;
$endpoint = "https://api.ebay.com/buy/browse/v1/item_summary/search?";
$args=array(
'q' => 'GTR',
'limit' => 3
);
$url=sprintf( '%s%s', $endpoint, http_build_query( $args ) );
/*
for advanced debug information we create a stream
and output to that during the request. At the end
of the request the stream is processed and we can
view that data.
*/
if( $verbose )$vbh = fopen('php://temp', 'w+');
$headers = array(
'X-EBAY-API-APP-ID: ' . $sapp_id,
'X-EBAY-API-DEV-NAME: ' . $dev_id,
'X-EBAY-API-CERT-NAME: ' . $cert_id,
'X-EBAY-C-ENDUSERCTX: 5337984774'
);
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'curl' );
if( $verbose ){
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh ); # the stream object
}
/* make the request and get info */
$response = curl_exec( $curl );
$info=(object)curl_getinfo( $curl );
$errors=curl_error( $curl );
/* store the verbose debug info */
if( $verbose ){
rewind( $vbh );
$debug=stream_get_contents( $vbh );
fclose( $vbh );
}
curl_close( $curl );
if( $info->http_code==200 ){
printf( '<pre>%s</pre>', print_r( $response, 1 ) );
} else{
printf( '<pre>%s</pre>', print_r( $verbose ? $debug : $info ,1 ) );
printf( '<pre>%s</pre>', print_r( $errors, 1 ) );
}
?>

Inline keyboard Telegram bot [PHP]

I want that my bot when I write /orario he answer me with a inline keyboard.
So.. I created an array for my keyboard in this way:
$tastierino_giorno = '[{"text":"Testo","callback_data":"StampaMessaggio"}]';
and in another function I write this:
function tastieraInline($chatid, $tastierino)
{
global $token;
$messaggio = "Scegli per che giorno inviare il messaggio:";
$tastiera = '&reply_markup={"inline_keyboard":
['.urlencode($tastierino).'],"resize_keyboard":true}';
$url = "https://api.telegram.org/$token/sendMessage?chat_id=$chatId&parse_mode=HTML&text=".urlencode($messaggio).$tastiera;
file_get_contents($url);
}
After this, with an if, I check if the users has write "/orario".
} elseif($message == "/orario"){
tastieraInline($chatid, $tastierino_giorno);
}
Now the problem is that it doesn't works... what's the problem?
Change
$tastiera = '&reply_markup={"inline_keyboard":
['.urlencode($tastierino).'],"resize_keyboard":true}';
to
$tastiera = '&reply_markup='.urlencode('{"inline_keyboard":
['.$tastierino.'],"resize_keyboard":true}');
you should URL encode the whole JSON data
You should pay attention to the result returned from your telegram calls. file_get_contents is great for getting something working quickly but doesn't return any error information.
You should use curl or a library like guzzle. An example for curl:
$ch = curl_init( $url );
if ( $ch == FALSE )
{
error_log( "Error initialising curl" );
return FALSE;
}
curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_POST, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, 1 );
// Set TCP timeout to 30 seconds
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Connection: Close' ) );
$result = curl_exec( $ch );
$error = curl_errno( $ch );
$errorStr = curl_error( $ch );
curl_close( $ch );
if ( $error != 0 )
{
return array( $errorStr, $result );
}
return $result;
Guzzle is a lot simpler if you don't mind installing an additional library.
Hopefully this will get you the error string from your failed telegram calls.
Onto your actual issue. You should create json for the keyboard markup using json_encode rather than appending strings. http_build_query makes building URLs much easier.

PHP Proxy POST request to API with file upload

I have a job application form that contains a bunch of text inputs and two fields to upload files (resume and cover letter).
This form needs to post to a job board API endpoint but the request has to be proxied so the API key isn't seen in the post. This is working fine with just the text inputs but I can't figure out how to get the files to upload as well. Below is what I have so far, which only posts the text.
How do I need to go about uploading the files as well?
<?php
if ( $_POST ) {
// API key
$api_key = 'super_secret_key';
$url = "https://api.myjobboard.io/applications/";
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_USERPWD, $api_key . ":" . '' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $_POST ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
$response = curl_exec( $ch );
echo $response;
} else {
echo '<p>Error: No post data.</p>';
}
?>

Transfer array from one page to another using CURL

Im trying to transfer an array of data between two files.
The sender.php code (the file sending the array using POST method)
$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three")
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_elements);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
echo "$response";
The receiver.php code (The file receiving the array from sender.php file and then take each element of the array and echo it and also put it in a document saved.txt.
echo $_POST($myvars); // To test the output of the received data.
foreach($myvars as $item) {
if (!empty($item)) {
echo $item."<br>";
$myfile = file_put_contents('Saved.txt', (" Name: ". ($_POST["$item"])) . PHP_EOL , FILE_APPEND);
}
}
The array isn't being transferred to the receiver.php or I am not catching it. In the document output I have only in the place of the variable $item instead of each element of the array.
Edit:
Added the following code in the receiving file in order to get the array elements from inside but all I get is array printed out:
foreach( $_POST as $stuff ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing ) {
echo $thing;
}
} else {
echo $stuff;
}
}
By adding on the receiving file the following:
echo "<pre>";
print_r($_POST);
echo "</pre>";
I get the following:
Array
(
[myvars] => Array
)
OK, the bottom line of the discussion in the comments above leads to this result:
The sending part:
<?php
$url = 'http://localhost/out.php';
$myvars = array("one","two","three");
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($post_elements));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
print_r($response);
The receiving part:
<?php
print_r($_POST);
The output on the sending side is:
Array ( [myvars] => Array ( [0] => one [1] => two [2] => three ) )
which basically says that you can simply use $_POST['myvars'] on the receiving side which will exactly hold the scalar array you want to transfer.
try to serialize the array because it always helps me :
$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three");
$myvars_post=join(" ",$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, "array=".urldecode($myvars_post));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
echo "$response";
and in the receiver.php use :
print_r($_POST);

Php script for push notfication returns nothing

I have this script for sending a push notification on my android app :
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("message");*/
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
I never get any push notification on my phone. The thing is that actually i never get any output from the script like the echo $result; returns nothing.
Is this even possible?
Any ideas?
Solution
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("message");*/
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
Now it works perfectly.
Found the error.
Replace line curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
with line curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
I corrected the code on the question so now it works.

Categories