Using PHP to get JSON data using curl - php

I am trying to use PHP to get JSON data using curl, however I am getting error 302, and am not getting data returned.
I can execute the curl at the command line using:
curl -X GET --header "Accept: application/json" "https://api.lootbox.eu/pc/us/Hydropotamus-1777/profile"
The following is the PHP script that is currently not working:
<?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
$curl = curl_init($url);
echo "A";
// Set some options - we are passing in a useragent too here
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
echo "B";
$resp = curl_exec($curl);
echo "C";
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
Below are a few environment details that may be helpful:
Windows 10
PHP 5.6.24
Chrome browser

Well I tried the following and it worked for me, getting the response:
<?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
// Initiate curl
$ch = curl_init();
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
?>
Seems you need to disable ssl verification.

A great tool to use is the RESTRequest class in PHP, https://gist.github.com/therealklanni/3440166 and then you can do:
<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
include_once("RestRequest.php");
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
$getDataRequest = new RestRequest($dataurl, 'GET');
$getDataRequest->execute();
$data = json_decode($getDataRequest->responseBody);
echo(json_encode($data));
?>

Related

php 5.3 cUrl / linux cmd cURL https

I have a problem setting up a https connection using cURL in php.
here is my php code to set up the connection.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endlocation);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CAINFO, $certificate);
curl_setopt($ch, CURLOPT_PORT, $portNumber);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
the folowing var are:
$endlocation = "https://lms.lifeline.nl/mailwebservice/inline/"
$data = json encoded data
$certificate = true path to .crt file
$portNumber = 443
when i execute the cURL my page breaks and i get a page error of the compound was reinitialized. as it happens to be i get back a false from the curl_exec.
how ever if i use this file not to directly set up a connection true php but by using linux command line on the same server:
$url = "https://lms.lifeline.nl/mailwebservice/inline";
exec("curl $url", $output, $status);
print_r($output); die;
then i do get a response back. is there somthing wrong whit my cURL exec in php format?. or is there somthing else that i need to look in to?

Passing JSON to PHP CURL [duplicate]

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

Displaying curl data, blank page

I'm trying to download json data using curl in PHP from companies house API.
Here is the example they provide that I'm trying to use:
https://developer.companieshouse.gov.uk/api/docs/company/company_number/readCompanyProfile.html#here
The example:
curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: https://api.companieshouse.gov.uk/company/{company_number}
My code
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/company/01000000");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'curl -u8yUXrestOfmyApiKey:'
));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($curl);
if(false == $result){
echo curl_error($curl);
}
curl_close($curl);
print($result);
?>
Using header:
'-u my_api_key:8yUXGgcHznjaNWnKpuKIJ7yv7HDvU_slH273GuF1'
I get 400 - bad request and with header in my code above I get nothing no errors blank page no data.
PS. There is a company with number 01000000 I've checked
You shuld add CURLOPT_USERPWD
curl_setopt($curl, CURLOPT_USERPWD, "YOUR API KEY"); #Add your api key

PHP Curl times out when command works fine

I want the following cURL command to be converted to PHP
curl -X PUT -H 'Content-Type: application/json' -d '{"on":true,"bri":255,"sat":255,"hue":20000}' http://MYSITE:PORT/api/HASH/lights/1/state
I did the following but it is just timing out.
$data_json = '{"on":true,"bri":255,"sat":255,"hue":20000}';
$url = "http://MYSITE:PORT/api/HASH/lights/1/state";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
you can set the curl timeout like so
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
you might want to increase the php timeout in php.ini too
I would try to debug the Curl request using the technique mentioned here, this should give you more information about what Curl is doing.
Also if you are willing to use a library I would recommend using Guzzle, it's well documented and makes these types of operation less painful in my experience.
<?php
use GuzzleHttp\Client;
require 'vendor/autoload.php';
$url = "http://jsonplaceholder.typicode.com/posts";
$client = new Client();
$body['title'] = "json guzzle post";
$body['body'] = "carlton";
$body['userId'] = "109109101";
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
var_dump($code);
var_dump($result);

What is cURL in PHP?

In PHP, I see the word cURL in many PHP projects. What is it? How does it work?
Reference Link: cURL
cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
In order to use PHP's cURL functions
you need to install the ยป libcurl
package. PHP requires that you use
libcurl 7.0.2-beta or higher. In PHP
4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's
7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.
// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');
cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.
CURL in PHP:
Summary:
The curl_exec command in PHP is a bridge to use curl from console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.
Warning, Danger:
curl is evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf / into your response, and then why am I dropped to a console and ls -l doesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.
Examples:
These were done on Ubuntu 12.10
Basic curl from the commandline:
el#apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240k
Then you can open up your gif in firefox:
firefox mycat.gif
Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.
cURL example get request to hit google.com, echo to the commandline:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
php> curl_exec($ch);
Which prints and dumps a mess of condensed html and javascript (from google) to the console.
cURL example put the response text into a variable:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif');
php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
php> $contents = curl_exec($ch);
php> echo $contents;
The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.
Do a curl from within a PHP file:
Put this code in a file called myphp.php:
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer)){
print "Nothing returned from url.<p>";
}
else{
print $buffer;
}
?>
Then run it via commandline:
php < myphp.php
You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.
You can do GET and POST requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs
Reminder of danger:
Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.
cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.
<?php
// Step 1
$cSession = curl_init();
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?>
Step 1: Initialize a curl session using curl_init().
Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curl using parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
Step 3: Execute the curl session using curl_exec().
Step 4: Close the curl session we have created.
Step 5: Output the return string.
public function curlCall($apiurl, $auth, $rflag)
{
$ch = curl_init($apiurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($auth == 'auth') {
curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
} else {
curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$dt = curl_exec($ch);
curl_close($ch);
if($rflag != 1) {
$dt = json_decode($dt,true);
}
return $dt;
}
This is also used for authentication. We can also set the username and password for authentication.
For more functionality, see the user manual or the following tutorial:
http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl
Firstly let us understand the concepts of curl, libcurl and PHP/cURL.
curl: A command line tool for getting or sending files using URL syntax.
libcurl: a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
PHP/cURL: The module for PHP that makes it possible for PHP programs to use libcurl.
How to use it:
step1: Initialize a curl session use curl_init().
step2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to.Append a search term "curl" using parameter "q=".Set option CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead ofprint it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
step3: Execute the curl session using curl_exec().
step4: Close the curl session we have created.
step5: Output the return string.
Make DEMO :
You will need to create two PHP files and place them into a folder that your web server can serve PHP files from. In my case I put them into /var/www/ for simplicity.
1. helloservice.php and 2. demo.php
helloservice.php is very simple and essentially just echoes back any data it gets:
<?php
// Here is the data we will be sending to the service
$some_data = array(
'message' => 'Hello World',
'name' => 'Anand'
);
$curl = curl_init();
// You can also set the URL you want to communicate with by doing this:
// $curl = curl_init('http://localhost/echoservice');
// We POST the data
curl_setopt($curl, CURLOPT_POST, 1);
// Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost/demo.php');
// Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Insert the data
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
// You can also bunch the above commands into an array if you choose using: curl_setopt_array
// Send the request
$result = curl_exec($curl);
// Get some cURL session information back
$info = curl_getinfo($curl);
echo 'content type: ' . $info['content_type'] . '<br />';
echo 'http code: ' . $info['http_code'] . '<br />';
// Free up the resources $curl is using
curl_close($curl);
echo $result;
?>
2.demo.php page, you can see the result:
<?php
print_r($_POST);
//content type: text/html; charset=UTF-8
//http code: 200
//Array ( [message] => Hello World [name] => Anand )
?>
The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script.
cURL in PHP is a bridge to use command line cURL from the php language
cURL
cURL is a way you can hit a URL from your code to get a HTML response from it.
It's used for command line cURL from the PHP language.
cURL is a library that lets you make HTTP requests in PHP.
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().
Sample Code
// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
//setting url
$url = 'http://example.com/api';
//data
$data = array("message" => "Hello World!!!");
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$output = curl_exec($ch);
if (FALSE === $output)
throw new Exception(curl_error($ch), curl_errno($ch));
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
For more information, please check -
cURL
cURL Functions
Php curl function (POST,GET,DELETE,PUT)
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, 1);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// curl_setopt($ch, CURLOPT_HEADER, 0);
$r = curl_exec($ch);
if (curl_error($ch)) {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
print_r('Error: ' . $err . ' Status: ' . $statusCode);
// Add error
$this->error = $err;
}
curl_close($ch);
return $r;
}
Php curl class (GET,POST,FILES UPLOAD, SESSIONS, SEND POST JSON, FORCE SELFSIGNED SSL/TLS):
<?php
// Php curl class
class Curl {
public $error;
function __construct() {}
function Get($url = "http://hostname.x/api.php?q=jabadoo&txt=gin", $forceSsl = false,$cookie = "", $session = true){
// $url = $url . "?". http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($session){
curl_setopt($ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
}
if($forceSsl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
}
if(!empty($cookie)){
curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
}
$info = curl_getinfo($ch);
$res = curl_exec($ch);
if (curl_error($ch)) {
$this->error = curl_error($ch);
throw new Exception($this->error);
}else{
curl_close($ch);
return $res;
}
}
function GetArray($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
$url = $url . "?". http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($session){
curl_setopt($ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
}
if($forceSsl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
}
if(!empty($cookie)){
curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
}
$info = curl_getinfo($ch);
$res = curl_exec($ch);
if (curl_error($ch)) {
$this->error = curl_error($ch);
throw new Exception($this->error);
}else{
curl_close($ch);
return $res;
}
}
function PostJson($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
$data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($session){
curl_setopt($ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
}
if($forceSsl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
}
if(!empty($cookie)){
curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer helo29dasd8asd6asnav7ffa',
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$res = curl_exec($ch);
if (curl_error($ch)) {
$this->error = curl_error($ch);
throw new Exception($this->error);
}else{
curl_close($ch);
return $res;
}
}
function Post($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $files = array('ads/ads0.jpg', 'ads/ads1.jpg'), $forceSsl = false, $cookie = "", $session = true){
foreach ($files as $k => $v) {
$f = realpath($v);
if(file_exists($f)){
$fc = new CurlFile($f, mime_content_type($f), basename($f));
$data["file[".$k."]"] = $fc;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($session){
curl_setopt($ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
}
if($forceSsl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
}
if(!empty($cookie)){
curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
}
$res = curl_exec($ch);
if (curl_error($ch)) {
$this->error = curl_error($ch);
throw new Exception($this->error);
}else{
curl_close($ch);
return $res;
}
}
}
?>
Example:
<?php
$urlget = "http://hostname.x/api.php?id=123&user=bax";
$url = "http://hostname.x/api.php";
$data = array("name" => "Max", "age" => "36");
$files = array('ads/ads0.jpg', 'ads/ads1.jpg');
$curl = new Curl();
echo $curl->Get($urlget, true, "token=12345");
echo $curl->GetArray($url, $data, true);
echo $curl->Post($url, $data, $files, true);
echo $curl->PostJson($url, $data, true);
?>
Php file: api.php
<?php
/*
$Cookie = session_get_cookie_params();
print_r($Cookie);
*/
session_set_cookie_params(9000, '/', 'hostname.x', isset($_SERVER["HTTPS"]), true);
session_start();
$_SESSION['cnt']++;
echo "Session count: " . $_SESSION['cnt']. "\r\n";
echo $json = file_get_contents('php://input');
$arr = json_decode($json, true);
echo "<pre>";
if(!empty($json)){ print_r($arr); }
if(!empty($_GET)){ print_r($_GET); }
if(!empty($_POST)){ print_r($_POST); }
if(!empty($_FILES)){ print_r($_FILES); }
// request headers
print_r(getallheaders());
print_r(apache_response_headers());
// Fetch a list of headers to be sent.
// print_r(headers_list());
?>

Categories