Error with file upload as base64 encoded string - php

I want to receive an image from an android device, which is sending an image as a Base64 encoded string. This is my controller action code:
public function Upload()
{
if ($this->request->is('post')) {
$dir= APP.'outsidefiles'; //chane directory for cloud
$fill = $this->request->data['File'] ;
$data = base64_decode($fill);
$im = imagecreatefromstring($data);
if ($im !== false)
{
$nam ='mypic.png';
move_uploaded_file($im['tmp_name'],$dir.DS.time().$nam);
}
//$dir= APP . 'outsidefiles';
// $this->request->data['Grade']['Fila']= $File;
$this->Grade->create();
if ($this->Grade->save($this->request->data))
{
$return = array(
'Response' =>'1',
'Body' => 'Data Saved');
return new CakeResponse(array('body' => json_encode($return, JSON_NUMERIC_CHECK)));
}
else
{
$return = array(
'Response' =>'0',
'Body' => 'Data not saved');
return new CakeResponse(array('body' => json_encode($return, JSON_NUMERIC_CHECK)));
}
}
}
However the image is not created in the destination folder - what is the error?

move uploaded file is for moving uploaded files
This will not work:
move_uploaded_file("I am not a file upload" , "/put/file/here/path.png");
It won't work even if the first argument points at a file because, as stated in the documentation:
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
This prevents this kind of naïve attack from working:
// User input is not safe, it could be e.g.:
$_FILES['example']['tmp_name'] = '/etc/passwd';
...
move_uploaded_file(
$_FILES['example']['tmp_name'],
"/web/accessible/location/now-public.txt"
);
image create from string does not return an array
This also won't work:
$im = imagecreatefromstring($data);
$im['tmp_name']; <-
As, the return value from this function is an image resource, not an array. tmp_name related to file uploads - there is no actual file upload if it is being submitted as a base64 encoded string; it's just a string.
To upload a base64 encoded string means only creating a file
The logical steps required are not related to file uploads at all, only writing a binary string to a file i.e.:
$data = base64_decode($fill);
file_put_contents('/tmp/pic.png', $data);

Related

Error in uploading image when using cpanel

when developing locally, i was able to upload images in storage directory, but now as the diectory sructure changed a bit.
Now Intervention is showing an error.
Error is
message: "Image source not readable", exception: "Intervention\Image\Exception\NotReadableException",…}
exception: "Intervention\Image\Exception\NotReadableException"
This is my controller
public function submitAddProduct(Request $request){
$data = $request->validate([
'image' => ['required','image'],
'image_second' => ['required','image']
]);
//dd(request('image')->store('uploads','public'));
$imagePath = request('image')->store('uploads','public');
$image = Image::make(public_path("storage/{$imagePath}"));
$image->save();
$imagePath2 = request('image_second')->store('uploads','public');
$image2 = Image::make(public_path("storage/{$imagePath2}"));
$image2->save();
$dataVal = $request->all();
$dataVal['image'] = $imagePath;
$dataVal['image_second'] = $imagePath2;
// d3d($dataVal);
$d = Products::create($dataVal);
$id = $d->id;
if($id){
$arr = array('msg' => $id);
}
return Response()->json($arr);
}
it should get stored in the uploads directory.
My cpanel directory structure is as follows
The public_html contains
And the system folder inside the public_html contains
The symlinks are working fine, as i can see images that were previously present in uploads.
symlink.php is
<?php
symlink('/home//public_html/system/storage/app/public','/home//public_html/storage');
Only the first Image gets uploaded to storage/uploads and then interventions shows error.
Please Help

Drupal 8: The file could not be created

I have below code to upload excel file provided by API in base64_encode format.
I would like to download that file and save in to file system.
public function import(Request $request) {
if ($request->getMethod() === 'POST') {
$data = json_decode($request->getContent(), TRUE);
$directory = 'public://import/';
// create directory if it does not exist
file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$uri = $directory. $data['name'];
$files_data = preg_replace('#^data:application/\w+;base64,#i', '', $data['data']);
$file_data = base64_decode($files_data);
$file = file_save_data($file_data, $uri, FILE_EXISTS_RENAME);
echo $file->id();
}
}
It goes to below function and gives error, although I have created tmp folder on project root and given needed 777 permission.
/drupal/web/core/includes/file.inc
function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
// Write the data to a temporary file.
$temp_name = drupal_tempnam('temporary://', 'file');
if (file_put_contents($temp_name, $data) === FALSE) {
\Drupal::messenger()->addError(t('The file could not be created.'));
return FALSE;
}
// Move the file to its final destination.
return file_unmanaged_move($temp_name, $destination, $replace);
}
What I am missing? It is not converting and saving file.
Usually this happen because of wrong temporary location and permission, what I suggest you is go to /admin/config/media/file-system and make sure you set Temporary Directory correctly. if its fine. check the permission of it. you need to set it writeable by webservice.
Fixed
On URL : domain.com/admin/config/media/file-system
Temporary directory -> Folder location and permission issue.

laravel 5 mime image validation throws exception when uploading an mp3 or mp4

ok.. i don't know how many of you had this problem in Laravel.. i could not find any solution for this.
i'm validating the uploaded image using Validator by setting rules with mime type jpeg, bmp and png.
I flash an error message if it's not of these types.
It works fine for all file types, but when i upload an mp3 or mp4 it shows an exception in my controller.
MyImageController.php Code :
public function addImageDetails()
{
$input = Request::all();
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
$rules = array('image' => 'required|mimes:jpeg,jpg,bmp,png');
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
\Session::flash('flash_message_error','Should be an Image');
return view('addDetails');
}
else {
//If its image im saving the ID, name and the image in my DB
}
This is the error that i get when i upload an mp3 or mp4
ErrorException in MyImageController.php line 25:
Undefined index: ID
validating all other file types like [.txt, .doc, .ppt, .exe, .torrent] etc..
Once you Allocate the Request::all(); to the variable $input
$input = Request::all();
Then you should check whether it has any value
if (isset($input['ID']))
If the condition satisfies the you shall allow it to proceed further steps else you should return the view with your error message like the code given below.
if (isset($input['ID']))
{
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
}
else
{
return view('addDetails')->with('message', 'Image size too large');;
}
Update :
Here you check for image type
if (isset($input['ID']))
{
if (Input::file('image'))
{
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
else
{
return view('addDetails')->with('message', 'Uploaded file is not an image');;
}
}
else
{
return view('addDetails')->with('message', 'Image size too large');;
}
Try with this clean code:
public function addImageDetails(Request request){
$this->validate($request, [
'image' => ['required', 'image']
]);
//If its image im saving the ID, name and the image in my DB
}
There is a rule called image that could be helpful for you in this situation

Zend File rename after uploading zend form

I'm not getting the information I am looking for from research. I'd like to perform a rename on the file upload after it has uploaded. I need the original filename as well as renaming it. Here is what I have so far:
$form = new Sam_Form_Database($this->resource);
$form->setMethod(Zend_Form::METHOD_POST);
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$data = $form->getValues();
try {
$form->fileelement->receive();
$originalFilename = pathinfo($form->fileelement->getFileName());
$newFilename = Sam_Util::generateHash().'.'.$originalFilename['extension'];
$filterFileRename = new Zend_Filter_File_Rename(array(
'target' => $newFilename,
'overwrite' => true,
'keepExtension' => true
));
$filterFileRename->filter($form->fileelement->getFileName());
} catch(Exception $e){
Sam::exception("Cannot upload file");
}
Sam_Util::insertDataIntoDatabase($data,$this->resource);
Sam_Util::redirectSimple('list');
}
The problems:
nothing seems to be uploading
before when it was uploading it wasn't renaming the file in the destination
What I need is a fluent way to handle uploading, retrieving the original filename, and performing a rename on the target file using zend.

multi picture upload in zend framework, how to?

i have an issue with uploading multiple files to disk. here is my code.
i have a request with 2 pictures that gets sent to a upload function. the 2 pictures are in a var called $multiUpload
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$file = array();
$filename = array();
foreach($multiUpload as $key=>$val){
// get the file extension
$file[] = explode('.',$val);
// create custom file name
$filename[] = time().'.'.$file[$key][1];
//send to the upload function
$this->uploadToDisk($folderPath, $filename[$key]);
// sleep 1 sec so that the pic names will be different
sleep(1);
}
return $filename;
}
public function uploadToDisk($folderPath, $filename)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination($folderPath);
$adapter->addFilter( 'Rename',array(
'target' => $folderPath."/".$filename,
'overwrite' => true
) );
if ($adapter->receive()) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
this will return
Array
(
[0] => Array
(
[0] => 1332977938.jpg
[1] => 1332977939.jpg
)
)
but only array[0][0] or 1332977938.jpg will actually get saves to the disk.
Why are they now both get saved? wired
any ideas?
I suspect the second call to uploadToDisk is returning fail because you can only call Zend_File_Transfer_Adapter_Http::receive() once for each file. Since you are not specifying a file when calling receive, it is receiving all of the files the first time you call uploadToDisk and subsequently is failing with a File Upload Attack error.
Here is some code you can try. This tries to receive each file individually and then save them one at a time with each call to uploadToDisk.
A few notes about the code:
The first parameter to uploadToDisk ($val) may need to be changed as I am not sure what the original values are. It should correspond to one of the element names used for the file upload (See Zend_File_Transfer_Adapter_Http::getFileInfo()) for a list of the files.
I changed the method for generating a unique filename so you don't have to sleep(1)
Zend_File_Transfer_Adapter_Abstract::setDestination() is deprecated and will go away in the future. Instead, just use the Rename filter. When using Rename, setDestination() has no effect.
And here it is...
<?php
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$filenames = array();
foreach($multiUpload as $key => $val){
// get the file extension
$ext = explode('.', $val);
$ext = $ext[sizeof($ext) - 1];
// create custom file name
do {
$filename = uniqid(time()) . '.' . $ext;
$diskPath = $folderPath . $filename;
} while (file_exists($diskPath));
$filenames[$key] = $filename;
//send to the upload function
// $val is the file to receive, $diskPath is where it will be moved to
$this->uploadToDisk($val, $diskPath);
}
return $filename;
}
public function uploadToDisk($file, $filename)
{
// create the transfer adapter
// note that setDestination is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($file)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}

Categories