Send File to HTTPS URL using CURL and PHP - php

I am attempting to send a file to an Https URL with this code:
$file_to_upload = array('file_contents'=>'#'.$target_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSER, FALSE);
curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file='.$file_to_upload);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close ($ch);
echo " Server response: ".$result;
echo " Curl Error: ".$error;
But for some reason I'm getting this response:
Curl Error: Failed to open/read local data from file/application
Any advice would help thanks!
UPDATE: When I take out CURLOPT_UPLOAD, I get a response from the target server but it says that there was no file in the payload

You're passing a rather strange argument to CURLOPT_POSTFIELDS. Try something more like:
<?
$postfields = array('file' => '#' . $target_path);
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
?>
Also, you probably want CURLOPT_RETURNTRANSFER to be true, otherwise $result won't get the output, it'll instead be sent directly to the buffer/browser.
This example from php.net might be of use as well:
<?php
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>

On top of coreward's answer:
According to how to upload file using curl with php, starting from php 5.5 you need to use curl_file_create($path) instead of "#$path".
Tested: it does work.
With the # way no file gets uploaded.

Related

cURL with PHP passing data with PUT

I would like to curl thru PHP using PUT method to a remote server. And stream to a file.
My normal command would look like this :
curl http://192.168.56.180:87/app -d "data=start" -X PUT
I saw this thread on SO .
EDIT :
Using Vitaly and Pedro Lobito comments I changed my code to :
$out_file = "logging.log";
$fp = fopen($out_file, "w");
$ch = curl_init();
$urlserver='http://192.168.56.180:87/app';
$data = array('data=start');
$ch = curl_init($urlserver);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_exec($ch);
curl_close($ch);
fclose($fp);
But still not Ok.
When My I have this response using curl :
192.168.56.154 - - [04/May/2017 17:14:55] "PUT /app HTTP/1.1" 200 -
And I have this response using the php above:
192.168.56.154 - - [04/May/2017 17:07:55] "PUT /app HTTP/1.1" 400 -
You're passing the POST string incorrectly
$data = array('data=start');
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
In this case, you've already built your string, so just include it
$data = 'data=start';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
http_build_query is only when you have a key => value array and need to convert it to a POST string
Why don't you save the curl output directly to a file? i.e.:
$out_file = "/path/to/file";
$fp = fopen($out_file, "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
fclose($fp);
curl_close($ch);
Note:
When you ask a question about an error, always include the error log. To enable error reporting, add error_reporting(E_ALL); ini_set('display_errors', 1); at the top of your php script.

Error when doing cURL request

This code always returns user doesn't exist from the API:
$data2 = array('user'=>$vars['mcusername'],
'pwd'=>$vars['mcpassword'],
'group'=>$postfields['group'],
'action'=>'Save');
// Connect to dvb API
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?part=userconfig&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
$data = curl_exec($ch);
curl_close($ch);
The string that works in a browser is this:
dvbapi.html?part=userconfig&user=PeterTest&pwd=obfuscated&group=1,2&disabled=0&action=Save
When you access the URL in the browser, you're performing a GET. In your cURL attempt, you're attempting to POST. This is likely the issue; the script may only accept GET.
Try using this cURL code instead:
// Gather up all the values to send to the script
$data2 = array('part' => 'userconfig',
'user' => $vars['mcusername'],
'pwd' => $vars['mcpassword'],
'group' => $postfields['group'],
'action' => 'Save');
// Generate the request URL
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?".http_build_query($data2);
// cURL the URL for a responce
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
// Show the responce
var_dump($data);
You can use http_build_query() to turn your array into a URL-encoded string to make the GET request.

cURL is not able to upload file on scribd

i want to upload a file to scribd.com using curl,
please help me guys,
i am trying this code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _'http://www.scribd.com/upload/supload');
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
$path=getcwd(); //absolute path
$post = array(
"file"=>"#".$path."/test.txt",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
you've got at least one syntax error (_ in your curlopt_url line). Have you checked for curl errors after the exec() call?
$response = curl_exec($ch);
if ($response === false) {
die(curl_error($ch));
}
as well, your comment indicates the file field's name is "file_box", but you're using just "file" as your upload field. You must match what scribd is expecting. You can't just throw a file over their way and expect it to work. You're using curl to recreate what a browser would do, which means you have to duplicate all the fields/data that gets sent when a normal browser-based upload is performed.

Diigo API -- HTTP Basic Authentication Error over CURL in PHP for HTTPS

Hi I am trying to post data Using CURL in PHP to diigo bookmarking, I have tried through API, When i executing file i got HTTP basic authentication here is my code
require_once('libs/diigo.class.php');
$diggo = new DiigoAPI("username","password");
$book = $diggo->getBookmarks();
$diggo->saveBookmarks("http://www.example.com");
public function saveBookmarks($url)
{
$attachment = array ("url" => $url, "title" => "SEnthil" , "shared" => "yes" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://secure.diigo.com/api/v2/bookmarks');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
echo $result;
curl_close ($ch);
}
Your curl doesn't have basic HTTP authentication set. You should set it up this way:
curl_setopt($curl, CURLOPT_USERPWD, $user_here . ":" . $password_here );
And the way you're doing it now the saveBookmarks function doesn't require the Diigo Class at all.

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