Accessing the SPtrans API, authorization failing on information requests - php

I'm trying to use the SPtrans API (http://www.sptrans.com.br/desenvolvedores/APIOlhoVivo.aspx), which is supposed to provide public transport information for the Sao Paulo (Brazil) area.
I'm trying to get in using PHP and curl.
I'm able to put in the requests and can authenticate myself (with a post request to /Login/Autenticar?token={token}. The post request returns a 'true' (and only a 'true').
(It seems that I need to put the token both as a GET and a POST.)
However, if I then put in an information (GET) request, for example to /Linha/Buscar?termosBusca={termosBusca}, I get a consistent return of "Authorization has been denied for this request." message.
You can see this (not) working at:
http://00qq.com/sptrans/index.php
Any thoughts or ideas on this would be extremely helpful.
Here's the code that picks up the data:
function getResult($accesspoint, $page, $postData, $post = true) {
$ch = curl_init();
$t = http_build_query($postData);
$url = $accesspoint.$page."?".$t;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post == true) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
$output = object_to_array(json_decode($output));
return $output;
}
Update
#chesterbr put me on the right track: I had to create, collect and store cookies upon authentication and then use those upon subsequent requests. Below is a proof of concept.
$site["sptrans"]["accesspoint"] = "http://api.olhovivo.sptrans.com.br/v0";
$site["sptrans"]["page"]["Login"] = "/Login/Autenticar";
$site["sptrans"]["page"]["Parada"] = "/Parada/Buscar";
$site["sptrans"]["page"]["Linha"] = "/Linha/Buscar";
$site["sptrans"]["token"] = ""; //This should contain your token.
error_reporting(E_ALL);
ini_set('display_errors', 1);
function object_to_array($data) {
if (is_array($data) || is_object($data)) {
$result = array();
foreach ($data as $key => $value)
$result[$key] = object_to_array($value);
return $result;
}
return $data;
}
function getResult($accesspoint, $page, $postData, $cookie, $post = true) {
$ch = curl_init();
$t = http_build_query($postData);
$url = $accesspoint.$page."?".$t;
// print $url."<br />";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
// curl_setopt($ch, CURLOPT_COOKIESESSION, true);
if ($post == true) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
$output = object_to_array(json_decode($output));
return $output;
}
//Create a cookie for the duration of the page.
$ckfile = tempnam ("cache/cookies", "spt.");
print "Authentication<br />";
$postData["token"] = $site["sptrans"]["token"];
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Login"], $postData, $ckfile);
print_r ($output);
unset($postData);
print "<hr />";
print "Linha<br />";
$postData["termosBusca"] = "8000";
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Linha"], $postData, $ckfile, false);
print_r ($output);
unset($postData);
print "<hr />";
print "Parada<br />";
$postData["termosBusca"] = "Afonso";
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Parada"], $postData, $ckfile, false);
print_r ($output);
unset($postData);
print "<hr />";
//Delete the cookie
unlink($ckfile);
You can see this work at http://00qq.com/sptrans/index.php

The API requires you to store the cookies from the authentication call and include them in subsequent ones (otherwise, the server can't know those calls belong to the same session, since HTTP is stateless by default).
You can make that in PHP by configuring the cURL library as described in: https://stackoverflow.com/a/12885587. See also http://www.php.net/manual/en/function.curl-setopt.php for more information on such options (search for "COOKIE" options).

Related

My API request keeps using up 25 requests for no apparent reason

My request functions from PUBG official API
<?php
function getProfile($profile, $div){
$pubgapikey = 'xxxxxxxxxxxxx';
$id = getID($profile);
$url = "https://api.pubg.com/shards/pc-na/players/$id/seasons/$div";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
if($json["data"]["type"] == "playerSeason"){
return $json["data"]["attributes"];
}else {
return false;
}
}
function getID($name){
$pubgapikey = 'xxxxxxxxxxxxxxxxxxx';
$url = "https://api.pubg.com/shards/pc-na/players?filter[playerNames]=$name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
return $json["data"][0]["id"];
}
So That's my function for requesting the data. I'll include the ways I call this.
// My index.php file (All requests go through here)
$page = explode("/", trim($_SERVER["REQUEST_URI"], "/"));
switch($page[0]){
case "profile":
require("controllers/search_controller.php");
$data = getProfile($page[1], "division.bro.official.2018-09");
if($data != false){
include("pages/profile.php");
}else{
include("pages/home.php");
echo '<script> document.getElementById("error").innerHTML = "Cannot find user. Remember To Be Capital Sensitive!"; </script>';
}
break;
}
I know that I'm using a really dumb way to include pages and what not but I don't wanna use or build my own php framework atm and this works just fine for what I'm doing
// Here is my php for calling the function
<?php
if (isset($_POST['username'])) {
$user = $_POST['username'];
if($user != ""){
header("Location: http://www.statstreak.us/profile/$user");
die();
}
}
?>
That's pretty much it. The form is just a basic html form.
For some reason this keeps using up my 25 requests/minute that I got from PUBG which is annoying as I can't find a reason why it would use up more than 2 requests per user

Handle TLSv1.2 connection with CURL

I am trying to automate the configuration of x IP cameras from their embbeded web server (Self Signed Certificates). So if you try to connect to a camera through a browser in a normal way (no script), you'll have to add an exception, works fine.
I want to automate this, and all my scripts PHP are ran in a Powershell CLI.
I have the following PHP script :
<?php
include('C:\wamp64\bin\php\php7.0.10\run\Librairie\LIB_parse.php');
include('C:\wamp64\bin\php\php7.0.10\run\Librairie\LIB_http.php');
include('C:\wamp64\bin\php\php7.0.10\run\Librairie\LIB_resolve_addresses.php');
$TableauIP = fopen('C:\wamp64\bin\php\php7.0.10\run\x\Ipcamera.txt', 'r');
$count = 0;
while (($URLcamera = fgets($TableauIP, 4096)) !== false){
$IP_unparsed = $URLcamera;
$Ipcamera = return_between($IP_unparsed, "//", "/", EXCL);
echo("Automatic configuration for : ".$Ipcamera."\n");
echo("...............\n\n");
echo("Downloading page : ".$IP_unparsed."\n\n");
$web_page =http_get($IP_unparsed, $ref = "");
echo "ERROR \n";
var_dump($web_page['ERROR']);
$head_section = return_between($string=$web_page['FILE'], $start="<head>", $end="</head>", $type=EXCL);
$meta_tag_array = parse_array($head_section, $beg_tag="<meta", $close_tag=">");
for($xx=0; $xx<count($meta_tag_array); $xx++){
echo $meta_tag_array[$xx]."\n";
}
for($xx=0; $xx<count($meta_tag_array); $xx++){
$meta_attribute = get_attribute($meta_tag_array[$xx], $attribute="http-equiv");
if(strtolower($meta_attribute)=="refresh"){
$new_page = return_between($meta_tag_array[$xx], $start="URL", $end=">", $type=EXCL);
$new_page = trim(str_replace("", "", $new_page));
$new_page = str_replace("=", "", $new_page);
$new_page = str_replace("\"", "", $new_page);
$new_page = resolve_address($new_page, $IP_unparsed);
}
break;
}
echo "HTML Head redirection detected<br>\n\n";
echo "Redirect page = ".$new_page."\n";
$web_page2 = http_get($new_page, $ref = "");
//$web_page = http_get($IP_unparsed.'/login.cs', $ref = "");
echo "FILE CONTENT \n";
var_dump($web_page2['FILE']);
echo "FILE ERROR \n";
var_dump($web_page2['ERROR']);
// for($xx=0; $xx<count($web_page); $xx++){
// echo($web_page[$xx]);
// }
// echo "ERROR \n";
// var_dump($new_page['ERROR']);
//*******************************
// $web_page = file($new_page);
// for($xx = 0; $xx < count($web_page); $xx++)
// echo $web_page[$xx];
//********************************
// $file_handle = fopen($new_page, "r");
// while (!feof($file_handle))
// {
// echo fgets($file_handle, 4096);
// }
// fclose($file_handle);
$count++;
}
?>
(I left the comments, I've tried different way to display the webpage)
As you can see, I am using the engine WampServer_x64 on a basic Windows 7.
I'm following a redirection to the https://x.x.x.x/login.cs page.
The important part is the download of webpage2.
Here the LIB_parse library (just necessary lines), wrapping curl options in PHP functions :
function http_get($target, $ref)
{
return http($target, $ref, $method="GET", $data_array="", EXCL_HEAD);
}
function http($target, $ref, $method, $data_array, $incl_head)
{
# Initialize PHP/CURL handle
$ch = curl_init();
# Prcess data, if presented
if(is_array($data_array))
{
# Convert data array into a query string (ie animal=dog&sport=baseball)
foreach ($data_array as $key => $value)
{
if(strlen(trim($value))>0)
$temp_string[] = $key . "=" . urlencode($value);
else
$temp_string[] = $key;
}
$query_string = join('&', $temp_string);
}
# HEAD method configuration
if($method == HEAD)
{
curl_setopt($ch, CURLOPT_HEADER, TRUE); // No http head
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // Return body
}
else
{
# GET method configuration
if($method == GET)
{
if(isset($query_string))
$target = $target . "?" . $query_string;
curl_setopt ($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt ($ch, CURLOPT_POST, FALSE);
}
# POST method configuration
if($method == POST)
{
if(isset($query_string))
curl_setopt ($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt ($ch, CURLOPT_POST, TRUE);
curl_setopt ($ch, CURLOPT_HTTPGET, FALSE);
}
curl_setopt($ch, CURLOPT_HEADER, $incl_head); // Include head as needed
curl_setopt($ch, CURLOPT_NOBODY, FALSE); // Return body
}
curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); // Cookie management.
curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT); // Timeout
curl_setopt($ch, CURLOPT_USERAGENT, WEBBOT_NAME); // Webbot name
curl_setopt($ch, CURLOPT_URL, $target); // Target site
curl_setopt($ch, CURLOPT_REFERER, $ref); // Referer value
curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
# Create return array
$return_array['FILE'] = curl_exec($ch);
$return_array['STATUS'] = curl_getinfo($ch);
$return_array['ERROR'] = curl_error($ch);
# Close PHP/CURL handle
curl_close($ch);
# Return results
return $return_array;
}
I do not know how to handle the TLS connection with cURL. I've been trying for hours with different stuff .. I have this issue : encrypted alert :
whireshark capture TCP and TLS exchange
I've add this line to the original library :
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
I can't get the web page.
Apparently, the SSL version is 1.0.2h.
I have tried many different things .. With many different error types, but always around the SSL certificate stuff..
I have no more ideas where to look..
If you guys can give me a trail ! That would be nice

PHP - echo json off url

I am trying to echo json of of a url. I can't figure out how to do it. I have tried many things. Can someone tell me why my code is not functioning properly? No json gets echoed to the screen. Thanks! Here is the link http://www.eastbay.com/shoppingcart/gateway?action=requestKey&_=
<?php
$raw_json = file_get_contents('http://www.eastbay.com/shoppingcart/gateway?action=requestKey&_=');
$json_array = json_decode($raw_json, true);
echo $json_array;
?>
Its not very pretty, you could put this in a loop but it wil get you started, I hope. Only thing you need to do is change the path where you want to store the cookies, it must be an absolute path.
<?php
$cookies = 'C:/folder/folder..../cookies.txt'; //use a absolute path
//Part 1 to get the cookies
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://www.eastbay.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies); // Send Cookies.
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies); // Receive Cookies.
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
//part 2 to get the json
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://www.eastbay.com/shoppingcart/gateway?action=requestKey&_=");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies); // Send Cookies.
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies); // Receive Cookies.
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// Decoding the json in to an array
$decoded = json_decode($output, true);
//using the array to get the data
echo "RequestKey: " . $decoded['data']['RequestKey'] . "<br>";
echo "Success: ". $decoded['success'] . "<br>";
//foreach loop because its an array which hold the errors, it wont output anything because there are no errors.
foreach($decoded['errors'] AS $error){
echo "Error: " . $error . "<br>";
}
?>

How to read CURL POST on remote server?

This is my cURL POST function:
public function curlPost($url, $data)
{
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
$this->curlPost('remoteServer', array(data));
How do I read the POST on the remote server?
The remote server is using PHP... but what var in $_POST[] should I read
for e.g:- $_POST['fields'] or $_POST['result']
You code works but i'll advice you to add 2 other things
A. CURLOPT_FOLLOWLOCATION because of HTTP 302
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
B. return in case you need to output the result
return $result ;
Example
function curlPost($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
print(curlPost("http://yahoo.com", array()));
Another Example
print(curlPost("http://your_SITE", array("greeting"=>"Hello World")));
To read your post you can use
print($_REQUEST['greeting']);
or
print($_POST['greeting']);
as a normal POST request ... all data posted can be found in $_POST ... except files of course :) add an &action=request1 for example to URL
if ($_GET['action'] == 'request1') {
print_r ($_POST);
}
EDIT: To see the POST vars use the folowing in your POST handler file
if ($_GET['action'] == 'request1') {
ob_start();
print_r($_POST);
$contents = ob_get_contents();
ob_end_clean();
error_log($contents, 3, 'log.txt' );
}

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