function not uploading remote pdfs - php

I have 2 functions: one that uses chunked uploading and the other that uploads the entire file
public function chunkedUpload($file, $filename = false, $path = '', $overwrite = true)
{
if (file_exists($file)) {
if ($handle = #fopen($file, 'r')) {
// Set initial upload ID and offset
$uploadID = null;
$offset = 0;
// Read from the file handle until End OF File, uploading each chunk
while ($data = fread($handle, $this->chunkSize)) {
$chunkHandle = fopen('php://temp', 'rw');
fwrite($chunkHandle, $data);
$this->OAuth->setInFile($chunkHandle);
// On subsequent chunks, use the upload ID returned by the previous request
if (isset($response['body']->upload_id)) {
$uploadID = $response['body']->upload_id;
}
$params = array('upload_id' => $uploadID, 'offset' => $offset);
$response = $this->fetch('PUT', self::CONTENT_URL, 'chunked_upload', $params);
$offset += mb_strlen($data, '8bit');
fclose($chunkHandle);
}
// Complete the chunked upload
$filename = (is_string($filename)) ? $filename : basename($file);
$call = 'commit_chunked_upload/' . $this->root . '/' . $this->encodePath($path . $filename);
$params = array('overwrite' => (int) $overwrite, 'upload_id' => $uploadID);
$response = $this->fetch('POST', self::CONTENT_URL, $call, $params);
return $response;
} else {
throw new Exception('Could not open ' . $file . ' for reading');
}
}
// Throw an Exception if the file does not exist
throw new Exception('Local file ' . $file . ' does not exist');
}
public function putFile($file, $filename = false, $path = '', $overwrite = true)
{
if (file_exists($file)) {
if (filesize($file) <= 157286400) {
$filename = (is_string($filename)) ? $filename : basename($file);
$call = 'files/' . $this->root . '/' . $this->encodePath($path . $filename);
// If no filename is provided we'll use the original filename
$params = array(
'filename' => $filename,
'file' => '#' . str_replace('\\', '\\', $file) . ';filename=' . $filename,
'overwrite' => (int) $overwrite,
);
$response = $this->fetch('POST', self::CONTENT_URL, $call, $params);
return $response;
}
throw new Exception('File exceeds 150MB upload limit');
}
// Throw an Exception if the file does not exist
throw new Exception('Local file ' . $file . ' does not exist');
}
I have tested these functions from the same server directory and they both work fine; however, chunkedUpload is able to upload from remote http:// and ftp:// urls but putFile is not able to. Why does this happen? Is there a problem within these two functions that might cause this?

this is because file_exists does not work on remote servers
file_exists() in PHP 5 does not accept URLs only local path names
use curl to send a head request instead
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'your url');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
var_dump($size);

Related

How to attach a file using cURL?

I am creating a zip folder in which I need to attach to an email. Attaching the zip folder is not working.
I included three files below that work together:
The SEND file is where the ajax sends the files to. Then there is a fileUpload.php file that uploads single files and generates the $filename variable array for all the files uploaded. This is where the zip folder gets created and where I attempt to attach it with $message.
The COMMUNICATION CLASS is used to send emails. Originally, the zip folder was created/attached here. For some reason, I can't figure out how to get the two files to work together, outside of what it already does.
The TEMPLATE file is where email html and css are contained. Also are the {variables}. This is where the filename and message variables are. Though, filename should be all that is required.
The zip folder is being created. It is just not attaching.
Does anyone see why when the zip is created that it isn't attaching to the email? Specifically, this part of the code is where I am trying to do it:
$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
SEND FILE
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require 'fileUpload.php';
$first_name = trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
$last_name = trim(htmlspecialchars($_POST['last_name'], ENT_QUOTES));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$zip = trim(htmlspecialchars($_POST['zip']));
$company = trim(htmlspecialchars($_POST['company'], ENT_QUOTES));
$details = trim(htmlspecialchars($_POST['description'], ENT_QUOTES));
$file = null;
require_once '../config.php';
/************************ Start to Company ******************************/
$placeholders = ['{first_name}',
'{last_name}',
'{phone}',
'{zip}',
'{company}',
'{description}',
'{interest}',
'{email}',
'{lead_owner}',
'{lead_assign}'
];
$values = [
htmlentities($_POST['first_name']),
htmlentities($_POST['last_name']),
htmlentities($_POST['phone']),
htmlentities($_POST['zip']),
htmlentities($_POST['company']),
nl2br(htmlentities($_POST['description'])),
htmlentities($_POST['interest']),
htmlentities($_POST['email']),
$lead_owner = htmlentities($_POST['leadOwner']),
$lead_assign = htmlentities($_POST['leadAssign']),
];
$template = str_replace($placeholders, $values, file_get_contents("templates/quote_to_domain.html"));
$files = null;
if (!empty($_FILES["uploadedFile"]["name"])) {
if ($_FILES['uploadedFile']['error'] == 1) {
$error = "The file {$_POST['first_name']} attempted to upload is too large. Contact them for an alternate way to send this file.";
$template = str_replace("{filename}", "$error", $template);
}
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
$extensions = ['pdf','jpg', 'jpeg', 'png', 'gif'];
//file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
$target_dir = "uploads/";
$differentExtensions = array_diff($uploadedFileTypes, $extensions);
if (count($differentExtensions) > 0) {
//file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
$f = new ZipArchive();
$zip = $f->open($target_dir . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($zip) {
for ($index = 0; $index < count($filename); $index++) {
$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
}
$f->close();
$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
//$template = str_replace("{filename}", $message, $template);
} else {
throw new Exception("Could not zip the files.");
$msg = "Could not zip the files.";
echo json_encode(['status_code' => 500,
'message' => $msg]);
}
} else {
$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). ' uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
foreach ($filename as $indFile) {
//print_r($template);
$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
}
$out .= '</ul>';
$template = str_replace("{filename}", $out, $template);
}
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (empty($value)) {
//echo "name is empty!";
$template = str_replace("{filename}", '', $template);
}
if ($file['error'][$key] != 4) {
//echo "error code is 4";
}
}
}
clearstatcache();
}
$to_company = Communication::mail_api($_POST, $filename, $template, 0);
Then here is the communication class. Originally, the zip code was in here (and still is). I can't figure out how to get the two files to work together as they should have.
COMMUNICATION CLASS
class Communication
{
public static function mail_api(Array $msg, Array $filename = null, $template = null, $recipient = false, $attachment = null)
{
$date = new DateTime();
$config = array();
$message = array();
$message['to'] = !$recipient ? $email_to_send_to : $msg['email'];
$message['h:Reply-To'] = !$recipient ? $msg['email'] : '';
$message['subject'] = isset($msg['subject']) ? $msg['subject'] : '';
if ($attachment) {
try {
if (!file_exists($attachment)) {
throw new Exception("File $attachment not found!");
}
$parts = explode('/', $attachment);
$filenames = end($parts);
$message['attachment[0]'] = curl_file_create($attachment,
pathinfo($attachment, PATHINFO_EXTENSION),
$filenames);
file_put_contents('log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Attachment added: \n", FILE_APPEND); //here
} catch (Exception $e) {
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}
}
$message['html'] = $template;
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['api_url']);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'o:tracking-clicks: false'
));
curl_setopt($ch, CURLOPT_USERPWD, "api:{$config['api_key']}");
$self = new Communication();
if (!empty($file) && !$recipient && count($filename) > 1) {
$f = new ZipArchive();
$zip = $f->open('uploads/' . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($zip) {
for ($index = 0; $index < count($_FILES['uploadedFile']['name']); $index++) {
// echo $file['uploadedFile']['name'][$index] . "\n";
//$f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
}
$f->close();
$message["attachment[0]"] = curl_file_create("uploads/{$filename[0]}.zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
} else {
throw new Exception("Could not zip the files.");
}
// $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='/php/uploads/{$file['uploadedFile']['name']}.zip'>{$file['uploadedFile']['name']}</a>", $message['html']);
} elseif (count($filename) == 1) {
$message["attachment[0]"] = curl_file_create("uploads/{$filename}",
pathinfo("uploads/{$filename}", PATHINFO_EXTENSION),
$filename);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$result = curl_exec($ch);
curl_close($ch);
$resp = json_decode($result);
file_put_contents('communication_log', "\n[{$date->format('Y-m-d H:i:s')}] " . "Log for {$message['to']}: \n" . print_r(json_encode($resp) . "\n\n" . print_r($message,1), 1), FILE_APPEND);
// print_r($resp);
if (isset($resp->id))
return true;
return false;
} catch (Exception $e) {
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error for {$message['to']}: \n" . print_r($e, 1), FILE_APPEND);
}
}
Then the template, which is an email that sends the file link or attachment (though attachment not sending):
TEMPLATE
<tr>
<td> {filename} </td>
</tr>
<tr>
<td><i>{message}</i></td>
</tr>

how to set default none.png image if input file empty php

I tried to apply none.PNG if input file empty and i use statement like this. I need to fix this to use it in my systems. thank you.
if(empty($image)){
$name = md5(time() . rand(0, 999)) . '.jpeg';
}else{
$name = 'none.jpeg';
}
public function saveimage()
{
if (isset($_POST['image_loc'])) {
$image = $_FILES['image_loc'];
$allowed = array('image/jpeg', 'image/jpg', 'image/png');
// print_r($image);
// die();
// check for erros
if ($image['error'] != 0) {
die('File upload error: ' . $image['error']);
}
// check if is image
if (in_array($image['type'], $allowed)) {
$name = md5(time() . rand(0, 999)) . '.jpeg';
move_uploaded_file($image['tmp_name'], ROOT . '/public/img/pics/' . $name);
echo $image['tmp_name'];
$this->insert($name);
}
}
}
After edited the code
The result show only if I upload file. i need none.PNG as well to show if not upload file. how can i do this.
public function saveimage()
{
if (isset($_POST['image_loc'])) {
$image = $_FILES['image_loc'];
$allowed = array('image/jpeg', 'image/jpg', 'image/png');
// print_r($image);
// die();
// check if is image
if (in_array($image['type'], $allowed)) {
////////////////////////// here ///////////////////////
if (empty($image)) {
$name = md5(time() . rand(0, 999)) . '.jpeg';
} else {
$name = 'none.jpeg';
}
////////////////////////// here ///////////////////////
move_uploaded_file($image['tmp_name'], ROOT . '/public/img/pics/' . $name);
echo $image['tmp_name'];
$this->insert($name);
}
}
}
If $_POST["image_loc"] is remote url, you can use function below that returns file size. So can check if it returns 0 or not. If $_POST["image_loc"] isn't remote url and it's image path in your server, you can simply use filesize($image_path) function to get image size.
function get_image_size($image_url){
$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
return $size;
}

Laravel: Save Base64 .png file to public folder from controller

I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.
Here is my controller
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
$png_url = "product-".time().".png";
$path = public_path('img/designs/' . $png_url);
Image::make($image->getRealPath())->save($path);
// I've tried using
// $result = file_put_contents($path, $image);
// too but still not working
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
Intervention Image gets binary data using file_get_content function:
Reference : Image::make
Your controller should be look like this:
public function postTest() {
$data = Input::all();
$png_url = "product-".time().".png";
$path = public_path().'img/designs/' . $png_url;
Image::make(file_get_contents($data->base64_image))->save($path);
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
$data = Input::all();
$png_url = "perfil-".time().".jpg";
$path = public_path() . "/img/designs/" . $png_url;
$img = $data['fileo'];
$img = substr($img, strpos($img, ",")+1);
$data = base64_decode($img);
$success = file_put_contents($path, $data);
print $success ? $png_url : 'Unable to save the file.';
$file = base64_decode($request['image']);
$safeName = str_random(10).'.'.'png';
$success = file_put_contents(public_path().'/uploads/'.$safeName, $file);
print $success;
This is an easy mistake.
You are using public_path incorrectly. It should be:
$path = public_path() . "/img/designs/" . $png_url;
Also, I would avoid your method of sending the image. Look at a proper upload in a form and use Laravel's Input::file method.
My solution is:
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
Storage::disk('local')->put('imgage.png', $image);
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
echo $storagePath.'imgage.png';
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
what am i doing is using basic way
$file = base64_decode($request['profile_pic']);
$folderName = '/uploads/users/';
$safeName = str_random(10).'.'.'png';
$destinationPath = public_path() . $folderName;
file_put_contents(public_path().'/uploads/users/'.$safeName, $file);
//save new file path into db
$userObj->profile_pic = $safeName;
}
Store or save base64 images in the public folder image and return file path.
$folderPath = public_path() . '/' . 'images/';
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$uniqid = uniqid();
$file = $folderPath . $uniqid . '.' . $image_type;
file_put_contents($file, $image_base64);
return $file;
Actually, Input::all() returns an array of inputs so you have following:
$data = Input::all();
Now your $data is an array not an object so you are trying to access the image as an object like:
$data->base64_image
So, it's not working. You should try using:
$image = $data['base64_image'];
Since it's (base64_image) accessible from $_POST then Input::file('base64_image') won't work because Input::file('base64_image') checks the $_FILES array and it's not there in your case.
Here is my solution for the file upload from base_64.
public static function uploadBase64File(Request $request, $requestName = 'imageData', $fileName = null, $uploadPath = 'uploads/images/')
{
try {
$requestFileData = $request->$requestName;
// decode the base64 file
$file = base64_decode(preg_replace(
'#^data:([^;]+);base64,#',
'',
$request->input($requestName)
));
if (in_array($file, ["", null, ' '])) {
return null;
}
//handle base64 encoded images here
if ($fileName == null) {
$fileName = Str::random(10);
}
$extension = '.' . explode('/', explode(':', substr($requestFileData, 0, strpos($requestFileData, ';')))[1])[1];
$filePath = $uploadPath . '' . $fileName . '' . $extension;
// dd($extension);
if (!File::exists(public_path($uploadPath))) {
File::makeDirectory(public_path($uploadPath), 0777, true);
}
// dd($filePath);
$ifImageUploadSuccessful = File::put(public_path($filePath), $file);
if (!$ifImageUploadSuccessful) {
return null;
}
return '/' . $filePath;
// throw new Exception("Unable To upload Image");
} catch (Exception $e) {
// dd($e);
throw new Exception($e->getMessage());
}
}
I'v done it!!
I replaced
$data->base64_image to $_POST['base64_image'] and then use
$result = file_put_contents($path, $image);
instead of Image::make($image->getRealPath())->save($path);
But this doesn't look like a laravel ways. I you have another way that look more elegant please tell me!

PHP REST download file

I have a webservice with a function like this
$app->get('/downloadPdf', function () use($app)
{
$log = 'example.pdf';
$res = $app->response();
$res['Content-Description'] = 'File Transfer';
$res['Content-Type'] = 'application/octet-stream';
$res['Content-Disposition'] ='attachment; filename=' . basename($log);
$res['Content-Transfer-Encoding'] = 'binary';
$res['Expires'] = '0';
$res['Cache-Control'] = 'must-revalidate';
$res['Pragma'] = 'public';
$res['Content-Length'] = filesize($log);
readfile($log);
});
Testing it with Advanced Rest Client works fine..
Question is .. how do i call it from my client with all the headers etc.
To specify more. I know there are a lot of examples on how to download a specific file by inserting its url into the curlopt_url with the complete address to the file. What i want is to let the webservice decide which file to return...
Thanks
Never got an answer .. so !!!
This is how i made it work....
Service Function can be seen below
$app->post('/downloadReport', 'authenticate', function() use ($app)
{
verifyRequiredParams(array('reportId'));
$body = $app->request()->getBody();
$params_str = urldecode($body);
$input = json_decode($params_str,true);
$report_id = $input['reportId'];
$db = new DbHandler();
$db->getReport($report_id);
$path = $db->getReportPdfPath($report_id);
$res = $app->response();
$res['Content-Description'] = 'File Transfer';
$res['Content-Type'] = 'application/octet-stream';
$res['Content-Disposition'] ='attachment; filename=' . basename($path);
$res['Content-Transfer-Encoding'] = 'binary';
$res['Expires'] = '0';
$res['Cache-Control'] = 'must-revalidate';
$res['Pragma'] = 'public';
$res['Content-Length'] = filesize($path);
readfile($path);
});
Called the function like this:
public function downloadReport($api_key,$id)
{
$curl_post_data = array('reportId' => $id);
$headers = array('Content-type: application/json','Authorization: '.$api_key,);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the information
$curl = curl_init(DONWLOAD_REPORT);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));
curl_setopt($curl, CURLOPT_USERPWD, $api_key);
$file = curl_exec($curl);
if ($file === false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
header('Content-type: ' . 'application/octet-stream');
header('Content-Disposition: ' . 'attachment; filename=report.pdf');
echo $file;
}
I have same problem with you,
I am using this code, and it works, return a pdf file from webservice.
$api = new RestClient(array(
'base_url' => 'http://another-webservice.com/',
'headers' => array(
'X-Token' => $res->headers->x_token,
'Accept' => 'application/pdf',
),
));
$result = $api->execute("reports/report",'GET', $params);
$filename = 'Report.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo $result->response;
References: How to display PDF in Browser

fopen on url and bytestream

i have a question about fopen() and base64 comunication.
The scenario is that: i have a service A that must fetch from url a resource (png/jpeg or pdf). The code is that:
$uri = urldecode($_POST['uri']);
$imgfile = $uri;
$handle = fopen($uri, 'r');
$imagebinary = '';
while (!feof($handle)) {
$c = fgetc($handle);
if($c === false) break;
$imagebinary .= $c;
}
fclose($handle);
$return = base64_encode($imagebinary);
Now i have JQUERY function that send this $return (something like that: 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs') to another PHP service, named B.
B service take this string and try to save it on disk. In the specific the service B try to save the file on amazon s3, the code is that:
// in $imagedata is saved the string generated by service A
$imagedata = $_POST['serviceA_base64encodedfile'];
// $contentType taken from switch function on $ext
// for example 'image/png'
$filename = sha1(uniqid()) . '.' . $ext;
$full_filename = $path . '/' . $filename;
$stream = fopen('data://' . $contentType . ';base64,' . $imagedata, 'r');
fseek($stream, 0);
$opt = array(
'fileUpload' => $stream,
'acl' => AmazonS3::ACL_PUBLIC,
'contentType' => $contentType
);
$s3 = new AmazonS3(AWS_KEY, AWS_SECRET_KEY);
$response = $s3->create_object($bucket, $filename, $opt);
But the image that being saved is corrupted, in additionals this images or pdf have less bytes then orginal.
I need realy help :D
I'm not 100% sure this will work, but why not base64_decode the data back to binary, then write the data to a temporary file and send it to amazon from that location. Something like (untested):
// in $imagedata is saved the string generated by service A
$imagedata = base64_decode($_POST['serviceA_base64encodedfile']);
if (!$imagedata){
//Handle invalid base64 encoded data
}
// $contentType taken from switch function on $ext
// for example 'image/png'
$filename = sha1(uniqid()) . '.' . $ext;
$full_filename = $path . '/' . $filename;
$tmpfname = tempnam("/tmp", "image_to_upload");
$populated = file_put_contents($tmpfname,$imagedata);
if (!$populated){
//handle write failures
}
$opt = array(
'fileUpload' => "/tmp/".$tmpfname,
'acl' => AmazonS3::ACL_PUBLIC,
'contentType' => $contentType
);
$s3 = new AmazonS3(AWS_KEY, AWS_SECRET_KEY);
$response = $s3->create_object($bucket, $full_filename, $opt);
I'm also presuming on the last call, that $full_filename is where you want to store the file on the s3 server... though you can just use $file_name.

Categories