How to save Data Url like save $_FILES in php - php

How to save DATA URL like save $_FILES in php?
my code is:
$dataurl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAB...."
$image_content = base64_decode(str_replace("#^data:image/\w+;base64,#i","", $dataurl)); // remove "data:image/png;base64,"
$tempfile = tmpfile(); // create temporary file
$filesize = fwrite($tempfile, $image_content); // fill data to temporary file
$metaDatas = stream_get_meta_data($tempfile);
$tmpFilename = $metaDatas['uri'];
$file = array(
'name' => 'MyFile.jpg',
'type' => 'image/jpeg',
'tmp_name' => $tmpFilename,
'error' => 0,
'size' => $filesize,
);
move_uploaded_file($file['tmp_name'], $location);
The problem maybe in move_uploaded_file($file['tmp_name'], $location);

Read the description in PHP guide for move_uploaded_file before using this function.
The important part is (qoute from the description):
This function checks to ensure that the file designated by filename is
a valid upload file (meaning that it was uploaded via PHP's HTTP POST
upload mechanism). If the file is valid, it will be moved to the
filename given by destination.
The file you created was NOT uploaded via PHP HTTP POST upload mechanism, it was a temporary file you have created yourself, so you can not move it with this function.
If the data arrives as a Base64 encoded string, you can just write the file directly to the desired location. The move_uploaded_file function is ONLY for files uploads, and Base64 strings sent in the body are not files.

Related

how to not generate hash when uploading image files to ftp server with laravel?

so I have successfully uploaded the image file to the ftp server and the image file is shaped like an auto generated hash file name, so how do I make the file name I upload is the same as the image name?, because when it is saved to the database it is not hashed but the name the file is the same as the uploaded image, but on the ftp server when saving it the file name is shaped like a hash
example upload file in ftp server :
example controller :
$lampiran = Lampiran_tte::where('surat_tte_id', $surat->id);
if ($request->hasfile('lampiran_gambar')) {
$files = [];
foreach ($request->file('lampiran_gambar') as $file) {
if ($file->isValid()) {
$filename = $file->getClientOriginalName();
$file->store('/lampiranSurat', 'ftp') . '/' . $filename;
$files[] = [
'lampiran_gambar' => $filename,
];
}
}
$gambar = '';
foreach ($files as $value) {
$gambar .= $value['lampiran_gambar'].'#';
}
$gambar = substr($gambar, 0, -1);
$lampiran->update([
'isi_lampiran' => $request->isi_lampiran,
'lampiran_gambar' => $gambar,
'update_by' => Auth::user()->name,
]);
}
if it is already stored in the database,
the image file name matches the image file name that was uploaded
example in database :
The store() function is generating the unique ID value for the file. Use the storeAs() function instead which allows you to specify a filename of your choice.
$file->storeAs('/lampiranSurat', $filename, 'ftp');

Store blob as a file in S3 with Laravel

I am using a file upload plugin in Vue to upload some image and pdf files through an API and it has an option to create a blob field when uploading the files.
The request sent to Laravel is as follows. I can access the blob from the browser by copying and pasting the URL on the browser.
On the Server side code, I am trying to save the file with the following code but the saved file is some corrupted 64byte file rather than the actual image. How would we store the blob as a normal file in the filesystem?
if ($request->has('files')) {
$files = $request->get('files');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('s3')->put($filename, $file['blob']);
Storage::disk('s3')->setVisibility($filename, 'public');
$url = Storage::disk('s3')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
Try by replacing this:
Storage::disk('s3')->put($filename, $file['blob']);
with this:
Storage::disk('s3')->put($filename, base64_decode($file['blob']));

How to encode the image file in PHP

i am using one file upload form field,from that field i want to encode the filename,don't to want to move the any temporary folder,directly i want to insert the database,while display the image directly fetch DB and display the website,I want encode like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA
$path = basename($_FILES['file']['name']);//here i am getting filename
$im = file_get_contents($path);//here i am getting false
$imdata = base64_encode($im); // so can't here encode the filename
$horoscope = array("encode" => $imdata,"path" =>$path,"getcontents" =>$im);
echo json_encode($horoscope);
PHP uploads the file into a temporary file and tells you where that is in the $_FILES['file']['tmp_name'] the $_FILES['file']['name'] holds the file name that the user called the file on their system, the one they select in the browser.
So if you want to grab the file before you have done a move_uploaded_file() on the file use $_FILES['file']['tmp']
$path = $_FILES['file']['tmp_name'];
$im = file_get_contents($path);
$imdata = base64_encode($im);
$horoscope = array("encode" => $imdata,
"path" =>$path,
"getcontents" =>$im
);
echo json_encode($horoscope);
I was not sure what you were passing back the $path for, so that may still need to be $_FILES['file']['name'].
$horoscope = array("encode" => $imdata,
"path" => $_FILES['file']['name'],
"getcontents" => $im
);
RE:Comment 1
I assume you want to store the base64encoded version of the file to the database so that will be $imdata
RE:Comment 2
To get the extension of the incoming file use pathinfo()
$path = $_FILES['file']['tmp_name'];
$file_parts = pathinfo($path);
$extn = $path_parts['extension'];
But beware, just because the extension says .png is not actual guarantee that it is a .png file

Uploading a base64 image as an image file

So I'm receiving an image in base64 encoding. I want to decode the image and upload it in a specific directory. The encoded file is an image and I'm using $file = base64_decode($base64_string); to decode it. Uploading it via file_put_contents('/uploads/images/', $file); always results in failed to open stream: No such file or directory error.
So, how do I take the decoded string, and upload it on a specific path?
Thanks.
Your path is wrong.
/uploads/images
is checking for a folder in the / directory called uploads. You should specify the full path to the folder:
/var/www/vhosts/MYSITE/uploads/images
I had the same problem and finally solved using this:
<?php
$file = base64_decode($base);
$photo = imagecreatefromstring($file);
//create a random name
$RandomStr = md5(microtime());
$name = substr($RandomStr, 0, 3);
$name .= date('Y-m-d');
$name .= '.jpg';
//assign name and upload your image
imagejpeg($photo, 'images/'.$name, 100);

Retrieving external image and saving locally results in distorted image

Stuck on this one. I have this function below that simply takes $ImageSrc which is an external image from anywhere, eg imgur, and then saves it locally (this is not a scraper, I'm allowing people to attach images to their profiles)
public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
$RandomName = substr(md5($Title . time()), 0, 20);
$UploadDir = "/home/vanrust/public_html/Screenshots/";
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
$image = file_get_contents($ImageSrc);
file_put_contents($UploadDir . $RandomName, $image);
}
The result of the file no matter what is unrecognizable.
The image:
After UploadScreenshot() has retrieved it:
Try to use rename() to move the original file to the new location and rename it.
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);
}
Alternatively, you can use move_uploaded_file() if your $ImageSrc does contain a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
file_put_contents() needs to be used with caution. A single offset (in binary codes) at the beginning or at the end of the file will significantly alter the picture. It requires a validation at the end to compare both files bytes.

Categories