how to run: url from php = run from browser - php

How to run url from php script in the same way (exactly the same behaviour) as in browser when i run url from address bar. I mean with the same header data, cookies and additional data which browser send. How to add this data in php.
I need this cause when I logged in, answers from this 2 cases are not the same:
in browser I still logged in and this is correct
from php run I am logged OUT - not correct
I've tried file_get_contents nad curl (from here) but it doesn't work properly - response is still different.
I'm calling http://127.0.0.1/check.html and here is function check:
public function check(){
echo 'begin';
// $total_rows = file_get_contents('https://127.0.0.1:8443/example.html?shopId=121');
$total_rows = $this->getUrl('https://127.0.0.1:8443/example.html', '121');
print_r($total_rows);
echo 'end';
}
function getUrl($url, $shopId ='') {
$post = 'shopId=' . $shopId;
$ch = curl_init();
$cookie_string="";
foreach( $_COOKIE as $key => $value ) {
$cookie_string .= "$key=$value;";
};
$cookie_string .= "JSESSIONIDSSO=66025D1CC9EF39ED7F5DB024B6026C61";
// echo $cookie_string;;
$ch = curl_init();
curl_setopt($ch,CURLOPT_COOKIE, $cookie_string);
// curl_setopt($ch, CURLOPT_PORT, 8443);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/../../files/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Secure Content-Type: text/html; charset=UTF-8"));
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: 127.0.0.1:8443'));
$ret = curl_exec($ch);
curl_error ($ch );
curl_close($ch);
return $ret;
}

Try it:
http://www.lastcraft.com/browser_documentation.php
Or that:
http://sourceforge.net/projects/snoopy/
Or that:
php curl: how can i emulate a get request exactly like a web browser?
Hope help

You can execute the cron job using your PHP script to execute the other script.

Related

What on my PHP Curl call do I need to add to read a response's custom headers?

I tried a few several ways to read the responses custom header but have not been able to. I know the response I get is served by nginx and the custom header names start with X-......
$endpoint = 'url here';
$ch = curl_init( $endpoint );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'cbFunc');
$result = curl_exec($ch);
print_r( curl_getinfo($ch ) );
The PHP manual is an excellent reference guide an a good starting point when you run into problems like this.
CURLOPT_HEADERFUNCTION [Set value to] A callback accepting five parameters.
hence
log_headers('init');
$endpoint = 'url here';
$ch = curl_init( $endpoint );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'log_headers');
$result = curl_exec($ch);
$headers=log_headers();
print_r($headers);
function log_headers($ch=false, $headers=false)
{
static $hdrs;
if (is_array($hrs) && $ch===$headers===false) {
return $hdrs[];
} elseif ($ch==='init') {
$hdrs=array();
return 0;
}
$hdrs[]=$headers;
return strlen($headers);
}

cURL can't get content of specific website

I try to get the content of this website with cURL
www.mytischtennis.de/public/
but it gets no body response. With many other websites the code works:
<?php
$output = grabPage(
"http://www.mytischtennis.de/public/"
//"http://www.spiegel.de" //this page and many other pages are working
);
if (is_array($output)) {
var_dump($output);
} else {
echo $output;
}
function grabPage($url)
{
$ch = curl_init();
$cookiePath= dirname(__FILE__) . "\cookie.txt";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 50);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_COOKIE, 'CFID=c7a592d8-5798-4471-9af4-4c4d954d03cd; cfid=c7a592d8-5798-4471-9af4-4c4d954d03cd; MYTT_COOKIESOK=1; CFTOKEN0=; cftoken=0; SRV=74');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiePath);
$fpErrors = fopen(dirname(__FILE__) . '\errorlog.txt', 'w');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fpErrors);
curl_setopt($ch, CURLOPT_URL, $url);
ob_start();
$curl_exec = curl_exec($ch);
ob_end_clean();
if ($curl_exec === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Success';
}
var_dump(curl_getinfo($ch));
curl_close($ch);
return $curl_exec;
}
I tried to read a fiddler/wireshark dump of a browser request to this website. But I can't figure out which of that many requests and which parameters are necessary to get the content.
You can test cURL with the url www.mytischtennis.de/public/ also on this website:
http://onlinecurl.com/
You need to accept gzip encoding in the response by sending the appropriate HTTP header in the request:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip'));
Now your answer from the server might or might not be gziped. The proper way to check that is to interpret the Content-Encoding HTTP header in the response. But you can also do it quick and dirty like this:
$content = #gzdecode($curl_exec);
return $content !== false ? $content : $curl_exec;

Getting executed URL from CURL

I have a Affiliate URL Like http://track.abc.com/?affid=1234
open this link will go to http://www.abc.com
now i want to execute the http://track.abc.com/?affid=1234 Using CURL
and now how i can Get http://www.abc.com
with Curl ?
If you want cURL to follow redirect headers from the responses it receives, you need to set that option with:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
You may also want to limit the number of redirects it follows using:
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
So you'd using something similar to this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
Edit: Question wasn't exactly clear but from the comment below, if you want to get the redirect location, you need to get the headers from cURL and parse them for the Location header:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
This will give you the headers returned by the server in $data, simply parse through them to get the location header and you'll get your result. This question shows you how to do that.
I wrote a function that will extract any header from a cURL header response.
function getHeader($headerString, $key) {
preg_match('#\s\b' . $key . '\b:\s.*\s#', $headerString, $header);
return substr($header[0], strlen($key) + 3, -2);
}
In this case, you're looking for the value of the header Location. I tested the function by retrieving headers from a TinyURL, that redirects to http://google.se, using cURL.
$url = "http://tinyurl.com/dtrkv";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$location = getHeader($data, 'Location');
var_dump($location);
Output from the var_dump.
string(16) "http://google.se"

parsing response POST data from curl_exec call

I have the following code block which connects out to a secure service (payment transaction gateway), passes in some fields ($postData) and receives a response ($returnValue).
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://secure.service.com/data');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
if ($returnValue = curl_exec($ch))
{
$error = curl_error($ch);
}
When I display the contents of $returnValue ... they show as follows:
HTTP/1.0 200 OK Approved Date: Wed, 10 Aug 2011 09:24:15 GMT
Connection: close Content-Type: application/x-www-form-urlencoded
Content-Length: 182
avs_code=X&cvv2_code=P&status_code=1&processor=TEST&auth_code=999999&settle_amount=2000&settle_currency=USD&trans_id=120741127516&auth_msg=TEST+APPROVED&auth_date=2011-08-10+09:24:15
Is there a method or CURL call that breaks apart this result string into its component parts? or is that something I need to write myself? I need to get the response code (200), the approval/decline part (Approved) and the query string (avs_code ....). I tried looking through the curl_getinfo but that is only getting me the HTTP Response code, not the approval/decline or the query string values.
I'm a novice at PHP so please let me know if I'm missing an obvious method call or CURL parameter.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE, "");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$header=substr($result,0,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
$body=substr($result,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
curl_close($ch);
Than use something like preg_match_all("/Set-Cookie: (.*?)=(.*?);/i",$header,$res);
See preg_match_all manual
I suggest you look at http://php.net/manual/en/function.http-parse-headers.php manual, if you don't want to install PECL pecl_http - there are usefull user comments. For example:
function http_parse_headers($header) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach ($fields as $field) {
if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if (isset($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
return $retVal;
}
You can parse cookies and post values with http://php.net/manual/ru/function.http-parse-cookie.php (or functions in comments) and http://php.net/manual/en/function.parse-str.php . HTTP protocol is rather transparent.

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