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);
}
?>
Related
I am using native php 5 (I know it sucks). I want to use curl post with some response
{ SUCCESS = 0,UNAUTHORIZED = 4,WRONG_PARAM = 5,DTIME_OLD = 6,WRONG_SIGN = 11,TOO_LONG = 12}
Actually i've tried on postman and it works with return 0 (SUCCESS).
But when I try on php 5 on localhost XAMPP, it always return empty reply from server.
I also check it on verbose cmd and it still no reply (img:https://i.stack.imgur.com/1zuIx.png).
Any idea, please?
Here is the code:
$path = "msisdn=087884327525&text=meong&sign=".$sign."&userid=19348×tamp=".$date_fix;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('accept: /User-Agent: python-requests/2.8.1',
'accept-encoding: gzip, deflate',
'cache-control: no-cache',
'connection: keep-alive',
'content-length: 119',
'Content-Type: application/x-www-form-urlencoded; charset=utf-8'
// 'postman-token: 53c6e053-1692-010b-ffb9-b249ab94fca1'
));
$response = curl_exec($ch);
if ($response === false){
print_r('Curl error: ' . curl_error($ch));
}else{
echo "success";
}
curl_close($ch);
print_r($response);
ANSWER
I change the 'accept' header and separate it with 'user-agent'. And also, I move the timestamp path to prevent error '×' into 'x'. I ran it on postman (works), then I copy the code from postman to my editor, and it works.
Here is the code:
$curl = curl_init();
curl_setopt_array($curl, array(
// CURLOPT_PORT => "9922",
CURLOPT_URL => $host,
CURLOPT_RETURNTRANSFER => true,
// CURLOPT_ENCODING => "",
// CURLOPT_MAXREDIRS => 10,
// CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false ,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "timestamp=".$date_fix."&msisdn=087881257525&text=test%20USSD&sign=".$sign."&userid=19348",
CURLOPT_HTTPHEADER => array(
"accept: /",
"accept-encoding: gzip, deflate",
"cache-control: no-cache",
"connection: keep-alive",
"content-type: application/x-www-form-urlencoded",
"postman-token: 95239f79-13c2-f64e-4fa0-d2498e5118c9",
"user-agent: python-requests/2.8.1"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
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);
}
I'm trying to fetch html from a page with curl and php. I have the following code, which works perfectly on my host:
<?php
$curl = curl_init();
$URLs[] = "http://www.stackoverflow.com";
echo request( $curl, $URLs[0] );
function request($curl, $url, $post = null)
{
echo (isset($post) ? 'POST ' . $url : 'GET ' . $url) . PHP_EOL;
try
{
curl_setopt_array($curl, array
(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
CURLOPT_HTTPHEADER => array
(
'Accept-Language: en-US;q=0.6,en;q=0.4',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
));
return curl_exec($curl);
}
catch(Exception $exception)
{
echo $exception;
}
}
curl_close($curl);
?>
When I put it on my webhost, I get no response. I checked for curl error and it says 'No Url set!'. Any hints please? Thanks!
try this other format of curl handling, initializing host in curl_init function:
$url = ....
$arrayConfig = ....
$curl = curl_init($url);
curl_setopt_array($curl,$arrayConfig);
$content = curl_exec($curl);
$err = curl_errno($curl);
$errmsg = curl_error($curl) ;
$header = curl_getinfo($curl);
curl_close($curl);
I'm getting a very strange behavior when I do multiple requests with curl. Here's the function I have:
function http_request($curl, $url, $post = null)
{
echo (isset($post) ? 'POST ' . $url : 'GET ' . $url) . PHP_EOL;
try
{
$cookie_path = tempnam(null, 'b');
curl_setopt_array($curl, array
(
CURLOPT_COOKIEFILE => $cookie_path,
CURLOPT_COOKIEJAR => $cookie_path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => count($post),
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
CURLOPT_HTTPHEADER => array
(
'Accept-Language: en-US;q=0.6,en;q=0.4',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
));
return curl_exec($curl);
}
catch(Exception $exception)
{
echo $exception;
}
}
Here's the code I use to call it:
$curl = curl_init();
http_request($curl, "http://host.com/url1");
http_request($curl, "http://host.com/url2", "postdata=123");
http_request($curl, "http://host.com/url3");
http_request($curl, "http://host.com/url4");
curl_close($curl);
This is the output I'm getting:
GET http://host.com/url1
POST http://host.com/url2
GET http://host.com/url3
GET http://host.com/url4
So far so good, but using packet analyzer (wireshark), the output looks like this:
POST http://host.com/url1
Content-Length: 0;
POST http://host.com/url2
Content-Length: 12;
POST http://host.com/url3
Content-Length: 0;
POST http://host.com/url4
Content-Length: 0;
Then I rewrote the code like this:
function http_request($curl, $url, $post = null)
{
echo (isset($post) ? 'POST ' . $url : 'GET ' . $url) . PHP_EOL;
try
{
$cookie_path = tempnam(null, 'b');
curl_setopt_array($curl, array
(
CURLOPT_COOKIEFILE => $cookie_path,
CURLOPT_COOKIEJAR => $cookie_path,
CURLOPT_COOKIESESSION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
CURLOPT_HTTPHEADER => array
(
'Accept-Language: en-US;q=0.6,en;q=0.4',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
));
if($post != null)
{
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
return curl_exec($curl);
}
catch(Exception $exception)
{
echo $exception;
}
}
but still the same thing happens, if I remove this code from the function:
if($post != null)
{
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
In packet analyzer I get:
GET http://host.com/url1
GET http://host.com/url2
GET http://host.com/url3
GET http://host.com/url4
It makes no sense how it gets set to POST on the first request, even my $post argument is not set. Thanks!
I vaguely remember I had the same problem some time ago. Try setting CURLOPT_HTTPGET explicitly as well:
if($post != null)
{
curl_setopt($curl, CURLOPT_HTTPGET, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
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;
}
}