convert base64 image to jpg then upload to server not working - php

I am new to base64 and I have never needed to convert it so I am not sure what is going on here. I have my base64 string in $socialmedia_image. I create a random file name with rand. I plug it into the function which I got off stack and....nothing. It does not convert or transfer over with move_uploaded_file and I have no idea who to check for an error.
Can someone tell me what I am doing wrong?
///// base64 string /////
$socialmedia_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg.....";
$rand = rand(000000000000000,999999999999999);
$output_file = $rand.".jpg";
$socialmedia_image = base64_to_jpeg( $socialmedia_image, $output_file );
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen( $output_file, 'w' );
$data = explode( ',', $base64_string );
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
fclose( $ifp );
return $output_file;
}
move_uploaded_file($socialmedia_image, "../tickets/attachments/".$output_file);

How about that?
file_put_contents($output_file, $data);

Related

Base64 image string into image file using PHP

I need code to convert a base64 image string into an image file and write into local directory using PHP. I tried:
function user_profile_photo(){
$input = urldecode(file_get_contents('php://input'));
$received = json_decode($input, true);
$user_id = $received['user_id'];
$img = $received['imagecode'];
$imagedata = base64_decode($img);
$image_path='uploads/images/'.$user_id;
$path = '/var/www/html/empengapp/uploads/images/'.$user_id;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
$new_name = date('ymd').time().'.jpg';
$pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
$success = file_put_contents($pathwithfile, $imagedata);
var_dump($imagedata);exit;
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}//end of function user_profile_photo
It is writing a file with given extension, but when you try to open file it shows an invalid file error.
I figure it out the solution.
$pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'
$ifp = fopen( $pathwithfile, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $imagedata );
$success = fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource
fclose( $ifp );
I was sending over the API to PHP server. You need to encode your image base64 string and your image base64 string must include "data:image/jpeg;base64". We are splitting it on PHP server But don't think to send image base54 without "data:image/jpeg;base64".
But remember one thing you have to use image base64 including

Delete a specific line in a TXT file

I have a .txt file with millions of lines of text
The code below Delete a specific line (.com domains) in a .txt file. But large files can not do :(
<?php
$fname = "test.txt";
$lines = file($fname);
foreach($lines as $line) if(!strstr($line, ".com")) $out .= $line;
$f = fopen($fname, "w");
fwrite($f, $out);
fclose($f);
?>
I want to remove certain lines and put them in another file
For example, the list of domain names of sites. cut the .com domain and paste it in another file...
Here's an approach using http://php.net/manual/en/class.splfileobject.php and working with a temporary file.
$fileName = 'whatever.txt';
$linesToDelete = array( 3, 5 );
// Working File
$file = new SplFileObject( $fileName, 'a+' );
$file->flock( LOCK_EX );
// Temp File
$temp = new SplTempFileObject( 0 );
$temp->flock( LOCK_EX );
// Wite the temp file without the lines
foreach( $file as $key => $line )
{
if( in_array( $key + 1, $linesToDelete ) === false )
{
$temp->fwrite( $line );
}
}
// Write Back to the main file
$file->ftruncate(0);
foreach( $temp as $line )
{
$file->fwrite( $line );
}
$file->flock( LOCK_UN );
$temp->flock( LOCK_UN );
This may be slow though, but a 40 meg file with 140000 lines takes 2.3 seconds on my windows xampp setup. This could be sped up by writing to a temp file and doing a file move, but I didn't want to step on file permissions in your environment.
Edit: Solution using Rename/Move instead of second write
$fileName = __DIR__ . DIRECTORY_SEPARATOR . 'whatever.txt';
$linesToDelete = array( 3, 5 );
// Working File
$file = new SplFileObject( $fileName, 'a+' );
$file->flock( LOCK_EX );
// Temp File
$tempFileName = tempnam( sys_get_temp_dir(), rand() );
$temp = new SplFileObject( $tempFileName,'w+');
$temp->flock( LOCK_EX );
// Write the temp file without the lines
foreach( $file as $key => $line )
{
if( in_array( $key + 1, $linesToDelete ) === false )
{
$temp->fwrite( $line );
}
}
// File Rename
$file->flock( LOCK_UN );
$temp->flock( LOCK_UN );
unset( $file, $temp ); // Kill the SPL objects relasing further locks
unlink( $fileName );
rename( $tempFileName, $fileName );
It could be because of the large size of the file that its taking too much of space.
When you do file('test.txt'), it reads the entire file into an array.
Instead, you can try using Generators.
GeneratorsExample.php
<?php
class GeneratorsExample {
function file_lines($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
}
function copyFile($srcFile, $destFile) {
foreach ($this->file_lines($srcFile) as $line) {
if(!strstr($line, ".com")) {
$f = fopen($destFile, "a");
fwrite($f, $line);
fclose($f);
}
}
}
}
callingFile.php
<?php
include('GeneratorsExample.php');
$ob = new GeneratorsExample();
$ob->copyFile('file1.txt', 'file2.txt')
While you could use tens of lines of PHP code, one line of shell code will do.
$ grep Bar.com stuff.txt > stuff2.txt
or as PHP
system ("grep Bar.com stuff.txt > stuff2.txt");

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 convert base64 in to image in php? [duplicate]

This question already has answers here:
How to save a PNG image server-side, from a base64 data URI
(17 answers)
Closed 3 years ago.
I am trying to convert my base64 image string to an image file. This is my Base64 string:
http://pastebin.com/ENkTrGNG
Using following code to convert it into an image file:
function base64_to_jpeg( $base64_string, $output_file ) {
$ifp = fopen( $output_file, "wb" );
fwrite( $ifp, base64_decode( $base64_string) );
fclose( $ifp );
return( $output_file );
}
$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );
But I am getting an error of invalid image, whats wrong here?
The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.
function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
An easy way I'm using:
file_put_contents($output_file, file_get_contents($base64_string));
This works well because file_get_contents can read data from a URI, including a data:// URI.
You need to remove the part that says data:image/png;base64, at the beginning of the image data. The actual base64 data comes after that.
Just strip everything up to and including base64, (before calling base64_decode() on the data) and you'll be fine.
maybe like this
function save_base64_image($base64_image_string, $output_file_without_extension, $path_with_end_slash="" ) {
//usage: if( substr( $img_src, 0, 5 ) === "data:" ) { $filename=save_base64_image($base64_image_string, $output_file_without_extentnion, getcwd() . "/application/assets/pins/$user_id/"); }
//
//data is like: data:image/png;base64,asdfasdfasdf
$splited = explode(',', substr( $base64_image_string , 5 ) , 2);
$mime=$splited[0];
$data=$splited[1];
$mime_split_without_base64=explode(';', $mime,2);
$mime_split=explode('/', $mime_split_without_base64[0],2);
if(count($mime_split)==2)
{
$extension=$mime_split[1];
if($extension=='jpeg')$extension='jpg';
//if($extension=='javascript')$extension='js';
//if($extension=='text')$extension='txt';
$output_file_with_extension=$output_file_without_extension.'.'.$extension;
}
file_put_contents( $path_with_end_slash . $output_file_with_extension, base64_decode($data) );
return $output_file_with_extension;
}
That's an old thread, but in case you want to upload the image having same extension-
$image = $request->image;
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = str_replace(' ', '+', $imageInfo[1]);
$imageName = "post-".time().".".$imgExt;
Storage::disk('public_feeds')->put($imageName, base64_decode($image));
You can create 'public_feeds' in laravel's filesystem.php-
'public_feeds' => [
'driver' => 'local',
'root' => public_path() . '/uploads/feeds',
],
if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}
This code worked for me.
<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Upload base64 encoded images using Facebook sdk?

It's possible to upload base64 encoded images directly without saving it using Facebook PHP SDK 3.1.1?
$facebook->setFileUploadSupport(true);
$facebook->api('/me/photos', 'POST', array(
'source' => '#/mycoolpic.png', // No need to use FS, base64 encoded image
'message' => "I'm cool",
));
You can do as follow in PHP :
function base64_to_jpeg( $base64_string, $output_file ) {
$ifp = fopen( $output_file, "wb" );
fwrite( $ifp, base64_decode( $base64_string) );
fclose( $ifp );
return( $output_file );
}
$facebook->setFileUploadSupport(true);
$image = base64_to_jpeg( $your_base64_string, 'tmp.jpg' );
$args = array('message' => 'Some message');
$args['image'] = '#' . realpath( $image );
$data = $facebook->api('/your_user_id/photos', 'post', $args);
unlink($image);
No, not that I have been aware of, or found out searching. Make sure you use realpath() around the image name, to give the absolute path to the image.

Categories