I've seen several posts about how to send GCM messages from my PHP server, but I can't get it working. This is my code:
public function test_gcm($id_user){
// Search user's RegIds and stores them in $regids
if(count($regids) == 0){
echo "This user has no registered device.";
return;
}
$ch = curl_init();
$data = array(
'data' => array('message'=>'my message', 'title'=>'message title'),
'registration_ids' => $regids
);
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
I'm using the browser key. I tried the server key too, but none of them work, the curl_exec always return false. Does anybody know why is it?
EDIT: I just used 'netstat -tuanc | grep 173' on my server and performed the server call. I'm using grep 173 because if I ping android.googleapis.com I ping this ip address. The netstat didn't show any connection to that ip address when I use the curl_exec. Does that mean I'm not connecting to android.googleapis.com? Or what I'm doing is wrong?
Thanks!
Check the "message" content are same or not in android code. 'message'=>'my message' should match with the message from IntentService class in android.
I've managed to fix it. It was a firewall issue, my firewall was blocking the connection. I've added the rules to accept these messages and now it works.
Thanks to all the people that tried to help :)
Try to change it from https to http
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
to
curl_setopt($ch, CURLOPT_URL, 'http://android.googleapis.com/gcm/send');
try this http://2mecode.blogspot.hk/2013/01/google-cloud-messaging-php.html
hope it can help you
Related
I try to get odata produced by a navision webservice. When I directly access the url given using chrome browser, the page asks for user name and password and then chrome shows xml data as expected.
But when i use a PHP script, it always returns "1".
My code looks like this:
$url = 'http://103.7.1.182:14048/DynamicsNAV71-6/OData/Company(\'Unit%20G%205\')/Item_Master_on_hand_no_Desc';
$login = 'Gem-gae\senzo1:Bsbsenzo2018';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $login);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/x-www-form-urlencoded',
'Content-Length: ' . strlen(1))
);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
Is there any mistakes with that code ?
Thanks for your help
There's no mistake on your code, it successfully connects to the external server via cURL and retrieves the data.
The value in $output (if you do a var_dump) is true (that's why you see 1 if you echo it).
Said that, the issue is on the server you are contacting (103.7.1.182:14048).
You probably need to send some data or something, I can't tell you exactly what because I don't know what is in that server.
To send data, you can add a curl_setopt line:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
Where $data is an array.
I'm trying to send a message to a Telegram Bot using CURL in this PHP code ...
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //Receiver Chat Id
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
The code runs with no error but no message is shown in my destination Telegram bot.
The token is what the BotFather give me when I created my destination Telegram bot (Use this token to access the HTTP API: <MY_DESTINATION_BOT_TOKEN>)
Any suggestion will be appreciated ...
I've solved .... In my original code there were two errors, one in the code and one due on a Telegram feature that I didn't know: actually, telegram bot to bot communication is not possible as explained here Simulate sending a message to a bot from url
So my code revised is the follow
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //** ===>>>NOTE: this chatId MUST be the chat_id of a person, NOT another bot chatId !!!**
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
In this way all works fine!
You can obtain chat ID from #RawDataBot, it will be .message.chat.id.
For instance, in this response will be 109780439.
if you want to send telegram using CURL, you need to download file cacert.pem and copy to your web server and then call them from your PHP script.
You can download file cacert.pem from
https://drive.google.com/open?id=1FCLH88MpKNLDXZg3pJUSAZ0BbUbNmBR2
I have tutorial video that can give you the clearly answer, include how to create bot, get token, get user chat_id, troubleshooting SSL and Proxy in CURL, etc:
Here is the link of my tutorial video https://youtu.be/UNERvcCz-Hw
Here is the complete script:
<?php
// using GET URL Parameter -> message
$pesan = urlencode($_GET["message"]);
$token = "bot"."<token>";
$chat_id = "<chat_id>";
$proxy = "<ip_proxy>:<port>";
$url = "https://api.telegram.org/$token/sendMessage?parse_mode=markdown&chat_id=$chat_id&text=$pesan";
$ch = curl_init();
if($proxy==""){
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
else{
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => "$proxy",
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err<>"") echo "Error: $err";
else echo "Message SENT";
?>
use this will work
$TOKEN="your bot token";
$url="https://api.telegram.org/bot{$TOKEN}/sendMessage";
$request=curl_init($url);
$query=http_build_query([
'chat_id'=>"your id",
'text'=>$msg,
'parse_mode'=>'MarkDown'
]);
curl_setopt_array($request,[
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>$query,
]);
curl_exec($request);
I've tested it and its worked.
you only need to us chatId like below:
$chatId='1234567';
I am using Php as a frontend and Java as a backend. I have created an Post API for uploading file and using curl for api request.
I have hit my Api using Postman at that time it works fine but i am facing prodblem when i request api using Curl i don't eble to get what i am doing wrong.
Here is the curl requested data :-
$data2 = array(
'file' =>
'#' . $data1->file->tmp_name
. ';filename=' . $data1->file->name
. ';type=' . $data1->file->type
);
This is how i am sending curl request:-
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch,CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HEADER, 1); //parveen
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //parveen
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
$headers = array(
'Content-Type:'.$this->service->contentType,
'Launcher:'.$this->serverName,
'domain:'.$this->service->domain,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$this->responseBody=curl_exec($ch);
Links where i find this solution:-
enter link description here
I search a lot to find the solution but nothing is worked for me so please help me .
Thanks
the way you're trying to upload the file hasn't been supported since the PHP5 days, and even in 5.5+ you'd need CURLOPT_SAFE_UPLOAD to upload with #. use CURLFile when uploading files, like
$data2 = array(
'file' => new CURLFile($data1->file->name,$data1->file->type,$data1->file->tmp_name)
);
also, don't use CURLOPT_CUSTOMREQUEST for POST requests, just use CURLOPT_POST. (this is also true for GET requests and CURLOPT_HTTPGET )
also, check the return value of curl_setopt, if there was a problem setting your option, it returns bool(false), in which case you should use curl_error() to extract the error message. use something like
function ecurl_setopt($ch,int $option,$value){
if(!curl_setopt($ch,$option,$value)){
throw new \RuntimeException('curl_setopt failed! '.curl_error($ch));
}
}
and protip, whenever you're debugging curl code, use CURLOPT_VERBOSE, it prints lots of useful debugging info
I have an API in postman. I want to create a CURL Request and get proper response with it. This is my POSTMAN API.
I am successfully getting this response with it.
"{\"Request\":{\"state\":\"Manama\",\"address\":\"406 Falcon Tower\",\"address2\":\"Diplomatic Area\",\"city\":\"Manama\",\"country\":\"BH\",\"fullname\":\"Dawar Khan\",\"postal\":\"317\"},\"Response\":{\"status\":\"Success\",\"code\":100,\"message\":\"Address is verified\"}}"
Now I want to use this API Call inside my PHP Code. I used this code.
$data = array(
'Request' => 'ValidateAddress',
'address' => test_input($form_data->address),
'secondAddress' => test_input($form_data->secondAddress),
'city' => test_input($form_data->city),
'country' => test_input($form_data->country),
'name' => test_input($form_data->name),
'zipCode' => test_input($form_data->zipCode),
'merchant_id' => 'shipm8',
'hash' => '09335f393d4155d9334ed61385712999'
);
$data_string = json_encode($data);
$url = 'myurl.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
echo '<pre>';print_r($json_result);echo '</pre>';
But I can't see my $json_result. It just echoes <pre></pre> in the view. Can anyone guide me? Thanks in advance. I want to get my Response.
UPDATE
I used curl_error and it gives me the following error.
Curl error: SSL certificate problem: self signed certificate in certificate chain
It is Very Simple Just Click on Code you will get the code in php.
you will get the code in many language like php,java,ruby,javascript,nodejs,shell,swift,pythom,C# etc.
Answer updated as per updated question.
There are two ways to solve this issue
Lengthy, time-consuming yet clean
Visit URL in web browser.
Open Security details.
Export certificate.
Change cURL options accordingly.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");
Quick but dirty
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
We are configuring cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view.
Excerpt from very detailed and precise article with screenshots for better understanding. Kindly refer the same before actually implementing it in production site.
I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8080)
The curl request I have written in my php code is:
$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;
I can do a curl request :
curl http://my-ip-address:8080/
from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".
Kindly help!
If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.
Two things that might be wrong:
Your Flask server has a firewall that doesn't allow external connections.
You are connecting using an private network IP address rather than a public IP address.
For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.
try to set your port with curl options like this:
curl_setopt($ch, CURLOPT_PORT, 8080);
so your signed url will be:
$signed_url = "http://my-ip-address";
I use this code for my work and worked :)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
the key is CURLOPT_POSTFIELDS