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);
}
Related
I am using instagram api to search specific hashtag getting top media and recent media but graphic shows 4 different calls, so the the 200 limit per hour are consumed really fast. I know about ig_hashtag_search , top_media and recent_media but what i dont know what is shadowIGHastag.
Is there a way to avoid overconsumption of my app?
This is how i use the api
function insthashtag()
{
include "../insta/define.php";
function makeApiCall($endpoint, $type, $params)
{
$ch = curl_init();
if ('POST' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
} elseif ('GET' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$hashtag = 'sedapal';
$hashtagId = '17843308429009249';
$hashtagSearchEndpoint = ENDPOINT_BASE . 'ig_hashtag_search';
$hashtagSearchParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,name',
'q' => $hashtag,
'access_token' => $accessToken
);
$hashtagSearch = makeApiCall($hashtagSearchEndpoint, 'GET', $hashtagSearchParams);
/* To get hashtagID */
/* echo '<pre>';
print_r($hashtagSearch);
die(); */
$hashtagDataEndpoint = ENDPOINT_BASE . $hashtagId;
$hashtagDataParams = array(
'fields' => 'id,name',
'access_token' => $accessToken
);
$hashtagData = makeApiCall($hashtagDataEndpoint, 'GET', $hashtagDataParams);
$hashtagTopMediaEndpoint = ENDPOINT_BASE . $hashtagId . '/top_media';
$hashtagTopMediaParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagTopMedia = makeApiCall($hashtagTopMediaEndpoint, 'GET', $hashtagTopMediaParams);
$topPost = $hashtagTopMedia['data'][0];
$topPost1 = $hashtagTopMedia['data'][1];
$topPost2 = $hashtagTopMedia['data'][3];
/* To get recent data
$hashtagRecentEndpoint = ENDPOINT_BASE . $hashtagId . '/recent_media';
$hashtagRecentParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagRecent = makeApiCall($hashtagRecentEndpoint, 'GET', $hashtagRecentParams);
$recentPost = $hashtagRecent['data'][0];
$recentPost2 = $hashtagRecent['data'][1]; */
/* $recentPost3 = $hashtagRecent['data'][2]; */
$return = [$topPost['media_type'], $topPost['media_url'], $topPost1['media_type'], $topPost1['media_url'], $topPost2['media_type'], $topPost2['media_url']];
$jsondata = json_encode($return, JSON_PRETTY_PRINT);
return $jsondata;
Specifically relating to this particular thread Upload a file to a website using php I want to implement this using cURL on PHP.
How do I set this up?
Below is what I have tried.
Note I just edited this by adding the codes I have tried.
<?php
if(isset($_POST["submit"])){
$errors= array();//
$name = $_FILES['fileToUpload']['name'];
$size = $_FILES['fileToUpload']['size'];
$type = $_FILES['fileToUpload']['type'];
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$upload_ok =1;
$file_ext=strtolower(end(explode('.',$_FILES['fileToUpload']
['name'])));//
$extensions= array("pdf","jpeg","jpg","png");
$jj = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$mj = base64_encode($jj);
if(in_array($file_ext,$extensions)=== false){
$errors[]="vvvvv.";
}
if($size >= xxx){
$errors[]='xxx;'
}
if(empty($errors)==true){
echo "Success </br>";
$request = "xxxxxxxxx";
$headers = array(
"Authorization: Bearer xxxxxx",
"Content-type => multipart/form-data",
"Accept:application/json",
);
$data = [
'voucher_data' => 'base64_encode($tmp_name)',
'callback_url' => 'xxxxxxxxx'
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "xxxxxxxxxx",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
curl_close($curl);
var_dump($response);
}else{
print_r($errors);
}
?>
I tried using curl_file_create($mj) as suggested below but on var_dump...it says bool(false)
I see that you want to make a request that uploads a file to another server other than your own.
After PHP 5.5, there is a function named curl_file_create and as the name suggests, it's being used for uploading files.
$post = array (
'extra_info' => '123456', // If required.. like user_id for avatar
'file_contents' => curl_file_create ('path/to/file');
);
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);
If you don't want to use that then there is a much simple way:
$args = [];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
$args['file'] = '#/path/to/file';
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_close ($ch);
Well after a lot of trying out different methods I passed this value to the post field directly without using it as array
CURLOPT_POSTFIELDS => “foo=$mj&callbackurl=url”,
and it worked. This was where I was stucked. I did it the other way and it didn't work. Each situation is unique. Someone could also need this.
This is the $_POST
Array
(
[name] => image.png
[type] => image/png
[tmp_name] => C:\xampp5\tmp\phpA637.tmp
[error] => 0
[size] => 16412
)
And here's the code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "2403",
CURLOPT_URL => "http://".cfg('api_ip').":2403/sk_group/update_profile_pic", //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 => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{\"groupId\":\"".$group."\",\"profile_pic\":\"".$name."\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_pic\"; filename=\"".$file."\"\r\nContent-Type: ".$type."\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"SessionId: ".$_SESSION['session']."",
"VersionCode: ".cfg('version_code')."",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
redirect("/meme/me/group"."?msg=".urldecode('Update icon group succes')."&type_msg=success");
}
i want to know how to $file to the image for success upload, cause $_POST only display the filename not with the fullpath.
Update
this is the full function in controller i have
function one()
{
$filename = $_FILES['icon']['name'];
$filedata = $_FILES['icon']['tmp_name'];
$filetype = $_FILES['icon']['type'];
two($_POST['group'], $filename, $filedata, $filetype);
}
this function on my helper
function two($group, $name, $file, $type)
{
$cFile = new CURLFile($file,$type,$name);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "2403",
CURLOPT_URL => "http://".cfg('api_ip').":2403/sk_group/update_profile_pic",
CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{\"groupId\":\"".$group."\",\"profile_pic\":\"".$name."\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_pic\"; filename=\"".$cFile."\"\r\nContent-Type: ".$type."\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"SessionId: ".$_SESSION['session']."",
"VersionCode: ".cfg('version_code')."",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
redirect("/meme/me/group"."?msg=".urldecode('Update icon group succes')."&type_msg=success");
}
}
still with same question like i asking..., where the file? and how to post it until success?
I have posted the same answer here
From PHP 5.5 and above the CURL will use CURL File to upload the files, for the lower PHP version, you need to manually generate the form boundary and then send the file. The following code sample handles both the cases.
For ease, here's the main part:
<?php
$file = "websites.txt";
upload_with_compatibility($file);
function upload_with_compatibility($file){
if (version_compare(phpversion(), '5.5', '>=')) {
echo "Upload will be done using CURLFile\n";
upload($file); //CURL file upload using CURLFile for PHP v5.5 or greater
}else{
echo "Upload will be done without CURLFile\n";
compatibleUpload($file); //CURL file upload without CURLFile for PHP less than v5.5
}
}
//Upload file using CURLFile
function upload($file){
$target = "http://localhost:8888/upload_file.php";
$host = parse_url($target);
$cFile = new CURLFile($file,'text/plain', $file);
$data = array(
'log_file' => $cFile,
);
//you can play around with headers, and adjust as per your need
$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36';
$curlHeaders = array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding: gzip, deflate',
'Accept-Language: en-US,en;q=0.8',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36', //change user agent if you want
'Connection: Keep-Alive',
'Pragma: no-cache',
'Referer: http://localhost:8888/upload.php', //you can change referer, if you want or remove it
'Host: ' . $host['host'] . (isset($host['port']) ? ':' . $host['port'] : null), // building host header
'Cache-Control: max-age=0',
'Cookie: __utma=61117235.2020578233.1500534080.1500894744.1502696111.4; __utmz=61117235.1500534080.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', //adjust your cookie if you want
'Expect: '
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_HEADER , true); //we need header
curl_setopt($curl, CURLOPT_USERAGENT,$agent);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$r = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfull
print_r($r);
}
}
curl_close($curl);
}
//Upload file without using CURLFile, because we are upload a file, so we need to generate form boundry
function compatibleUpload($file){
$target = "http://localhost:8888/upload_file.php";
//use this to send any post parameters expect file types
//if you are not sending any other post params expect file, just assign an empty array
// $assoc = array(
// 'name' => 'demo',
// 'status' => '1'
// );
$assoc = array(); //like this
//this array is used to send files
$files = array('log_file' => $file);
static $disallow = array("\0", "\"", "\r", "\n");
// build normal parameters
foreach ($assoc as $k => $v) {
$k = str_replace($disallow, "_", $k);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"",
"",
filter_var($v),
));
}
// build file parameters
foreach ($files as $k => $v) {
switch (true) {
case false === $v = realpath(filter_var($v)):
case !is_file($v):
case !is_readable($v):
continue; // or return false, throw new InvalidArgumentException
}
$data = file_get_contents($v);
$v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
$k = str_replace($disallow, "_", $k);
$v = str_replace($disallow, "_", $v);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
"Content-Type: application/octet-stream",
"",
$data,
));
}
// generate safe boundary
do {
$boundary = "---------------------" . md5(mt_rand() . microtime());
} while (preg_grep("/{$boundary}/", $body));
// add boundary for each parameters
array_walk($body, function (&$part) use ($boundary) {
$part = "--{$boundary}\r\n{$part}";
});
// add final boundary
$body[] = "--{$boundary}--";
$body[] = "";
// set options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_HEADER , true); //we need header
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => implode("\r\n", $body),
CURLOPT_HTTPHEADER => array(
"Expect: ",
"Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
),
));
$r = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfully uploaded
print_r($r);
}
}
curl_close($ch);
}
?>
I need to log on a page using curl to get a value from the page, but I don't get any result at all.
Have I missed something or is it maybe impossible to implement?
<?
$u = "******************";
$p = "******************";
$token = file_get_contents("https://secure.izettle.com/portal/login");
preg_match('/content=\"(.*?)\" name=\"csrf-token/', $token, $t);
$authenticity_token = $t[1];
echo $authenticity_token;
$fields = array("user[email_address]" => $u, "user[password]" => $p, "authenticity_token" => $authenticity_token );
$ch = curl_init();
//Set curl options
$options = array(
CURLOPT_URL => "https://secure.izettle.com/portal/login",
CURLOPT_COOKIEJAR => "cookie.txt",
CURLOPT_COOKIEFILE => "cookie.txt",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields
);
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "https://secure.izettle.com/portal/reports?date=2014-05-21");
$page = curl_exec($ch);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
echo $page.'<br>';
Is it possible for split up the code and try. Not sure it will work. Assumes the second form method is "post"
<?php
$u = "******************";
$p = "******************";
$fields = array("user[email_address]" => $u, "user[password]" => $p);
$ch = curl_init();
//Set curl options
$options = array(
CURLOPT_URL => "https://secure.izettle.com/portal/login",
CURLOPT_COOKIEJAR => "cookie.txt",
CURLOPT_COOKIEFILE => "cookie.txt",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_FOLLOWLOCATION =>true
);
curl_setopt_array($ch, $options);
$res = curl_exec($ch);
unset($ch);
//*****************************************************************************
$qry_str = "?date=2014-05-21";
$ch = curl_init();
// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'secure.izettle.com/portal/…' . $qry_str);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
print_r($content);
?>
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;
}
}