In this process cURL send file to any web server along with other params. Check it out below code: |
Assuming that you're using PHP 5.5+, you need to use CURLFile for uploading your file: |
<?php $headers = array( 'Authorization: Bearer Token Value', 'Content-type: multipart/form-data' ); $url = "https://example.com/api/v1/import/uploadfile"; $post_data = array( "file1" => new CURLFile("/var/www/files/file1.csv", 'text/csv', 'File1.csv'), "file2" => new CURLFile("/var/www/files/file1.pdf", 'application.pdf', 'File1.pdf'), "param1" => "Test" ); $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_VERBOSE, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); |
Showing posts with label curl. Show all posts
Showing posts with label curl. Show all posts
Sunday, October 8, 2023
How to Send files via POST with cURL and PHP (Example)
Friday, June 22, 2018
Header only retrieval in php via curl | PHP CURL get content type from URL | PHP CURL retrieve headers information from URL
Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata. |
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers: |
The PHP code for the CURL request would look something like this: |
$agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 X-Client-Data: CIa2yQEIpLbJAQjBtskBCKmdygEIqKPKARiSo8oB"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_FILETIME, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_USERAGENT, $agent); $header = curl_exec($curl); $info = curl_getinfo($curl); curl_close($curl); |
Which will output as below: |
HTTP/1.1 200 OK Date: Fri, 22 Jun 2018 06:47:27 GMT Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 Last-Modified: Sun, 11 Feb 2018 16:39:41 GMT ETag: "5ae6f-564f2687e28f8" Accept-Ranges: bytes Content-Length: 372335 Content-Type: application/pdf Array ( [url] => http://localhost/text-finder/download.pdf [content_type] => application/pdf [http_code] => 200 [header_size] => 265 [request_size] => 258 [filetime] => 1518367181 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.016 [namelookup_time] => 0.016 [connect_time] => 0.016 [pretransfer_time] => 0.016 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 372335 [upload_content_length] => -1 [starttransfer_time] => 0.016 [redirect_time] => 0 [redirect_url] => [primary_ip] => ::1 [certinfo] => Array ( ) [primary_port] => 80 [local_ip] => ::1 [local_port] => 51877 ) HTTP/1.1 200 OK Date: Fri, 22 Jun 2018 06:48:11 GMT Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 Last-Modified: Fri, 22 Jun 2018 04:18:28 GMT ETag: "92-56f3352eebe85" Accept-Ranges: bytes Content-Length: 146 Content-Type: text/html Array ( [url] => http://localhost/text-finder/test2.html [content_type] => text/html [http_code] => 200 [header_size] => 253 [request_size] => 256 [filetime] => 1529641108 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.015 [namelookup_time] => 1.0E-6 [connect_time] => 0.015 [pretransfer_time] => 0.015 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 146 [upload_content_length] => -1 [starttransfer_time] => 0.015 [redirect_time] => 0 [redirect_url] => [primary_ip] => ::1 [certinfo] => Array ( ) [primary_port] => 80 [local_ip] => ::1 [local_port] => 51944 ) |
Thursday, December 19, 2013
SOAP request in PHP with CURL
Php code to soap action via curl:
<?php $xml = '<?xml version="1.0" encoding="utf-8"?>'. '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'. ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"'. ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'. '<soap:Body>'. '<GetShirtInfo xmlns="http://api.soap.website.com/WSDL_SERVICE/">'. '<ItemId>15</ItemId>'. '</GetShirtInfo>'. '</soap:Body>'. '</soap:Envelope>'; $url = "https://api.soap.website.com/soap.asmx?wsdl"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $headers = array(); array_push($headers, "Content-Type: text/xml; charset=utf-8"); array_push($headers, "Accept: text/xml"); array_push($headers, "Cache-Control: no-cache"); array_push($headers, "Pragma: no-cache"); array_push($headers, "SOAPAction: http://api.soap.website.com/WSDL_SERVICE/GetShirtInfo"); if($xml != null) { curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml"); array_push($headers, "Content-Length: " . strlen($xml)); } curl_setopt($ch, CURLOPT_USERPWD, "user_name:password"); /* If required */ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); ?>
And output would be like this:
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <ShirtInfoResponse xmlns="http://api.soap.website.com/WSDL_SERVICE/"> <ShirtInfo> <ItemId>15</ItemId> <ItemName>Some Item Name</ItemName> <ItemPrice>658.7</ItemPrice> <ItemCurrency>AUD</ItemCurrency> </ShirtInfo> </ShirtInfoResponse> </soap:Body> </soap:Envelope>
Sunday, August 25, 2013
Call and store response from a url using bash script
#!/bin/bash
## generate random string of length 18
function randpass
{
echo `</dev/urandom tr -dc A-Za-z0-9 | head -c18`
}
## get current time stamp
timestamp=$(date +%s);
sessionId="$(randpass).$(randpass).$timestamp";
privateKey='test';
## get substring of sessionId from 0 to 5 characters.
sessionIdPart=${sessionId:0:5};
systemKeyPart=${privateKey:0:4};
## reverse string and store in a variable
word="$(echo "$sessionIdPart" | rev)$(echo "$systemKeyPart" | rev)";
word="$word$sessionId$privateKey";
## make a string md5
hash=`echo -n "$word" | md5sum | awk '{print $1}'`;
hash=${hash:0:10};
breakRest="securedSessionKey=$sessionId&securedHash=$hash";
saveFile=$(date +"%Y-%m-%d %T");
## saveFile would be '2013-08-25 19:23:28'
## calling a url using 'curl' and store response to some file.
curl -s -L
-o "$
saveFile
.html"
"http://domain.com/getStudent?$breakRest" &## "&" sign at the end means run curl in background.
exit 1;
Thursday, August 22, 2013
Asynchronous cURL Requests
A possibly underused technique available to PHP developers is the ability to spawn a background PHP script without JavaScript. All you need to do this is the cURL library and a few lines of code. Let me explain, suppose you have a script that is going to take minutes (or longer) to run, you don’t want to sit looking at a blank screen, and your users certainly won’t! In this kind of scenario you can separate out that logic to a background file and leave your view free for other things, perhaps to query the database to see how the background process is doing?
All you need to do to set this off is use the following code (entering your own url):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
curl_close($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
curl_close($ch);
There is an irritating 1 second delay for this to finish, but this cannot be helped (so far as I am aware!)
Remember to be careful with this technique (especially if you turn off script timeout etc) and build in a control to stop the script should you need to (database query every minute? or a lock file?)
Enjoy!
Update
It has been pointed out to me that on modern systems (cURL 7.16.2 or higher and PHP 5.2.3 or above) you can use a millisecond option to reduce the delay effectively to zero.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
curl_close($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
curl_close($ch);
Monday, August 19, 2013
Downloading a Remote File With cURL and PHP
cURL is a great tool to help you connect to remote web sites, making it easy to post forms, retrieve web pages, or even to download files. In this PhpRiot Snippet I'll show you how you can download a file straight to disk using cURL.
Note: To simplify our key points in this article we don't perform any error checking on the cURL requests. You should always do so; the
curl_getinfo
function is extremely useful for this.
If you use basic options when executing a cURL request, the returned data will be output directly. If instead you want to assign the response to a PHP variable you would specify the
CURLOPT_RETURNTRANSFER
option.
You can then read the response and write it to disk, as shown in the following listing. The
$path
variable is the location on the server where you want to write the file.<?php
set_time_limit(0);
$url = 'http://www.example.com/a-large-file.zip'; $path = '/path/to/a-large-file.zip'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); curl_close($ch); file_put_contents($path, $data); ?>
There is however a problem with this code. If the file you're downloading is quite large, the entire contents must be read into memory before being written to disk. Doing so can result in your script breaking down due to exceeding the memory limit.
Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.
Therefore, you should let cURL do the hard work by passing to it a writable file stream. You can do this using the
CURLOPT_FILE
option.
Note: Because we'll be writing to a file you no longer specify the
CURLOPT_RETURNTRANSFER
option.
To do this you must first create a new file pointer using fopen(). Next we pass this file pointer to cURL and perform the request. Finally, we close the file pointer.
<?php
set_time_limit(0); $url = 'http://www.example.com/a-large-file.zip'; $path = '/path/to/a-large-file.zip'; $fp = fopen($path, 'w'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp); $data = curl_exec($ch); curl_close($ch); fclose($fp); ?>
That's all there is to it. You can now download files without worrying about exceeding PHP's memory limit.
Tuesday, August 13, 2013
PHP QR Code Generator Class
Here is the PHP QR code generator class that creates PNG QR code images from text. The class will create various QR code types like text, URLs, emails, etc:
BarcodeQR.zip.
Requirements: PHP Web server and cURL Library (client URL).
The PHP QR code class will create a PNG QR code image or save a PNG QR code image file, here is an example:
You can also save the QR code PNG image like this:
BarcodeQR.zip.
Requirements: PHP Web server and cURL Library (client URL).
The PHP QR code class will create a PNG QR code image or save a PNG QR code image file, here is an example:
// include BarcodeQR class
include "BarcodeQR.php";
// set BarcodeQR object
$qr = new BarcodeQR();
// create URL QR code
$qr->url("Pritom K Mondal");
// display new QR code image
$qr->draw();
This example will create and display this QR code image:You can also save the QR code PNG image like this:
// save new QR code image (size 150x150)
$qr->draw(150, "tmp/qr-code.png");
Other QR code types the class will create:// bookmark
$qr->bookmark("title", "url");
// contact
$qr->contact("name", "address", "phone", "email");
// content
$qr->content("type", "size", "content");
// email
$qr->email("email", "subject", "message");
// geo location
$qr->geo("lat", "lon", "height");
// phone
$qr->phone("phone");
// sms
$qr->sms("phone", "text");
// text
$qr->text("text");
// URL
$qr->url("url");
// wifi connection
$qr->wifi("type", "ssid", "password");
http://www.shayanderson.com/php/php-qr-code-generator-class.htmThursday, April 25, 2013
cURL in PHP to access HTTPS (SSL/TLS) protected sites
The problem
From PHP, you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP, FTP, LDAP.
If you simply try to access a HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. Say you have the following code: (Error handling omitted for brevity)
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
If
$url
points toward an HTTPS resource, you’re likely to encounter an error like the one below:Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.
The quick fix
There are two ways to solve this problem. Firstly, we can simply configure cURL to accept any server(peer) certificate.
This isn’t optimal from a security point of view, but if you’re not passing sensitive information back and forth, this is probably alright.
Simply add the following line before calling
curl_exec()
:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Friday, March 1, 2013
php authentication basic username and password
index.php
<?php
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { header('WWW-Authenticate: Basic realm="Need Authentication"'); header('HTTP/1.0 401 Unauthorized'); echo 'Need Authentication'; exit; } else { if(empty($_SERVER["PHP_AUTH_USER"]) || $_SERVER["PHP_AUTH_USER"] != "apm" || empty($_SERVER["PHP_AUTH_PW"]) || $_SERVER["PHP_AUTH_PW"] != "gh3412") { header('WWW-Authenticate: Basic realm="Authentication Error"'); header('HTTP/1.0 401 Unauthorized'); echo 'Authentication Error'; exit; } } ?>
<?php $ch = curl_init(); if(is_array($get_variables)) { $get_variables = '?' . str_replace('&','&',urldecode(http_build_query($get_variables))); } else { $get_variables = null; } curl_setopt($ch, CURLOPT_URL, "http://dom.com/index.php" . $get_variables); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //CURL doesn't like google's cert curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'adm:pwd3012'); $headers[0] = "Authorization: Basic " . base64_encode("apm:gh3412"); if($post_variables == null || !is_array($post_variables)) { $post_variables = array(); } if(is_array($post_variables)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_variables); } if(is_array($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER,$headers); } $response = curl_exec($ch); $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); ?>
Tuesday, February 26, 2013
simple class for calling a url using either curl or fopen
<?php class EmailManager { var $_server; var $_account; const client_login_url = 'https://www.google.com/accounts/ClientLogin'; function __construct($params = array()) { if(!isset($params["server"])) { throw new Exception("Server name required."); } if(!isset($params["account"])) { throw new Exception("Account name required."); } $this->_account = $params["account"]; $this->_server = $params["server"]; } protected function authenticateUser($email, $password) { $postVariables = array( 'accountType' => 'GOOGLE', 'Email' => $email, 'Passwd' => $password, 'service' => 'analytics' ); $response = $this->httpRequest(EmailManager::client_login_url, null, $postVariables); } protected function httpRequest($url, $get_variables=null, $post_variables=null, $headers=null) { $interface = null; if(function_exists('curl_exec')) { $interface = 'curl'; } else { $interface = 'fopen'; } if($interface == 'curl') { return $this->curlRequest($url, $get_variables, $post_variables, $headers); } else if($interface == 'fopen') { return $this->fOpenRequest($url, $get_variables, $post_variables, $headers); } } private function curlRequest($url, $get_variables=null, $post_variables=null, $headers=null) { $ch = curl_init(); if(is_array($get_variables)) { $get_variables = '?' . str_replace('&','&',urldecode(http_build_query($get_variables))); } else { $get_variables = null; } curl_setopt($ch, CURLOPT_URL, $url . $get_variables); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //CURL doesn't like google's cert if(is_array($post_variables)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_variables); } if(is_array($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER,$headers); } $response = curl_exec($ch); $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); return array('body'=>$response,'code'=>$code); } private function fOpenRequest($url, $get_variables=null, $post_variables=null, $headers=null) { $http_options = array('method'=>'GET','timeout'=>3); if(is_array($headers)) { $headers = implode("\r\n",$headers) . "\r\n"; } else { $headers = ''; } if(is_array($get_variables)) { $get_variables = '?' . str_replace('&','&',urldecode(http_build_query($get_variables))); } else { $get_variables = null; } if(is_array($post_variables)) { $post_variables = str_replace('&','&',urldecode(http_build_query($post_variables))); $http_options['method'] = 'POST'; $headers = "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($post_variables) . "\r\n" . $headers; $http_options['header'] = $headers; $http_options['content'] = $post_variables; } else { $post_variables = ''; $http_options['header'] = $headers; } $context = stream_context_create(array('http'=>$http_options)); $response = @file_get_contents($url . $get_variables, null, $context); return array('body'=>$response!==false?$response:'Request failed, fopen provides no further information','code'=>$response!==false?'200':'400'); } } ?>
Subscribe to:
Posts (Atom)