Untitle file issue at google drive when using curl API - php

When I try to upload file at google drive using php curl API it is giving untitled. ANd I can't show file name. How can I properly upload file using curl php? I don't want to use client libraries.There is not file title of uploaded file at google drive
function save_application_form($wpcf7) {
//global $wpdb;
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$submited = array();
$submited['title'] = $wpcf7->title();
$submited['posted_data'] = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$cf7_file_field_name = 'file-846';
$image_location = $uploaded_files[$cf7_file_field_name];
$mime_type = finfo_file($finfo, $image_location);
$token = GetRefreshedAccessToken('client_id', 'refresh_token', 'client_secret');
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array(
'Content-Type:' . $mime_type,
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($image_location),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}

You are not uploading the metadata of the file you are only uploading the file itself. THe post body needs to include the file metadata the filename being one of those items.
Offical php client library example
The documentation shows how to do this with googles client library.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg'));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
PHP CURL wild guess
Sorry i cant help you do this in curl. But it should just be a matter of sending the post body as a JSon string containing the data you wish. The following is my best guess after some Googling.
$data = array("name" => "picture.jpg", "mimeType"=> "image/jpeg");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

Related

Unable to upload file to box using Api in php

I'm unable to upload file on box using php. I've tried all the contents which I've found on stackOverflow but never got success. Even I've tried https://github.com/golchha21/BoxPHPAPI/blob/master/README.md Client but still got failure. Can anyone help me how to upload file on box using php curl.
$access_token = 'xGjQY2XU0bmOEwVAdkqiZTsGuFyFuqzU';
$url = 'https://upload.box.com/api/2.0/files/content';
$headers = array("Authorization: Bearer $access_token"
. "Content-Type:multipart/form-data");
$filename = 'file.jpg';
$name = 'file.jpg';
$parent_id = '0';
$post = array('filename' => "#" . realpath($filename), 'name' => $name,
'parent_id' => $parent_id);
$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_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
var_dump($response);
Even I've used this request too...
$localFile = "file.jpg";
$fp = fopen($localFile, 'r');
$access_token = '00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9';
$url = 'https://upload.box.com/api/2.0/files/content';
$curl = curl_init();
$cfile = new CURLFILE($localFile, 'jpg', 'Test-filename.jpg');
$data = array();
//$data["TITLE"] = "$noteTitle";
//$data["BODY"] = "$noteBody";
//$data["LINK_SUBJECT_ID"] = "$orgID";
//$data["LINK_SUBJECT_TYPE"] = "Organisation";
$data['filename'] = "file.jpg";
$data['parent_id'] = 0;
curl_setopt_array($curl, array(
CURLOPT_UPLOAD => 1,
CURLOPT_INFILE => $fp,
CURLOPT_NOPROGRESS => false,
CURLOPT_BUFFERSIZE => 128,
CURLOPT_INFILESIZE => filesize($localFile),
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9",
"Content-Type:multipart/form-data"
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
var_dump($info);
$req_dump = print_r($response, true);
file_put_contents('box.txt', $req_dump, FILE_APPEND);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
And in response I always got an empty string.
Please tell me what am I doing wrong?
I'm using Box PHP Client for creation of folders, uploading of files and then sharing of uploaded files using this client.
https://github.com/golchha21/BoxPHPAPI
But this client's uploading file wasn't working... then I dig into it and I found something missing into this method.
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}
Just put forward slash after # sign. Like this, Then I'll start working
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#/" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}

cURL file upload not working in PHP 5.6.x running on Windows 2012 R2

I am using the following code to upload a file to a server using a .NET upload script:
if(isset($_FILES['fileToUpload'])) {
$url = "path/to/FileUpload.aspx"; // request URL
$filename = $_FILES['fileToUpload']['name'];
$filedata = $_FILES['fileToUpload']['tmp_name'];
$filesize = $_FILES['fileToUpload']['size'];
$filetype = $_FILES['fileToUpload']['type'];
if ($filedata != '') {
$dom = dom_import_simplexml($response);
$processXML = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
$params = $companyId.",".$userId.",".$dataXML;
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$ch = curl_init();
$file = new CURLFile($filedata,$filetype,$filename);
$postfields = array("file" => $file,"params" => $params);
$options = array(
CURLOPT_URL => $url,
CURLOPT_PORT => 8085,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SAFE_UPLOAD => false,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if(!curl_errno($ch)) {
if ($http_code == 200) {
echo "File uploaded successfully<br>";
// If file uploaded successfully, post the question...
postQuestion($arg1,$arg2);
} else {
$arr = array('status' => 'error', 'message' => 'http error');
}
} else {
$arr = array('status' => 'error', 'message' => 'upload error');
echo json_encode($arr);
}
curl_close($ch);
} else {
echo "Invalid file";
}
}
PROBLEM
The script always returns array('status' => 'error', 'message' => 'upload error');
This same code works in Apache (xampp).
I checked all configs (php.ini, required .dll's) on the server and everything seems to be in order.
Some posts here and elsewhere suggested copying ssleay.dll and libeay.dll from PHP installation directory to Windows\System32. Tried that as well.
curl_error($ch) returns nothing
curl_errno($ch) returns 43
Environment Details
Windows 2012 R2
PHP v5.6.0
cURL v7.36.0
What am I missing here? I just started learning PHP 2 weeks back, so please be gentle :)

How do I send files in PHP via CURL? #filename won't work

I'm trying to send an image via POST using PHP's CURL methods.
I am sending the image to an API that expects the POST field 'photo_file' to be an image.
I set the 'photo_file' to # followed by the file name.
However, when I make the request the API receives the literal string '#filename' instead of the file contents.
Here is the relevant code:
Calling code:
$data = array(
'campaign_id' => $_POST['campaign_id'],
);
$img_source = realpath($img_source); // "/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg"
$response = $y->upload_photo($img_source, $data);
$y->upload_photo():
public function upload_photo($img_source, $data) {
$fields = array(
'campaign_id' => $data['campaign_id'],
'photo_file' => '#' . $img_source
);
return $this->request('photos', $fields, 'post');
}
$this->request() (relevant parts):
public function request($function, $fields = array(), $method = 'get') {
$ch = curl_init();
$url = $this->host . $function;
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Accept: application/json', 'Expect:'),
CURLOPT_VERBOSE => 1,
CURLOPT_HEADER => 1,
);
if ($method == 'post') {
$curlConfig[CURLOPT_POST] = 1;
$curlConfig[CURLOPT_POSTFIELDS] = true;
$curlConfig[CURLOPT_POSTFIELDS] = $fields;
}
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
list($header_blob, $body) = explode("\r\n\r\n", $result, 3);
$this->http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return json_decode($body);
}
The API is returning an error, and when its dev looked at the logs he saw that the request on his end was:
'campaign_id' => '4'
'photo_file' => '#/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg'
so adding # to the beginning of the file didn't actually send the contents of the file, like I understand it's supposed to. Also, the API works fine with other platforms that use it, so the problem is definitely on my end.

How do I upload images to the Google Cloud Storage from PHP form?

I'm currently utilizing a php app to upload images to the Google cloud storage platform, however, unlike on my local server, I am having tremendous trouble figuring out how to make this work.
Here is exactly what I am trying to do:
Write the Path of the image to my Google cloud SQL
Actually upload the image to the Google cloud storage platform
write a script calling on the image, from the saved SQL path, to then post to my site
Can anyone point in the right direction?
Thanks!
Something like this worked for me with the form on GAE - upload photo from Form via php to google cloud storage given your folder permission are set...
// get image from Form
$gs_name = $_FILES["uploaded_files"]["tmp_name"];
$fileType = $_FILES["uploaded_files"]["type"];
$fileSize = $_FILES["uploaded_files"]["size"];
$fileErrorMsg = $_FILES["uploaded_files"]["error"];
$fileExt = pathinfo($_FILES['uploaded_files']['name'], PATHINFO_EXTENSION);
// change name if you want
$fileName = 'foo.jpg';
// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
file_put_contents("gs://<bucketname>/".$fileName, $gs_name, 0, $ctx);
// or move
$moveResult = move_uploaded_file($gs_name, 'gs://<bucketname>/'.$fileName);
The script to call the image to show on your site is typical mysqli or pdo method to get filename, and you can show the image with...
<img src="https://storage.googleapis.com/<bucketname>/<filename>"/>
in case anyone may be interested, I made this, only upload a file, quick & dirty:
(I do not want 500+ files from the php sdk just to upload a file)
<?php
/**
* Simple Google Cloud Storage class
* by SAK
*/
namespace SAK;
use \Firebase\JWT\JWT;
class GCStorage {
const
GCS_OAUTH2_BASE_URL = 'https://oauth2.googleapis.com/token',
GCS_STORAGE_BASE_URL = "https://storage.googleapis.com/storage/v1/b",
GCS_STORAGE_BASE_URL_UPLOAD = "https://storage.googleapis.com/upload/storage/v1/b";
protected $access_token = null;
protected $bucket = null;
protected $scope = 'https://www.googleapis.com/auth/devstorage.read_write';
function __construct($gservice_account, $private_key, $bucket)
{
$this->bucket = $bucket;
// make the JWT
$iat = time();
$payload = array(
"iss" => $gservice_account,
"scope" => $this->scope,
"aud" => self::GCS_OAUTH2_BASE_URL,
"iat" => $iat,
"exp" => $iat + 3600
);
$jwt = JWT::encode($payload, $private_key, 'RS256');
// echo "Encode:\n" . print_r($jwt, true) . "\n"; exit;
$headers = array(
"Content-Type: application/x-www-form-urlencoded"
);
$post_fields = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt";
// $post_fields = array(
// 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
// 'assertion' => $jwt
// );
$curl_opts = array(
CURLOPT_URL => self::GCS_OAUTH2_BASE_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $post_fields,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
// var_dump($curl); exit;
$response = curl_exec($curl);
if (curl_errno($curl)) {
die('Error:' . curl_error($curl));
}
curl_close($curl);
$response = json_decode($response, true);
$this->access_token = $response['access_token'];
// echo "Resp:\n" . print_r($response, true) . "\n"; exit;
}
public function uploadObject($file_local_full, $file_remote_full, $content_type = 'application/octet-stream')
{
$url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
if(!file_exists($file_local_full)) {
throw new \Exception("$file_local_full not found.");
}
// $filesize = filesize($file_local_full);
$headers = array(
"Authorization: Bearer $this->access_token",
"Content-Type: $content_type",
// "Content-Length: $filesize"
);
// if the file is too big, it should be streamed
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => file_get_contents($file_local_full),
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
return $response;
}
public function uploadData(string $data, string $file_remote_full, string $content_type = 'application/octet-stream')
{
$url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
// $filesize = strlen($data);
$headers = array(
"Authorization: Bearer $this->access_token",
"Content-Type: $content_type",
// "Content-Length: $filesize"
);
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
return $response;
}
public function copyObject($from, $to)
{
// 'https://storage.googleapis.com/storage/v1/b/[SOURCEBUCKET]/o/[SOURCEOBJECT]/copyTo/b/[DESTINATIONBUCKET]/o/[DESTINATIONOBJECT]?key=[YOUR_API_KEY]'
$from = rawurlencode($from);
$to = rawurlencode($to);
$url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$from/copyTo/b/$this->bucket/o/$to";
// $url = rawurlencode($url);
$headers = array(
"Authorization: Bearer $this->access_token",
"Accept: application/json",
"Content-Type: application/json"
);
$payload = '{}';
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
// echo '<pre>'; var_dump($response); exit;
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
return $response;
}
public function deleteObject($name)
{
// curl -X DELETE -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"
//
$name = rawurlencode($name);
$url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$name";
$headers = array(
"Authorization: Bearer $this->access_token",
"Accept: application/json",
"Content-Type: application/json"
);
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "DELETE",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
// echo '<pre>'; var_dump($response); exit;
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
return $response;
}
public function listObjects($folder)
{
// curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
//
$folder = rawurlencode($folder);
$url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o?prefix=$folder";
$headers = array(
"Authorization: Bearer $this->access_token",
"Accept: application/json",
"Content-Type: application/json"
);
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
// echo '<pre>'; var_dump($response); exit;
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
return $response;
}
}

php - Facebook Video Upload Curl

To upload the video to Facebook using the following lines.
$video = "http://xxx.com/video.mp4";
$data = array('name' => 'file', 'file' => $video,
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
I received an error:
"error":{"message":"(#353) You must select a video file to
upload.","type":"OAuthException","code":353}}
If I change curl to form post it works. Any ideas on why is it so?
Use the path to the video on server instead of the url. So:
$video = "uploads/video.mp4";
Then:
$data = array('name' => 'file', 'file' => '#'.realpath($video),
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
Notice the use of realpath() following the '#' symbol. Haven't tested with your code but I have a similar implementation and works great. Should do the trick!
For FB SDK4: (see the hardcoded video path, and the encoding).
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
private function postFBVideo($authResponse, $fileObj, $formData)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}

Categories