Unable to send json string containing encoded string with curl in php - php

I have created a script to send json data to a url
$data = array();
$key = 'mysecretkey';
$string = 'teststring';
$data['date'] = '2013-06-19 05:38:00';
$data['encrypted_string'] = mcrypt_encode($string,$key);
$data['id'] = 231;
$data['source_ref'] = 'testreference';
$data['status'] = 'Active';
header('Content-type: text/json');
header('Content-type: application/json');
$url = 'http://localhost/myproject/test/add_json_data';
$json_string = json_encode($data);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS,$json_string);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
mcrypt_encode encodes the string. Here is the json_string
{
"date": "2013-06-19 05:38:00",
"encrypted_string": "7Y4jqgIfhj25ghsF8yJ/qTtzXafTtIlwsz7xWIDVWJGoF22X2JbfSWfQtgmI1dYyyJDgs3nmaWctTEgKW5VmHw==",
"id": 231,
"source_ref": "testreference",
"status": "Active"
}
When i exe4cute the script nothing happens on the url i provided.
Here is what i am doing on the url.
function add_json_data()
{
$json = file_get_contents('php://input');
$obj = json_decode($json);
$this->load->helper('file');
write_file('json.json',$json);
}
I am using codeigniter so i am simply saving the post data in a file in json format to see what is coming. But i see the url is not called. I assume due to the encoded json string which contains encoded string it is not sending data to url. How can i send my encoded key to the url. I have also checked if i replace encrypted_string with something 'test' it is working fine. How can i send data to the url or any alternative? Please help.

Always turn on error_reporting when you're developing code, otherwise the simplest syntax error looks like a showstopping bug.
The line:
$string = 'teststring'
Is missing a semicolon.

I have found the answer for this. Here is how i can do this
$data = array();
$key = 'mysecretkey';
$string = 'teststring';
$data['date'] = '2013-06-19 05:38:00';
$data['encrypted_string'] = mcrypt_encode($string,$key);
$data['id'] = 231;
$data['source_ref'] = 'testreference';
$data['status'] = 'Active';
$url = 'http://localhost/myproject/test/add_json_data';
$json_string = json_encode($data);
$header[] = 'Content-type: text/json';
$header[] = 'Content-type: application/json';
$header[] = 'Content-Length: '.strlen($json_string);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS,$json_string);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HTTPHEADER,$header);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
After setting header array and passing it to curl as an option it is working fine.

Related

The request body contains invalid JSON in PHP CURL Request (Discord Webhook)

im trying to upload image to discord webhook about 2 hrs.
Now trying like this but didn't works i got these errors:
{"code": 50109, "message": "The request body contains invalid JSON."}"
I'm trying to upload my local file with curl.
Here is my code:
<?php
$ch = curl_init("https://discord.com/api/webhooks/xx/xx");
$payload = array();
$handle = fopen("cat.png", "r");
$data = fread($handle, filesize("cat.png"));
$payload['files[]'] = $data;
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($payload) );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
?>

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.

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

How to get japanese wiki link from my english wiki link?

Task: We have wikipedia English page and need to retrieve the same page address in Japanese.
suggested to parse http://en.wikipedia.org/wiki/Mini 4wd?action=raw results (there are other languages links in the bottom), but this way is too inefficient. Are there any other ways is the one real option?
We found some API in Wiki that seems fine for single word. but for two words like - Kamen rider, mini 4wd ... it doesn't work.
My code is not working
$url = 'https://en.wikipedia.org/w/api.php?action=query&prop=langlinks&format=json&lllimit=100&llprop=url&lllang=ja&titles=Kamen rider';
$url = rawurldecode(urlencode($url));
echo $url;
// outputs: https://en.wikipedia.org/w/api.php?action=query&prop=langlinks&format=json&lllimit=100&llprop=url&lllang=ru&titles=Mini+4wd
// and then the rest your logic whatever it is the rest
$header[] = "Accept: application/json";
$header[] = "Accept-Encoding: gzip";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = json_decode(curl_exec($ch));
/* echo '<pre>';
print_r($response);
echo '</pre>'; */
exit;
Two words doesn't work because its not properly formatted. Kamen<space>rider and mini<space>4wd has spaces. You need it to be converted first. Consider this example:
$url = 'https://en.wikipedia.org/w/api.php?action=query&prop=langlinks&format=json&lllimit=100&llprop=url&lllang=ru&titles=Mini 4wd';
$url = rawurldecode(urlencode($url));
echo $url;
// outputs: https://en.wikipedia.org/w/api.php?action=query&prop=langlinks&format=json&lllimit=100&llprop=url&lllang=ru&titles=Mini+4wd
// and then the rest your logic whatever it is the rest
$contents = file_get_contents($url);
$contents = json_decode($contents, true);
// echo '<pre>';
// print_r($contents);
// echo '</pre>';
Sample Fiddle
Kindly try this code it works. Your $keywords = 'Mini 4wd';
$url = 'https://en.wikipedia.org/w/api.php?action=query&prop=langlinks&format=json&lllimit=100&llprop=url&lllang=ja&titles='.$keywords.'&redirects=';
$url1 = rawurldecode(urlencode($url));
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url1);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// $output contains the output string
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$exec = explode('"url":"',$output);
$exe = explode('",',$exec[1]);
$URL = $exe[0];
Output :
<p>Wikipedia Help here as <?php echo $URL;?></p>

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