is there another way to do this HTTP request in php? - php

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

Related

Consuming cURL in restful codeigniter

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

Curl is returning a string

I'm using curl to get my values from a site name PKNiC
My code is:
function _isCurl() {
return function_exists('curl_version');
}
if (_iscurl()) {
//curl is enabled
$url = "https://pk6.pknic.net.pk/pk5/lookup.PK?name=cat.com.pk&jsonp=?";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
var_dump($output);
// Curl operations finished
} else {
echo "CURL is disabled";
}
Now when I run this program it returns a string to me with whole page print on it as a single string.
I need registrant name, expiry date, create date, contacts. How do I get those things? I have no idea how it works and it just provide me a single string when I use var_dump or print_r or any thing to view it. How to get the record of my choice?
Use a DOM Crawler, like this one: http://symfony.com/doc/current/components/dom_crawler.html.
Then you can get the registrant name like this:
use Symfony\Component\DomCrawler\Crawler;
$crawler = new Crawler($htmlFromCurl);
$crawler = $crawler->filter('.whitebox tr:nth-child(3) td:last-child');
Filtering is even easier if you have the CssSelector component
installed. This allows you to use jQuery-like selectors to traverse.
You can install the Dom Crawler without using the whole framework
composer require symfony/dom-crawler

How to use GET in PHP with OneNote API?

I've got the OneNote API PHP Sample (thanks jamescro!) working with all the POST examples, but there's no GET example and I haven't managed to put together code of my own that works. Here's what I've tried without success:
// Use page ID returned by POST
$pageID = '/0-1bf269c43a694dd3aaa7229631469712!93-240BD74C83900C17!600';
$initUrl = URL . $pageID;
$cookieValues = parseQueryString(#$_COOKIE['wl_auth']);
$encodedAccessToken = rawurlencode(#$cookieValues['access_token']);
$ch = curl_init($initUrl);
curl_setopt($ch, CURLOPT_URL, $initUrl); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (! $response === false) {
curl_close($ch);
echo '<i>Response</i>: '. htmlspecialchars($response);
}
else {
$info = curl_getinfo($ch);
curl_close($ch);
echo '<i>Error</i>: ';
echo var_export($info);
}
It just returns 'Error' with an info dump. What am I doing wrong?
without information on the specific error I'm not sure what issue you are hitting. Try looking at the PHP Wordpress plugin here: https://github.com/wp-plugins/onenote-publisher/blob/master/api-proxy.php
look at what is sent to wp_remote_get - there are necessary headers that are needed.
Also make sure you have the scope "office.onenote" when you request the access token.
If you need more help, please add information about the specific URL you are attempting to call, as well as the contents of your headers. If you have any errors, please include the output.
Solved:
As Jay Ongg pointed out, "there are necessary headers that are needed".
After adding more detailed error checking and getting a 401 response code, I added:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:text/html\r\n".
"Authorization: Bearer ".$encodedAccessToken));
... and could access the requested page.

How to call posts from PHP

I have a website, that uses WP Super Cache plugin. I need to recycle cache once a day and then I need to call 5 posts (URL adresses) so WP Super Cache put these posts into cache again (caching is quite time consuming so I'd like to have it precached before users come so they dont have to wait).
On my hosting I can use a CRON but only for 1 call/hour. And I need to call 5 different URL's at once.
Is it possible to do that? Maybe create one HTML page with these 5 posts in iframe? Will something like that work?
Edit: Shell is not available, so I have to use PHP scripting.
The easiest way to do it in PHP is to use file_get_contents() (fopen() also works), if the HTTP stream wrapper is enabled on your server:
<?php
$postUrls = array(
'http://my.site.here/post1',
'http://my.site.here/post2',
'http://my.site.here/post3',
'http://my.site.here/post4',
'http://my.site.here/post5',
);
foreach ($postUrls as $url) {
// Get the post as an user will do it
$text = file_get_contents();
// Here you can check if the request was successful
// For example, use strpos() or regex to find a piece of text you expect
// to find in the post
// Replace 'copyright bla, bla, bla' with a piece of text you display
// in the footer of your site
if (strpos($text, 'copyright bla, bla, bla') === FALSE) {
echo('Retrieval of '.$url." failed.\n");
}
}
If file_get_contents() fails to open the URLs on your server (some ISP restrict this behaviour) you can try to use curl:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_CONNECTTIMEOUT => 30, // timeout in seconds
CURLOPT_RETURNTRANSFER => TRUE, // tell curl to return the page content instead of just TRUE/FALSE
));
$text = curl_exec($ch);
curl_close($ch);
return $text;
}
Then use the function curl_get_contents() listed above instead of file_get_contents().
An example using PHP without building a cURL request.
Using PHP's shell exec, you can have an extremely light function like so :
$siteList = array("http://url1", "http://url2", "http://url3", "http://url4", "http://url5");
foreach ($siteList as &$site) {
$request = shell_exec('wget '.$site);
}
Now of course this is not the most concise answer and not always a good solution also, if you actually want anything from the response you will have to work with it a different way to cURLbut its a low impact option.
Thanks to Arkascha tip I created a PHP page that I call from CRON. This page contains simple function using cURL:
function cache_it($Url){
if (!function_exists('curl_init')){
die('No cURL, sorry!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 50); //higher timeout needed for cache to load
curl_exec($ch); //dont need it as output, otherwise $output = curl_exec($ch);
curl_close($ch);
}
cache_it('http://www.mywebsite.com/url1');
cache_it('http://www.mywebsite.com/url2');
cache_it('http://www.mywebsite.com/url3');
cache_it('http://www.mywebsite.com/url4');

Callback from API not happening after posting parameters to API URL from server side

API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.

Categories