I have created webservices in restler framework and I am trying to insert data using curl in php from client lib that I have created.
api.php
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
for testing purpose from client : testing.php
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal#gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
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 : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);
but it's throwing 404. Please help.
//curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-Type : text","Content-lenght:".strlen($data_string)));
NOTE: Uncomment the line may be.
See the example of post data using curl.
function post($requestJson) {
$postUrl = $this->endpoint."?access_token=".$this->token;
//Get length of post
$postlength = strlen($requestJson);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$postUrl);
curl_setopt($ch,CURLOPT_POST,$postlength);
curl_setopt($ch,CURLOPT_POSTFIELDS,$requestJson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
//close connection
curl_close($ch);
return $response;
}
Checkout some links for more information,
Execute a HTTP POST Using PHP CURL
Submitting a form post with PHP and CURL
Post to a URL Using cURL and PHP
Setup a simple cURL connection to POST data using PHP
Edit:
Restler always returning error 404 not found
may help you.
You should not be mapping all the parameters to URL,
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
By doing so the API can only accept URL such as
http://localhost/Restler/public/examples/news/addcomment/900150983cd24fb0d6963f7d28e17f72/kamal#gmail.com/commentusingcurl/2
Change you API method to
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
Then your cURL example should work fine
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal#gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
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 : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);
Related
<?php
$message=$_POST["msg"];
echo $message;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://.../pl1.php?
m=$message");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
Above is the code iam using.anyone suggest me how do i get value of m in pl1.php
I am getting following error:
Your browser sent a request that this server could not understand.
In PHP variables passed as query string inside URL are accessible in $_GET array.
In your case it will be $_GET['m'].
Try this code:
<?php
$message=$_POST["msg"];
echo $message;
// curl initialize
$ch = curl_init();
// set curl options
curl_setopt($ch, CURLOPT_URL, "http://.../pl1.php?
m=$message");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute request and return response
$output = curl_exec($ch);
echo $output;
// close cURL request
curl_close($ch);
?>
And to get that data on page pl1.php use $_GET['m'];
But, I believe sending data using curl with post method is better than get method.
Thank you
I have recently created one API in Laravel .This was structure of that API :
method : post
url : http://172.22.34.45/mydemo/public/api/v1/file/upload
Form Data
attachment :input file
appVersion :1.0
apiVersion :2.0
type :1
authToken :khsdhdy997sdjjsd886
In my question is how can i implement this API in my Codeigniter project.
I know using ajax but in my scenario its not working perfect.Please suggest another option
eg : calling api from codeigniter controller
By using curl POST like this:
$url = "http://172.22.34.45/mydemo/public/api/v1/file/upload";
$data = array("all the parameters as array elements");
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reponse= curl_exec($ch);
curl_close($ch);
} catch (Exception $ex) {
}
$data is the array with values to be sent. $reponse will have whatever you return.
This the proven solution to implement RESTFULL Service in CI that I've tested in several projects.Please refer the documentation carefully before implement.It will save your time.
https://github.com/chriskacerguis/codeigniter-restserver
I would like to integrate with ChannelAdvisor REST API using the SOAP Credentials Flow.
Based on their documentation, I have setup the following in PostMan (rest client in Chrome browser) like this:
When I make the rest; the rest api server returns the expected response:
So, I tried to replicate this in PHP with the following class:
<?php
class ChannelAdvisorREST {
/**
* ChannelAdvisor constants & properties
*/
const BASE_URL = 'https://api.channeladvisor.com/v1';
private $config;
/**
* Class constructor
*/
public function __construct()
{
$this->config = \Config::get('channeladvisor');
}
// TEST
public function test($accountId)
{
// var_dump($this->config);
var_dump(self::getAccessToken($accountId));
}
// TEST
/**
* Method to get access token from rest server.
*
* #param $accountId
* #return string
*/
private function getAccessToken($accountId)
{
return self::curlPOST('/oauth2/token', [
'client_id' => $this->config['api_app_id'],
'grant_type' => 'soap',
'scope' => 'inventory',
'developer_key' => $this->config['api_developer_key'],
'password' => $this->config['api_password'],
'account_id' => $accountId
]);
}
/**
* Method to generate a HTTP POST request
*
* #param $endpoint
* #param $fields
* #return string
*/
private function curlPOST($endpoint, $fields = array())
{
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_USERPWD, $this->config['api_app_id'] .':'. $this->config['api_shared_secret']);
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
// Execute post request
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Finished
return $result;
}
}
When I execute the test($accId) method on this class, I get the following response:
boolean false
Any idea why it isn't quite working as same as the PostMan test?
P.S. I have already verified all the config/parms etc... are correct and same as my PostMan test. This class is a snipped version from my original code (created in Laravel 4.2, but this issue is not related to Laravel).
Two things:
Make sure that you send the same headers as your browser sends. For example, I don't see the Authorization-header in your code, and that one is probably quite crucial for authorizing the request on the server-side. Also for the scope you use 'inventory' instead of 'orders inventory'. Be very strict in this exercise.
Test the post-data not in an array, but write down the query-string as it should be according to yourself, this way you know there is not some issue by CURL trying to convert your array into a query-string (note, both is possible for CURL, array and query-string).
So most easy to test with:
client_id=1234&grant_type=soap&scope=order%20inventory...etc add other variables...
I have found the problem. The issue was caused by my php not being configured with curl.cainfo.
I found this by adding the following debug code to my curlPOST method like this:
private function curlPOST($endpoint, $fields = array())
{
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_USERPWD, $this->config['api_app_id'] .':'. $this->config['api_shared_secret']);
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// Debug error
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($ch), htmlspecialchars(curl_error($ch)));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return $result;
}
This outputted the following error message:
cUrl error (#60): SSL certificate problem: unable to get local issuer certificate
Verbose information:
* Hostname was found in DNS cache
* Hostname in DNS cache was stale, zapped
* Trying 216.27.89.14...
* Connected to api.channeladvisor.com (216.27.89.14) port 443 (#7)
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 7
boolean false
Which helped me track down the issue with my php.
:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.
I want to have a script on one website and database on other website.
First website has 2 fields where they enter username and password. Then php posts username/password to other php file and that php does something and then somehow sends the data to my second website, where I insert username and password to MySql database.
So I can do everything except:
I have 2 variables in PHP file, and I want to send them to other webpage, which gets them with maybe $_POST ? Also posting should be automatic, so the script posts them itself not via button press. How to do it?
Is my question clear? I can explain.
Thanks.
Why can't your script on your dummy website retrieve the data via $_POST and then call the script from your real website?
http://davidwalsh.name/execute-http-post-php-curl
Check that out. This way your can POST to your real website from your dummy site's script, completely transparent to the user.
Hope that makes sense.
You can use the PHP cURL library to send these kinds of data requests.
Link: http://php.net/manual/en/book.curl.php
There are three obvious ways to do this:
1) Simple – keep the page hosted on site 2, but use an iframe on site 1 to embed it.
2) Post the form from site 1 to site 2 by setting the action attribute to a script on site 2.
3) Post the form on site 1 to a script on site 1, then use CURL to post it to the other site behind the scenes.
/**
* create request || application/json
* #param $method
* #param $url
* #param $args
* #param $isSentBody
* #param $cert
* #return resource
*/
function createRequest($method, $url, $args, $isSentBody, $cert = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
if ($isSentBody) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
//'Authorization : Bearer ' . getAccessToken(),
));
}
if ($cert)
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . $cert);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
try {
return curl_exec($ch);
} catch (Exception $e) {
throw $e;
}
}