In native PHP, I have a consuming restful server like this:
$url = "http://localhost/pln/api/json?rayon=$rayon&id_pel=$id_pel&nama=$nama";
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$respone = curl_exec($client);
$result = json_decode($respone);
How can I access cURL like this when using CodeIgniter?
There's no active cURL library around for CodeIgniter 3.x. There were one for CI 2.x which is no longer maintained.
Consider using Guzzle which is very popular and considered as a de-facto HTTP interfacing library for PHP. Here's an usage example from the docs:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
I also recommend using Requests which is inspired by Python Requests module and is way more easier than Guzzle to get started with:
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[...]"
As CodeIgniter 3.x has support for Composer packages out of the box, you can easily install one of these packages through composer and start using it right away.
I stongly recommend you to not to go down the "Download Script" way as suggested in Manthan Dave's answer. Composer provides PHP with a sophisticated dependency management ecosystem; Utilize that! "Download This Script" dog days are over for good.
I used the following function in codeigniter for curl url and works fine, try it out:
function request($auth, $url, $http_method = NULL, $data = NULL) {
//check to see if we have curl installed on the server
if (!extension_loaded('curl')) {
//no curl
throw new Exception('The cURL extension is required', 0);
}
//init the curl request
//via endpoint to curl
$req = curl_init($url);
//set request headers
curl_setopt($req, CURLOPT_HTTPHEADER, array(
'Authorization: Basic ' . $auth,
'Accept: application/xml',
'Content-Type: application/x-www-form-urlencoded',
));
//set other curl options
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($req, CURLOPT_TIMEOUT, 30);
//set http method
//default to GET if data is null
//default to POST if data is not null
if (is_null($http_method)) {
if (is_null($data)) {
$http_method = 'GET';
} else {
$http_method = 'POST';
}
}
//set http method in curl
curl_setopt($req, CURLOPT_CUSTOMREQUEST, $http_method);
//make sure incoming payload is good to go, set it
if (!is_null($data)) {
if (is_array($data)) {
$raw = http_build_query($data);
} else {
//Incase of raw xml
$raw = $data;
}
curl_setopt($req, CURLOPT_POSTFIELDS, $raw);
}
//execute curl request
$raw = curl_exec($req);
if (false === $raw) { //make sure we got something back
throw new Exception(curl_error($req) . $url, -curl_errno($req));
}
//decode the result
$res = json_decode($raw);
if (is_null($res)) { //make sure the result is good to go
throw new Exception('Unexpected response format' . $url, 0);
}
return $res;
}
You could use default Curl library of codeigniter:
$this->load->library('curl');
$result = $this->curl->simple_get('http://example.com/');
var_dump($result);
For more details refer this link :
https://www.formget.com/curl-library-codeigniter/
Adding to #sepehr answer. Requests library can be configured in a very easy way in codeigniter as described here
https://stackoverflow.com/a/46062566/2472685
Related
I am trying to use a PHP CURL request to upload data to Pass Slot to change an image, and I am continually getting errors.
This is the CURL request needed from their developer section on their website
POST https://api.passslot.com/v1/passes/pass.example.id1/27f145d2-5713-4a8d-af64-b269f95ade3b/images/thumbnail/normal
and this is the data that needs to be sent in its requested format
------------------------------330184f75e21
Content-Disposition: form-data; name="image"; filename="icon.png"
Content-Type: application/octet-stream
.PNG
imagedata
This is the code I am using currently, as I am not familiar with what is required on Multipart Form requests on API
$passId = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx";
$pass_generate_url = "pass.xxxxxxxxxxxx";
$url1 = 'https://api.passslot.com/v1/passes/'.$pass_generate_url.'/'.$passId.'/images/strip/normal';
$logo_file_location = "image.png";
$logo_file_location1 = "http://xxxxxxx.com/uploads/";
$data1 = array('image' => '#uploads/'.$logo_file_location,'application/octet-string',$logo_file_location1,'some_other_field' => 'abc',);
$auth1 = array( 'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=',
'Content-Type: text/plain');
$ch1 = curl_init($url1);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $data1);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $auth1);
$response1 = curl_exec($ch1);
$ch1 = curl_init($url1);
When I run the code, this is the response from the CURL I get
{"message":"Validation Failed","errors":[{"field":"image","reasons":["Required"]}]}
Is there something I need to add to make the code work please?
Yes, I think you can build your own curl including to use say PHP CURLFile (sending the Multipart delimiter boundary and then the graphic data, etc) But you may choose to use an API (Say PassSlot PHP SDK)
https://github.com/passslot/passslot-php-sdk
General usage
require 'passslot-php-sdk/src/PassSlot.php';
$engine = PassSlot::start('<YOUR APP KEY>');
$pass = $engine->createPassFromTemplate(<Template ID>);
$engine->redirectToPass($pass);
For PNG file, it is like:
<?php
require_once('../src/PassSlot.php');
$appKey ='<YOUR APP KEY>';
$passTemplateId = 123456;
$outputPass = FALSE;
$values = array(
'Name' => 'John',
'Level' => 'Platinum',
'Balance' => 20.50
);
$images = array(
'thumbnail' => dirname(__FILE__) . '/thumbnail.png'
);
try {
$engine = PassSlot::start($appKey);
$pass = $engine->createPassFromTemplate($passTemplateId, $values, $images);
if($outputPass) {
$passData = $engine->downloadPass($pass);
$engine->outputPass($passData);
} else {
$engine->redirectToPass($pass);
}
} catch (PassSlotApiException $e) {
echo "Something went wrong:\n";
echo $e;
}
For further reference, please visit this
https://github.com/passslot/passslot-php-sdk/blob/master/examples/example.php
You may also view the source of the API to get inspired:
https://github.com/passslot/passslot-php-sdk/blob/master/src/PassSlot.php
Additional remark:
In case there is certificate expiry warning/error when running the SDK, please download the latest cacert.pem from https://curl.se/docs/caextract.html and replace the one in the SDK
I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}
If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,
Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.
I'm creating an application for Google App engine, where CURL isn't allowed.
As far as I know, urlFetch is the best alternative.
I don't know if I can achieve the same result with urlFetch, but I would really, really appreciate it if anyone with more experience could help me out.
The plan was to convert the following CURL requests to urlFetch. If anyone can point me in the right direction, or propose a better alternative, I'd greatly appreciate it.
public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $this->options['url'].$endpoint);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
if ($headers && is_array($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$post_data['req_token'] = $this->hash($param1, $param2);
curl_setopt($ch, CURLOPT_POST, count($post_data));
if (!$headers)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
else
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data);
$this->debug('POST params: ' . json_encode($post_data));
$result = curl_exec($ch);
if ($result === false) {
$this->debug('CURL error: '.curl_error($ch));
return false;
}
$this->debug('HTTP response code' . curl_getinfo($ch, CURLINFO_HTTP_CODE));
$this->debug('POST return ' . $result);
// close connection
curl_close($ch);
if ($json)
return json_decode(utf8_encode($result), true);
else
return $result;}
Did you look at the Urlfetch documentation and the linked PHP article about wrappers?. You can experiment with this live shell.
The code could be translated to something like:
public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
$post_data['req_token'] = $this->hash($param1, $param2);
$this->debug('POST params: ' . json_encode($post_data));
$data = http_build_query($post_data);
$options =
array("http"=>
array(
"method" => "POST",
"content" => $post_data,
)
);
if ($headers && is_array($headers)) {
$options["http"]["header"] = $headers;
}
$context = stream_context_create($options);
$result = file_get_contents("http://app.com/path?query=update", false, $context);
if ($result === FALSE) {
$this->debug('Error: '. print_r($http_response_header));
return FALSE;
}
$this->debug('Response headers:' . print_r($http_response_header)); // To get the status code you would need to parse that response
$this->debug('POST return ' . $result);
if ($json)
return json_decode(utf8_encode($result), true);
else
return $result;
}
Here is simple library which replaces curl native functions with urlfetch. https://github.com/azayarni/purl
Someone here suggested using the PURL from azayarni. Let me warn you: avoid using it on Google App Engine. I spent SEVERAL days trying to get it work without success: the Google PHP Client SDK is rewriting itself some CURL functions and simply PURL mess it up a lot. Some things were working, some were not. The URLFETCH tool is much more easier and safe.
Its a very old post, but just an update: Google App Engine now supports cURL with its PHP 5.5 runtime.
I tried to post to wordpress blog from extrnal php code , all of my files are in the same directory, public_html.
this is my code:
function wpPostXMLRPC1($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
but its wrong, the error is
Fatal error: Call to undefined function xmlrpc_encode_request()
i can post to my wordpress blog with microsoft word(publish->blogPost), so Help me
PHP's xmlrpc extension seems to be not enabled on your server.
Wordpress using http://scripts.incutio.com/xmlrpc/ as xmlrpc server, you don't need xmlrpc extension to post to your wp. Just follow the instruction http://scripts.incutio.com/xmlrpc/advanced-client-construction.php.
But if you want to post on another way, such as posting by email you can follow this tutorial codex.wordpress.org/Post_to_your_blog_using_email
I struggled with the same. I found a similar problem somewhere else on the net and tweaked to to fit Wordpress. Mind you Wordpress install (wordpress.org), not the blog hosting service at wordpress.com. This should be working provided you have curl and xmlwriter enabled:
<?php
class atompub
{
//public $parae = '';
function __construct($one, $two, $three, $four)
{
$this->author=$one;
$this->title=$two;
$this->categories=$three;
$this->body=$four;
}
function create_post()
{
$xmlwriter = new XMLWriter();
$xmlwriter->openMemory();
$xmlwriter->startDocument("1.0", "UTF-8");
$xmlwriter->startElement('entry');
$xmlwriter->writeAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$xmlwriter->startElement('author');
$xmlwriter->writeElement('name', $this->author);
$xmlwriter->endElement();
$xmlwriter->writeElement('title', $this->title);
$xmlwriter->startElement('content');
$xmlwriter->writeAttribute('type', 'html');
$xmlwriter->text($this->body);
$xmlwriter->endElement();
$xmlwriter->startElement('category');
$xmlwriter->writeAttribute('term', $this->categories);
$xmlwriter->endElement();
$xmlwriter->endElement();
$xmlwriter->endDocument();
return $xmlwriter->outputMemory();
}
function __destruct()
{
}
}
$target = "<URL til your WordPress installation>/wp-app.php/posts";
// Note that the directory "posts" are used for posting (POST method)
// "service" is used to pull info via the GET method (not shown here)
$user = "XXX"; // Substitue XXX with your WordPress username
$passwd = "YYY"; // Substitue XXX with your WordPress password
$author='Your Name';
$title='The title of your choice for your new entry';
$array_of_categories='Category';
$body='This is the main body. All the text goes in here';
$xml_post = new atompub($author,$title,$array_of_categories,$body);
$post = $xml_post->create_post();
$headers = array("Content-Type: application/atom+xml ");
$handle = curl_init($target);
$curlopt_array = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERPWD => $user.':'.$passwd,
CURLOPT_FOLLOWLOCATION => true,
CURLINFO_HEADER_OUT => true);
curl_setopt_array($handle, $curlopt_array);
$result = curl_exec($handle);
//var_dump($result);
$header_sent=curl_getinfo($handle);
//var_dump($header_sent);
if ($result === false) {
print "Got " . curl_errno($handle) . " : " . curl_error($handle) . "\n";
curl_close ($handle);
return;
}
$response_http_code = curl_getinfo ($handle, CURLINFO_HTTP_CODE);
if ($response_http_code != 201) {
print("HTTP status code: $response_http_code \n");
curl_close($handle);
return;
}
curl_close($handle);
?>
This should work directly, but you need to change the strings indicated (Blog URL, username, password, author, etc...). Beware that the login in insecure. This is only for demonstrating the functionality. You may also want to change the response code handling (which isn't mine, it came along with the original example which this is based upon).
On success Wordpress returns XML to you with details of the post event.
Fatal error: Call to undefined function xmlrpc_encode_request()
some times this error appear because xmlrpc extension is disabled.
execute phpinfo() to see if xmlrpc module displays or not.
If not, you need to enable it from php.ini by removing the semicolon, like
;extension=php_xmlrpc.dll to extension=php_xmlrpc.dll
and then restart Apache
function do_post_request($url, $data, $optional_headers = null) {
$request = new HttpRequest($url, HttpRequest::METH_POST);
$request->setBody($data);
$response = $request->send();
return $response->getBody();
}
This piece of code doesn't seem to be working, and seems to crash my script. I don't know if its because I don't have the php_http module, but is there an equivalent I can use?
For instance curl? I have tried curl, but I don't know much about it, and with curl I got a "bad request" returned from the server I was trying to connect to with a 400 status.
Anything would be good
Thanks
Tom
Edit:
function do_post_request($url, $data, $optional_headers = null) {
$request = new HttpRequest($url, HttpRequest::METH_POST);
$request->setBody($data);
$response = $request->send();
return $response->getBody();
}
echo "before";
$response = do_post_request($url, $data);
echo "After";
Doing that makes "before" appear on the page. But no "After".
After managing to turn error reporting on I get this:
Fatal error: Class 'HttpRequest' not found in /home/sites/ollysmithwineapp.com/public_html/mellowpages/geocode.php on line 25
So I need another way to do the HTTP Request.
Sure HTTP extension is installed and configured correctly?
Installation/Configuration
Installation
This » PECL extension is not bundled
with PHP.
Information for installing this PECL
extension may be found in the manual
chapter titled Installation of PECL
extensions. Additional information
such as new releases, downloads,
source files, maintainer information,
and a CHANGELOG, can be located here:
»
http://pecl.php.net/package/pecl_http.
and maybe cURl is the way to go
RAW POST using cURL in PHP
PHP4: Send XML over HTTPS/POST via cURL?
Stolen from this question. You can insert $data directly where CURLOPT_POSTFIELDS is set in place of the query string.
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.mysite.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
I also found a solution using stream_context_create(). It gives you more control over what you're sending in the POST.
Here's a blog post explaining how to do it. It lets you easily specify the exact headers and body.
http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
There is no HttpRequest::setBody() method. You should use the addPostFields function instead, using an associative array:
function do_post_request($url, $data, $optional_headers = null) {
$request = new HttpRequest($url, HttpRequest::METH_POST);
$request->setPostFields($data);
$response = $request->send();
return $response->getBody();
}
$responseBody = do_post_request('http://www.example.com',array('examplefield'=>'exampledata'));