I would like to use the following class to resize my image before storing it on my server: https://www.verot.net/php_class_upload.htm?lang=en-GB
I have image data stored in a MySQL table encoded as base64.
So far I've gotten this far:
$data = $myBase64DataFromDb;
//if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
// $data = substr($data, strpos($data, ',') + 1);
// $type = strtolower($type[1]); // jpg, png, gif
// $data = base64_decode($data);
$path = '/img/put/here/';
// $filename = $data.'.'.$type;
// $handle = new upload($filename);
$handle = new upload($data);
$handle->file_max_size = '5000000';
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = true;
$handle->process($path);
if ($handle->processed) {
echo $filename;
$handle->clean();
} else {
echo 'error : ' . $handle->error;
}
// }
I keep getting error:
error : File not uploaded. Can't carry on a process.
What am I missing?
Related
am trying to upload .mp4 files with php but it's not working. Here's the script:
PHP Class to handle the upload:
class CustomFileUpload
{
public static function upload($data)
{
$errors = [];
$response = [];
$file = htmlentities(trim($data['file']['name']), ENT_QUOTES, 'UTF-8');
$tmpDir = $data['file']['tmp_name'];
$fileSize = $data['file']['size'];
$fileExt = strtolower(pathinfo($file,PATHINFO_EXTENSION));
$validExtensions = ['mp3', 'mp4'];
$uploadDir = '';
if ($fileExt == "mp4") {
$uploadDir = './public/ex-media/videos/';
} elseif ($fileExt == "mp3") {
$uploadDir = './public/ex-media/audios/';
} else {
$errors['msg'] = 'file type not allowed.';
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
if(!in_array($fileExt,$validExtensions))
{
$errors['msg'] = "Invalid extension detected for selected image file, please use a supported image extension.";
$errors['ext-detected'] = $fileExt;
}
if(empty($errors))
{
$uuid = explode("-", $data['uuid']);
$fileNewName = $uuid[0]."-".time().".".$fileExt;
var_dump($tmpDir);
exit();
$moved = move_uploaded_file($tmpDir, $uploadDir.$fileNewName);
if ($moved) {
$response['status'] = 200;
$response['msg'] = "success";
$response['fileUrl'] = $fileNewName;
echo('heres ur newly uploaded file - '.$fileNewName);
exit();
return $response;
} else {
$response['status'] = 502;
$response['msg'] = "failed";
$response['error'] = "upload failed for UNKNOWN reasons!";
echo('error while uploading file - go to CustomFileUpload.php');
exit();
return $response;
}
}
else {
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
}
}
PHP Controller Action that calls the CustomFileUpload class:
public function uploadAction()
{
$response = ['status_code' => 404];
if ($this->getRequest()->isPost())
{
$data = $this->params()->fromPost();
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$fileUpload = CustomFileUpload::upload($data);
}
return new JsonModel($response);
}
If I upload an mp3 file, it works perfectly but for mp4, it's the opposite. So I tried to dump the content of the tmp_dir var_dump($tmpDir); exit(); as seen the CustomFileUpload class. After doing this, it turns out that the tmp_dir is empty for mp4 files which is not so for the mp3 files as seen in the screenshots below (taken from Postman).
tmp_dir IS NOT EMPTY for mp3 file:
enter image description here
tmp_dir IS EMPTY for mp3 file:
enter image description here
Please, how do I fix these?
I've spend all day figuring out how to store an image in tmp, change its size and then upload it to my S3 bucket. The S3 bucket works fine and i am able to upload images when i don't resize. The resize function is the createThumbnail function and works fine when not combined with S3 probably because it's a wrong format or something. The second file "init.php" contains all the functions. The images are uploaded to the temp folder but when i run the script it doesn't get uploaded after it's resized. I don't get any error logs on localhost and when i upload the code to my AWS instance it just returns a internal server error but the error log in my instance is oddly empty... I need some fresh eyes on this issue.
banner_image.php
<?php
include "init.php";
if (#session($_SESSION["buddy"])){
$valid_file_formats = array("jpg","png","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST" && !empty($_FILES['banner_image']['tmp_name']) && !empty($_FILES['banner_image']['name'])){
$folder = usernameFromEmail($_SESSION["user"]); // session based on users email
$buddy = $_SESSION["user"];
$name = $_FILES['banner_image']['name'];
$size = $_FILES['banner_image']['size'];
$path = $folder."/cover/"; // path to image folder
$temp = explode(".", $name);
$newfilenameKey = round(microtime(true)); // generating random file name
$newfilename = $newfilenameKey . "." . "png"; // always using png
if(strlen($newfilename) && strlen($name)) {
$ext = explode(".", $name);
$ext = end($ext);
if(in_array($ext,$valid_file_formats)) { // valid file format array check
if($size<=(10485760)) { // size check in bits
$tmp = $_FILES['banner_image']['tmp_name'];
$file_name = $path.$newfilename; // full path including file name
if(putS3IMG($bucket, $file_name, $tmp)){ // upload untouched image to S3 bucket
list($width, $height) = getimagesize($tmp);
$type = 2;
$w = 300;
$h = 300 * ($height / $width);
// getting new dimensions for the new image
if(createThumbnail(1,$tmp,$w,$h,$path,$file_name) == 1){ // function for smaller image
return json_encode(array("succ" => 1));
}
}
}
}
}
}
}
?>
here is my init.php file included in the banner_image.php file which contains my functions.
<?php
// connection to S3Client .... $client
function createThumbnail($type,$image_name,$new_width,$new_height,$uploadDir,$moveToDir){
global $bucket;
//$type: defines the name of the new file
//image_name: tmp name
//uploadDir: path
//moveToDir: files new path incl. file name
$mime = getimagesize($image_name);
if($mime['mime']=='image/png') {
$src_img = imagecreatefrompng($image_name);
} else if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$src_img = imagecreatefromjpeg($image_name);
}
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
$thumb_w = $new_width;
$thumb_h = $new_height;
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
$background = imagecolorallocate($dst_img, 0, 0, 0);
imagecolortransparent($dst_img, $background);
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
$image_name_new = explode(".", $moveToDir);
if ($type == 1){
$new_image_name = $image_name_new[0] . "_thumb." . $image_name_new[1];
} else if ($type == 2){
$new_image_name = $image_name_new[0] . "_image." . $image_name_new[1];
}
$tmpPath = tempnam(sys_get_temp_dir(), $new_image_name); // getting temporary directory
if($mime['mime']=='image/png') {
imagepng($dst_img,$tmpPath,8);
} else if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
imagejpeg($dst_img,$tmpPath,80);
}
imagedestroy($dst_img);
imagedestroy($src_img);
if(putS3IMG($bucket, $image_name, $tmpPath)){ // this part does not work
return 1;
} else {
return 2;
}
}
function putS3IMG($bucket, $file_name, $tmp){ // function uploading to my bucket
//file_name is with directories
//tmp is $_FILES tmp_name
global $client;
$result = $client->putObject([
'Bucket' => $bucket,
'Key' => $file_name,
'SourceFile' => $tmp
]);
if ($result){
return true;
}
return false;
}
SOLUTION:okay, so eventually i ended up using AWS lambda which solved the issue but it isn't a free solution. So, if any of you come up with a solution that allow you to resize without using third party tools feel free to comment it in order to make life easier for the next programmers viewing this question.
I am developing a module for my client to upload and browse file in Opencart.
when I am uploading file from my back-end server I am getting the output as file.zip.xyzasdf. Where I just want to remove this .xyzasdf
Can any one suggest me how to remove sanitize from the following code...
public function upload() {
$this->load->language('catalog/download');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'catalog/download')) {
$json['error'] = $this->language->get('error_permission');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array();
$extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));
$filetypes = explode("\n", $extension_allowed);
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array();
$mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));
$filetypes = explode("\n", $mime_allowed);
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Check to see if any PHP files are trying to be uploaded
$content = file_get_contents($this->request->files['file']['tmp_name']);
if (preg_match('/\<\?php/i', $content)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
$file = $filename . '.' . token(32);
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_FOLDER . $file);
$json['filename'] = $file;
$json['mask'] = $filename;
$json['success'] = $this->language->get('text_upload');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Any help would be greatly appreciated...
Thanks
Removing the random string that is added to the filename is simple. Just change
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);
to:
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $filename);
But keep in mind that this will bring problems.
OpenCart saves the random string in the database at the time of file upload, so it will later use it to identify the file.
If you delete this feature, the uploaded files in the admin panel will not be available.
I was using php codeigniter 2.x now i updated it to 3.x, after that my upload code is not working.
this is my code. please go though it.
when this code is working always getting the error
The upload path does not appear to be valid.
$this->load->library('upload');
$session = $this->ifisSession();
$uploadfolder = 'profileImgs';
$fullPath = 'abc';
$imageconfig['upload_path'] = $fullPath;
$imageconfig['max_size'] = (1024); // 1mb file size
$imageconfig['allowed_types'] = 'gif|jpg|png';
$imageconfig['max_width'] = (1024 );
$imageconfig['max_height'] = (1024);
$fieldName = 'profileimage';
//$uploadfilename = $_FILES[$fieldName];
$uploadfilename = $_FILES[$fieldName]['name'];
// printv($uploadfilename, 'this ihere');
$fileinfo = pathinfo($uploadfilename);
if (isset($fileinfo['extension'])) {
$ext = $fileinfo['extension'];
$imageconfig['file_name'] = $session['firstname'] . '_' . $session['user_id_pk'] . '_' . uniqid() . '.' . $ext;
}
$this->load->library('upload', $imageconfig);
if (!$this->upload->do_upload('profileimage')) {
$error = $this->upload->display_errors();
$data['data']['profileUpdate_error'] = $error;
// move to profile page with erro message
} else {
$profileUploadinfo = array('upload_data' => $this->upload->data());
$profileimgurl = '';
$res = $this->Model_userinfo->updateProfileImg($session['user_id_pk'], $profileimgurl);
if($res > 0){
$data['data']['profileUpdate_success'] = 'Profile Updated';
}else{
$data['data']['profileUpdate_error'] = 'Profile Not updated';
}
}
I'm writing a Joomla 1.5 extension for an advanced frontend user interface.
Now I have to add a function so the users can upload a picture in the frontend and it will be added to their account.
Is there a standard Joomla picture upload available or something?
Thanks
I have this is my code: (and some more I can not paste everything in here)
function deleteLogo($logo)
{
// define path to file to delete
$filePath = 'images/stories/members/' . $logo;
$imagePath = 'images/stories/members/image/' . $image;
// check if files exists
$fileExists = JFile::exists($filePath);
$imageExists = JFile::exists($imagePath);
if($fileExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($filePath);
}
if($imageExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($imagePath);
}
}
function saveLogo($files, $data)
{
$uploadFile = JRequest::getVar('logo', null, 'FILES', 'ARRAY');
$uploadImage = JRequest::getVar('image', null, 'FILES', 'ARRAY');
$save = true;
$saveImage = true;
if (!is_array($uploadFile)) {
// #todo handle no upload present
$save = false;
}
if ($uploadFile['error'] || $uploadFile['size'] < 1) {
// #todo handle upload error
$save = false;
}
if (!is_uploaded_file($uploadFile['tmp_name'])) {
// #todo handle potential malicious attack
$save = false;
}
if (!is_array($uploadImage)) {
// #todo handle no upload present
$saveImage = false;
}
if ($uploadImage['error'] || $uploadImage['size'] < 1) {
// #todo handle upload error
$saveImage = false;
}
if (!is_uploaded_file($uploadImage['tmp_name'])) {
// #todo handle potential malicious attack
$saveImage = false;
}
// Prepare the temporary destination path
//$config = & JFactory::getConfig();
//$fileDestination = $config->getValue('config.tmp_path'). DS . JFile::getName($uploadFile['tmp_name']);
// Move uploaded file
if($save)
{
$this->deleteLogo($data['oldLogo']);
$fileDestination = 'images/stories/members/' . $data['id'] . '-' . $uploadFile['name'];
$uploaded = JFile::upload($uploadFile['tmp_name'], $fileDestination);
}
if($saveImage)
{
$this->deleteLogo($data['oldImage']);
$fileDestination = 'images/stories/members/image/' . $data['id'] . '-' . $uploadImage['name'];
$uploadedImage = JFile::upload($uploadImage['tmp_name'], $fileDestination);
}
}