Manually add files in $_FILES - php

I need to add manually files into $_FILES, then I use this method :
public function addToFiles($key, $filename): void {
$tempName = tempnam('/tmp', 'php_files');
$originalName = basename(parse_url($filename, PHP_URL_PATH));
$rawData = file_get_contents($filename);
file_put_contents($tempName, $rawData);
$_FILES[$key]['name'][] = $originalName;
$_FILES[$key]['type'][] = mime_content_type($tempName);
$_FILES[$key]['tmp_name'][] = $tempName;
$_FILES[$key]['error'][] = 0;
$_FILES[$key]['size'][] = strlen($rawData);
}
I see temporary file in temporary directory but move_uploaded_file () return false.
What wrong with this code ?
Thank you

Related

=Error to convert and store base64 encoding to an image in laravel 5.4

I am trying to convert and store base64 encoding to an image in laravel 5.4. Here $ifphoto has base64 value. I also checked it using return. I have visitor_photo folder in public folder. How can I store that. My controller function is here. Thanks in advance
public function store(Request $request)
{
$visitor = new visitor() ;
$ifphoto = $request->v_photo;
if (isset($ifphoto)) {
define('UPLOAD_DIR', 'public/visitor_photo/');
$encoded_data = $ifphoto;
$img = str_replace('data:image/jpeg;base64,', '', $encoded_data );
$data = base64_decode($img);
$file_name = 'image_'.date('Y-m-d-H-i-s', time()); // You can change it to anything
$file = $file_name . '.png';
$request->v_photo->move(base_path('public/visitor_photo'), $file);
// $file = UPLOAD_DIR . $file_name . '.png';
// $success = file_put_contents($file, $data);
$visitor->v_photo = $file_name;
}
$visitor->save();
return redirect('/home');
}
Below code will store your base64 string as image in app/public folder. You can change the path as per your requirement.
Code :
if (isset($ifphoto)) {
$file_name = 'image_'.date('Y-m-d-H-i-s', time()).'.png';
if($ifphoto!=""){
\Storage::disk('public')->put($file_name,base64_decode($ifphoto));
}
}

yii2 REST api for file upload

Im trying to upload a file image/file type from mobile app and store that image in the backend. Im using Yii2 framework API to do this. And im using postman to check the API. Im running the below in my action.
/*Uploading documents*/
public function actionUploading_doc() {
$uploads = \yii\web\UploadedFile::getInstanceByName('upfile');
print_r($uploads);exit;
if (empty($uploads)){
return "Must upload at least 1 file in upfile form-data POST";
}
foreach ($uploads as $file){
$filename = time() . $image->name;
$path = "uploads/" . $filename;
$file->saveAs($path);
}
}
When i run this as POST method from postman.. and print the value of $uploads im getting empty value. It mean its not coming to controller.
Please help me in solving this.
For me this is what i did without the UploadFile class
/*Uploading documents*/
public function actionUploading() {
$uploads = \yii\web\UploadedFile::getInstanceByName('upfile');
\yii::$app->request->enableCsrfValidation = false;
$filename = $uploads->name;
$path = "http://localhost/projects/YiiRestful/api/web/uploads/".$filename;
$putdata = fopen("php://input", "r");
// make sure that you have /web/upload directory (writeable)
// for this to work
$path = "uploads/".$filename;
$fp = fopen($path, "w");
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
}
I would try something like this... (not tested)
public function actionUploadingDoc() { // good practice to use camel case for methods
$uploads = \yii\web\UploadedFile::getInstances('upfile');
if (empty($uploads)){
return false;
// handle error reporting somewhere else
}
$path = 'uploads/'; // set your path
foreach ($uploads as $upload){
$filename = $path . time() .'_'. $upload->name ;
$upload->saveAs($filename);
}
return true;
}
You can use base64 string to uplod. define function inside controller like this
public function base64_to_jpeg($base64_string, $output_file) {
$path="your/real/path/";
// open the output file for writing
$ifp = fopen( $path.$output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
if(count($data)>1) {
$dataText=$data[ 1 ];
} else {
$dataText=$base64_string;
}
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $dataText ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
And use inside action as
public function actionUpload(){
$imgName=md5(uniqid()).'.jpg';
$this->base64_to_jpeg($base64_string, $imgName);
}

How to move files to another folder in php

I have 4 csv files in "files" folder & I want to move these files with content to another folder (i.e. backups),Files are given below.
abc.csv
abc1.csv
abc2.csv
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
$rename_file = $file.'_'.$date;
move_uploaded_file($rename_file, "$destination");
}
Since you are not uploading any files, try rename() function instead.
$Ignore = array(".","..","Thumbs.db");
$OriginalFileRoot = "files";
$OriginalFiles = scandir($OriginalFileRoot);
$DestinationRoot = "backups";
# Check to see if "backups" exists
if(!is_dir($DestinationRoot)){
mkdir($DestinationRoot,0777,true);
}
$Date = date('Y-m-d');
foreach($OriginalFiles as $OriginalFile){
if(!in_array($OriginalFile,$Ignore)){
$FileExt = pathinfo($OriginalFileRoot."\\".$OriginalFile, PATHINFO_EXTENSION); // Get the file extension
$Filename = basename($OriginalFile, ".".$FileExt); // Get the filename
$DestinationFile = $DestinationRoot."\\".$Filename.'_'.$Date.".".$FileExt; // Create the destination filename
rename($OriginalFileRoot."\\".$OriginalFile, $DestinationFile); // rename the file
}
}
The function move_uploaded_file is relevant for uploading files, not for other things.
To move file in the filesystem you should use the rename function:
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
if (!is_file($file)) {
continue;
}
$rename_file = $destination.$file.'_'.$date;
rename($file, $rename_file);
}

php upload isset and rename file if it's exist

I know, there are many solutions for this question, but unfortunately I couldn't solve it, Here is my upload code:
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true)
{
$ret = false;
if (isset($file['tmp_name']) && isset($file['name']))
{
if ($destinationName == '')
{
$destinationName = $file['name'];
}
$destinationFile = $destinationDir . '/' . $destinationName;
if (move_uploaded_file($file['tmp_name'], $destinationFile))
{
if ($secure)
{
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
return $ret;
}
1: How can I rename file while uploading to server ?
2: If file name is exist then how to rename it automatically?
Thanks in advance
Use file_exists for this case :
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){
$ret = false;
if(isset($file['tmp_name']) && isset($file['name'])){
if ($destinationName == ''){
$destinationName = md5($file['name']);
}
$destinationFile = $destinationDir.'/'.$destinationName;
if(file_exists($destinationFile)){
// Change the destination file name if it exists
$destinationFile = $destinationDir.'/'.md5($destinationName.rand());
}
if (move_uploaded_file($file['tmp_name'], $destinationFile)){
if($secure){
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
Note:
move_uploaded_file — Moves an uploaded file to a new location
structured like this
bool move_uploaded_file ( string $filename , string $destination )
in $destination parameter you give the name of your new uploaded file. Name your file to something that unique. Whatever !, so don't worry about this

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!

Categories