Upload File Via PHP Curl PUT - php

Having quite a bit of trouble PUT-ting a PDF. I've managed to get it working fine in Postman, using the code below (large code block) and appending the PDF via the body as form-data. I'm trying to replicate this in PHP now. I'm having trouble attaching the PDF though.
I've tried numerous techniques trying to attach the PDF via "CURLOPT_INFILE", "CURLOPT_POSTFIELDS" to no avail.
I create the file via:
$pdf = $_SERVER['DOCUMENT_ROOT'] . '/pdf/temp/temp.pdf';
$file = curl_file_create($pdf, 'application/pdf', 'receipt');`
or
$file = new CURLFile($pdf, 'application/pdf', 'receipt');
I've tried using:
$file = fopen($pdf, 'rb');
$file = array('file' => $file);
CURLOPT_POSTFIELDS => $file,
CURLOPT_INFILESIZE => $fileSize,
CURLOPT_INFILE => $file
No luck though.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://staging-tallie.com/v2/enterprise/ENTERPRISEID/MyReceipt/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => array(
"accept: application/json; charset=utf-8",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"token: TOKEN",
"upload-filename: receipt.pdf"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Error reads:
<?xml version="1.0" encoding="utf-8"?>
<ErrorResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseCode>400</ResponseCode>
<Message>Unable to Save the file to the Storage Service.</Message>
</ErrorResponse>

400 is an HTTP response code indicating that the request was impossible to satisfy. That, along with the accompanying message text, suggest that the PHP process does not have write access to the destination directory.

This code worked for me in order to upload a file to bluemix Cloud Object Storage. File is uploaded from temporary folder after form submit using PUT method. Don't forget to validate file mime and extension before upload.
if (is_uploaded_file($_FILES['my_file']['tmp_name'])){
$ch = curl_init();
$url = IBM_BLUEMIX_BUCKET_END_POINT.$bucket_name."/".$file_name; // give the file a unique name
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_PUT, true); //PUT REQUEST
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-amz-acl: public-read', //header required for bluemix
'Authorization: Bearer '.$access_token, // authorization for bluemix iam
'Content-Type: '.$conten_type, //application/pdf or image/jpg
'Expect: '
));
$image_or_file = fopen($_FILES['my_file']['tmp_name'], "rb");
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $image_or_file);
curl_setopt($ch, CURLOPT_INFILESIZE, $_FILES[$fieldName]['size']);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
array(
'file' =>
'#' . $_FILES['my_file']['tmp_name']
. ';filename=' . $_FILES['my_file']['name']
. ';type=' . $conten_type //application/pdf or image/jpg
));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,16);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$response = curl_exec($ch);
$headerSent = curl_getinfo($ch ); // request headers from response (check if something wrong)
curl_close ($ch);
fclose($image_or_file);
if(!$response){ // or response
// do something...
}
}else{
//File did not upload, do something ...
}

Related

Download Github Release asset file via PHP

I am using PHP Github API to list my releases. Now I need to copy an asset file to my server from the latest release.
The PHP Github API does not provide download functionality so I decided to make a cURL request directly.
This is my code atm:
<pre>
<?php
// This file is generated by Composer
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate(':mytoken', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('arminetsw', 'webstore');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['browser_download_url'];
$download_url = 'https://api.github.com/repos/arminetsw/webstore/releases/assets/:myAssetId?access_token=:mytoken';
$cliente = curl_init();
$file = fopen("webstore.zip", 'w');
curl_setopt($cliente, CURLOPT_URL, "https://api.github.com/repos/arminetsw/webstore/releases/assets/32188729?access_token=:mytoken");
curl_setopt($cliente, CURLOPT_HEADER, 'Accept: application/octet-stream');
curl_setopt($cliente, CURLOPT_USERAGENT, 'Webstore');
curl_exec($cliente);
curl_close($cliente);
fclose($file);
//$nuevo_fichero = ''
/*if (!copy($download_url, $nombre_fichero)) {
echo "Error al copiar $nombre_fichero...\n";
}*/
var_dump($release);
?>
</pre>
I only get a webstore.zip 0 bytes file with no errors.
*The repo is private.
Final working code:
<pre>
<?php
set_time_limit(0);
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('user', 'repo');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['url'];
$authorization = "access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$download_url .= "?" . $authorization;
$file = fopen($nombre_fichero, 'w');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $download_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_USERAGENT => "Webstore",
CURLOPT_FILE => $file,
CURLOPT_HTTPHEADER => [
"Accept: application/octet-stream",
"Content-Type: application/octet-stream"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
fputs($file, $response);
fclose($file);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
</pre>

How do I use Oauth2 using cURL and PHP

I can't get the folling script to work:
I'm using an api called swiftdil. Their example is as follows:
Example request:
curl -X POST https://sandbox.swiftdil.com/v1/oauth2/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-u 'your_username:your_password'
Example output:
{
"access_token":"your_access_token",
"expires_in": 3600,
"refresh_expires_in": 1800,
"refresh_token": "your_refresh_token",
"token_type": "bearer",
"not-before-policy": 0,
"session_state": "your_session_state"
}
So the url I've to submit my credentials to is https://sandbox.swiftdil.com/v1/oauth2/token
I've tried the following code:
// Api Credentials
$url = 'https://sandbox.swiftdil.com/v1/oauth2/token';
$username = "my_username";
$password = "my_password";
// Set up api environment
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" .
$password);
// Give back curl result
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($info);
print_r($curl_error);
?>
The script is giving me back the following result:
HTTP/1.1 400 Bad Request Server: nginx/1.13.8 Date: Tue, 15 May 2018 09:17:26 GMT Content-Type: text/html Content-Length: 173 Connection: close
400 Bad Request.
Am I missing something? I do fullfill the needs of the example given above right? I do make a postcall, give all the credenatials as asked, but still can't get anything back.
I am not a PHP developer, I mostly do JavaScript. When I integrate with other REST services I tend to use Postman (https://www.getpostman.com/).
Try the following:
Attempt to successfully connect with the API using Postman (should be relatively straightforward).
When successful, Postman has the ability to generate PHP code automatically, which you can then copy and paste. Works like a charm with JavaScript, don't see why it will be any different with PHP.
I just filled in the details in postman based on what you provided:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.swiftdil.com/v1/oauth2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ=",
"Content-Type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Please note, 'Authorization: Basic' can be used as basic authorization mechanism instead of 'Bearer' (it should work too). So replace 'bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ' with the base64 encoded string 'username:password' (use actual username and password).
You also need to set the curl post fields by setting the below option as per your data.
"curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
))";
If still not work, you can find the curl error as :
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}

uploading file to dropbox using V2 in custom PHP

I have written code for file uploading and it is working fine on one server but not on local machine. Following is code:
<?php
ini_set("display_errors",1);
$api_url = 'https://content.dropboxapi.com/2/files/upload'; //dropbox api url
$token = 'fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$headers = array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: ' .
json_encode(
array(
"path" => '/' . basename('image/1st.jpg'),
"mode" => "add",
"autorename" => true,
"mute" => false
)
),
'Content-Type: application/octet-stream'
);
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
$path = 'images/1st.jpg';
$fp = fopen($path, 'rb');
$filesize = filesize($path);
curl_setopt($ch, CURLOPT_POSTFIELDS, fread($fp, $filesize));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1); // debug
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "<pre>response === "; print_r($response); echo "</pre>";
echo "<pre>http_code === "; print_r($http_code); echo "</pre>";
?>
When i run this code on local, i got following output:
response ===
http_code === 0
On test server, it produce following output:
{"name": "1st.jpg", "path_lower": "/1st.jpg", "path_display": "/1st.jpg", "id": "id:UDbOKdE2bKXXXXXXECg", "client_modified": "2017-10-10T10:05:11Z", "server_modified": "2017-10-10T10:05:11Z", "rev": "4075316e33a", "size": 143578, "content_hash": "f30041XXXXXXXXXXX35ee3cXXXXXXe649afe8d"}
200
what can be possible reason for this issue?
Try to disable SSL veryfy host:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
Or more correct way is:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem file to some safe location in your system
Update your php.ini file and configure the path to that file:
; Linux and macOS systems
curl.cainfo = "/path/to/cacert.pem"
; Windows systems
curl.cainfo = "C:\path\to\cacert.pem"
Following steps resolved issue for me:
1) Download the latest cacert.pem from https://curl.haxx.se/ca/cacert.pem
2) Add the following line to php.ini

How to turn API response into an image?

I'm trying to work with an API using Postman. In Postman the image displays fine. I am using Postman to generate the following code
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.com/v2/tier1/XXXXX/photos/photo/MYPHOTOIDISHERE/download?api_key=MYAPIKEYISHERE",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 74f19da6-d4ba-fe02-4ad3-2a313b472ca2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only modification I have made to the code from Postman is the CURLOPT_SSL_VERIFYPEER as I was getting an error.
The image displays perfectly in Postman but when I try to use the code myself I get a long string that looks like UTF. A small sample (it's very long) of this is as follows;
����JFIF``��C #!!!$'$ & ! ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
How do I convert this into an image?
The result you are seeing is the actual bytes of the image.
You need to save that to a file or process it as image bytes. To save it, dump it to a file using file_put_contents($filename, $data)
// Instead of 'echo $response';
file_put_contents('image.jpg', $response);
You will see a new file image.jpg in your script's directory.
This assumes the image is a jpeg, you could do some checks to determine the type before saving it.
I am able to save image in folder, but problem is that Its showing error - window photo viewer can't open this picture because the file appears to be damaged, corrupted or is too large
here is my code
$oAuthToken = $token->access_token;
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $googlefileid . '?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
$authHeader ,
]);
$data = curl_exec($ch);
curl_close($ch);
Storage::put($googlfilename,$data);
Please tell me what i am doing wrong.

trouble connecting to Reed api - php

I cant seem to connect to the reed api, docs here: https://www.reed.co.uk/developers/jobseeker
it states that:
You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty.
my code currently looks like this:
$api_key = 'MY-API-KEY';
$url = ' https://www.reed.co.uk/api/1.0/search?keywords=Accounts Assistant&resultsToTake=100&resultsToSkip=0'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, urlencode($url));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Basic '.$api_key
));
$server_output = curl_exec($ch);
curl_close($ch);
var_dump($server_output);
the output is always:
bool(false)
Is there something I have missed? Is anyone else able to connect?
I've tried the url directly in my browser and it works, after using my api key in the popup auth box so I know the url and api key is correct.
Please see this answer ( https://stackoverflow.com/a/13654911/5056954 )
I tried to access the reed website and it seems its also asking for a username. Basic auth is also base64 encoded, so the following snippet should work for you if the username is not required:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Basic '. base64_encode($api_key)
));
The easiest way is to use Postman. Once you tune up your query it gives you snippets of codes in many programming languages.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic YOUR-AUTOMATICALLY-ENCODED-API-KEY-BY-POSTMAN",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The code from Postman includes (, "postman-token: xxxxxxx-xxxx-xxx-xx-xx"). Just delete that.
It's the space in the URL parameter.
It should be:
$url = 'https://www.reed.co.uk/api/1.0/search?keywords=Accounts%20Assistant&resultsToTake=100&resultsToSkip=0'

Categories