My PHP code (free.php) on http://techmentry.com/free.php is
<?php
{
//Variables to POST
$access_token = "b34480a685e7d638d9ee3e53cXXXXX";
$message = "hi";
$send_to = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('access_token' => $access_token,
'message' => urlencode('hi'),
'send_to' => $send_to,)
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
I am getting this error: THE MESSAGE WAS BLANK
This error means: "The message field was blank or was not properly URL encoded" (as told by my SMS gateway). But as you can see that my message field isn't blank.
I believe you can't send an array to CURLOPT_POSTFIELDS, you would need to replace the line with the following
curl_setopt($ch, CURLOPT_POSTFIELDS, "access_token=".$accesstoken."&message=".urlencode('hi')."&send_to=".$send_to);
I hope this solves it
Use http_build_query():
<?php
{
$postdata = array();
//Variables to POST
$postdata['access_token'] = "b34480a685e7d638d9ee3e53cXXXXX";
$postdata['message'] = "hi";
$postdata['send_to'] = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata) );
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
Related
I have a CURL code that I use to integrate with GetResponse and I thought ill go ahead and copy/paste it for slack too. For some reason there are no errors at all yet slack is empty of requests (a POST to this URL with Postman works just fine). What am I missing? I couldn't find a solution the whole night.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
$slackReporting_error = "";
if(empty($slackReporting_res->error)){
echo "OK";
} else {
$slackReporting_error = $slackReporting_res->error->message;
}
echo $slackReporting_error;
?>
I always get an OK.
Since you din't return anything from function so you are getting nothing inside $slackReporting_res .Do like below:-
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);exit;
}
curl_close($ch);
return $content;
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
var_dump ($slackReporting_res); //check output and work accordingly
?>
And now Op's got error and solved through this link(mentioned by OP in comment):-
PHP - SSL certificate error: unable to get local issuer certificate
Here is a simple example of how to use slack with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here
I want to know final url just before executing curl to check all parameters passing as desired. how to view that.
<?PHP
function openurl($url) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
openurl($sms_url);
?>
desired output to check all params and its values passing correct..
http://remoteserver/plain?user=user123&password=user#user!123&Text=TESThere
You forgot to add the $postvars as parameter to your function.
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
// create a test var which we can display on screen / log
$test_url = sms_url . http_build_query($postvars);
// either send it to the browser
echo $test_url;
// or send it to your log (make sure loggin is enabled!)
error_log("CURL URL: $test_url", 0);
openurl($sms_url, $postvars);
I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
Im trying my hand at using curl to post some data, I am not reciving my post content and can not find the source of the problem
curl.php
<?php
$data = array("user_email" => "22" , "pass" => "22" );
$string = http_build_query($data);
$ch = curl_init("http://localhost:8888/290_project/test.php"); //this is where post data goes too, also starts curl
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch) //ends curl
?>
test.php
<?php
if(isset($_POST['user_email'], $_POST['pass'])) {
$name = $_POST['user_email'];
$pass = $_POST['pass'];
echo $name;
echo $pass;
} else {
echo "error";
} ?>
Every time I get my error response meaning the post data is not going through. I have tried everything I could think of to trouble shoot;I must be over looking something I am simply not yet familiar with?
Please set CURLOPT_URL to http://localhost:8888.....
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8888/290_project/test.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
if(!curl_errno($ch)){
$info = curl_getinfo($ch);
} else {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch) //ends curl
?>
With curl_getinfo() - Gets information about the last transfer.
For more detail read below link:- http://php.net/manual/en/function.curl-getinfo.php
I have edited the answer, The reason for error is not curl.
http_build_query($data, '', '&');
Following is working example. Please try this.
$postData = array(
'user_name' => 'abcd',
'password' => 'asdfghj',
'redirect' => 'yes',
'user_login' => '1'
);
$url='http://localhost:8888/290_project/test.php';
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $url);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$store = curl_exec($ch);
print_r($store);
curl_close($ch)
You have an error in your php code:
edit:
if(isset($_POST['user_email'], $_POST['pass'])) {
to:
if(isset($_POST['user_email']) && isset($_POST['pass'])) {
Hello I am passing an JSON array from one server say www.example1.com and I want to receive that data on another server say www.example2.com/test.php . I have tried this using cURL but I am not getting that data at the receiving. Following is my code
Code at Sender
$send_data = json_encode($myarray);
$request_url = 'www.example2.com/test.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'send_data='.$send_data);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);
Code at Receiver
if(isset($_REQUEST['send_data'])){
$userinfo = json_decode($_REQUEST['send_data'],true);
print_r($userinfo);
}
How do I fetch the data at receiver's end.
Try this method.
FILE: example1.com/sender.php
$request_url = 'www.example2.com/test.php';
$curl = curl_init( $request_url );
# Setup request to send json via POST.
$send_data = json_encode($myarray);
curl_setopt( $curl, CURLOPT_POSTFIELDS, $send_data );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($curl);
curl_close($curl);
# Print response.
echo "<pre>$result</pre>";
on your second page, you can catch the incoming request using file_get_contents("example1.com/sender.php"), which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("example1.com/sender.php")),1).'</pre>';
Use the following
FILE: example1.com/sender.php
<?php
header('Content-Type: application/json'); echo
json_encode(array('response1' => 'This is response1', 'response2' => 'This is response2', $_POST));
?>
FILE: example2.com/receiver.php
<?php
$request_url = 'http://www.example1.com/sender.php';
$sendData = array('postVar1' => 'postVar1');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'sendData=' . http_build_query($sendData));
print_r($response = curl_exec($curl));
curl_close($curl);
?>
You will get a JSON object as a cURL response.