- Saved searches
- Use saved searches to filter your results more quickly
- jlammx/php_upload_base64-encoded_binary_files_to_a_directory
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- How to upload base64 file in PHP.
- How to upload base64 to file in PHP
- Example Core PHP:
- Upload base64 to file in Codeigniter
- Example Codeigniter :
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Upload Base64-encoded binary files to a directory using PHP
jlammx/php_upload_base64-encoded_binary_files_to_a_directory
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP | Upload Base64-encoded binary files to a directory
This repository is an example of upload Base64-encoded binary files to a directory.
The encoding is designed to make binary data survive transport through transport layers when the channel does not allow binary data or that are not 8-bit clean, such as mail bodies or NNTP.
- file_get_contents() — Reads entire file into a string
The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file. - base64_encode() — Encodes data with MIME base64
MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64.
The base64_encoded data takes 33% more space then original data.
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. - base64_decode() — Decodes data encoded with MIME base64
Decodes a base64 encoded string. - file_put_contents() — Write data to a file
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
What is encoding and decoding in a computer?
Encoding is the process of putting a sequence of characters (letters, numbers, punctuation, and certain symbols) into a specialized format for efficient transmission or storage.
Decoding is the opposite process — the conversion of an encoded format back into the original sequence of characters.
A encoded file is a file that has been transformed into a different format from the original to facilitate transfer and storage. Some examples of file encoding include Base64, UTF-8, and ASCII. File encoding can make the file easier to handle for users, as encoded files may be easier to read and download in some web browsers. However, file encoding can also increase file size and decrease data transfer efficiency.
Overall, the best way to send a file over the web will depend on the file type, the purpose of the transfer, and user preferences. If data transfer efficiency is a priority, you may want to send a binary file. If readability and ease of use are more important, you may want to send an encoded file. In any case, it is important to ensure file transfer is secure and complies with applicable privacy and security policies and requirements. — Chat GPT
The form should contain the attributes as method=’post’ and enctype=’multipart/form-data’ to support file upload. It helps to bundle the form data and the binary data to post it to the server-side PHP file.
form action="" enctype pl-s">multipart/form-data" method pl-s">POST" name pl-s">frm"> input type pl-s">file" name pl-s">myfile" /> input type pl-s">submit" name pl-s">submit" value pl-s">Upload"/> form>
- The file_get_contents() function get the image and convert into string.
- The base64_encode() function encode the image string data into base64.
- The base64_decode() function decode the image string data in base64.
- The file_put_contents function moves the file to the directory as an image.
$targetDir pl-s">uploads/"; // Check if it is an array and if it has data if(is_array($_FILES) && !empty($_FILES["myfile"]["name"])) < // Get the file path $path = $_FILES['myfile']['tmp_name']; // Get the file name $name = $_FILES['myfile']['name']; // Get the file type $type = pathinfo($path, PATHINFO_EXTENSION); // Get the image and convert into string, this string can be use in file_put_contents() like a parameter and works $imgData = file_get_contents($path); // Encode the image string data into base64 $imgEncoded = base64_encode($imgData); // Display the output // echo $data; // Format the image SRC in base64: data:;base64,; $srcBase64 = 'data:image/' . $type . ';base64,' . $imgEncoded; // Validates that the uploaded file is not empty and is posted via the HTTP_POST method if(is_uploaded_file($path)) < // Decode the image string data in base64 $decodedImage = base64_decode($imgEncoded); // Pass the parameters, the destination for moved file and the decoded file $return = file_put_contents($targetDir.$name, $decodedImage); if($return !== false)< echo "File uploaded successfully!"; // Show a sample image in base64 echo '$srcBase64.'">'; > else < echo "Sorry, there was an error uploading your file."; > > > else < echo "Please select a file to upload."; > ?>
How to upload base64 file in PHP.
Uploading files or images from mobile app is a most common case in many projects, there are two ways to finish this task, one of them is most popular, much safer, and considering as a best practice, which is encoding the uploaded file as a base64 string in your mobile application and send it as a normal post to the PHP API.
Java, objective c, c# and also Javascript has an option to encode files to base64 strings before sending it to the server
In this tutorial we will create a simple API to upload base64 encoded files or images to PHP server and also you will learn:
So enough talking and let’s do it.
First Step: Create Table Schema
CREATE TABLE `uploaded_files` ( `id` int(11) NOT NULL, `file_name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `uploaded_files` ADD PRIMARY KEY (`id`); ALTER TABLE `uploaded_files` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Second Step: Create uploader.php file
put this file into your root like WWW or HTDOCS , then copy the full code below and paste into the file, which contains 3 functions :
Upload_file() , this function to take encoded file as a parameter, decoded it, save as a file, and return JSON message
Mime2ext(), this function to take mime type as a parameter and return the equivalent extension
database_saving() , this function to save the file name and extension into database
catch (Exception $e) < header('Content-Type: application/json'); echo json_encode($e->getMessage()); > > /* to take mime type as a parameter and return the equivalent extension */ function mime2ext($mime)< $all_mimes = '<"png":["image\/png","image\/x-png"],"bmp":["image\/bmp","image\/x-bmp", "image\/x-bitmap","image\/x-xbitmap","image\/x-win-bitmap","image\/x-windows-bmp", "image\/ms-bmp","image\/x-ms-bmp","application\/bmp","application\/x-bmp", "application\/x-win-bitmap"],"gif":["image\/gif"],"jpeg":["image\/jpeg", "image\/pjpeg"],"xspf":["application\/xspf+xml"],"vlc":["application\/videolan"], "wmv":["video\/x-ms-wmv","video\/x-ms-asf"],"au":["audio\/x-au"], "ac3":["audio\/ac3"],"flac":["audio\/x-flac"],"ogg":["audio\/ogg", "video\/ogg","application\/ogg"],"kmz":["application\/vnd.google-earth.kmz"], "kml":["application\/vnd.google-earth.kml+xml"],"rtx":["text\/richtext"], "rtf":["text\/rtf"],"jar":["application\/java-archive","application\/x-java-application", "application\/x-jar"],"zip":["application\/x-zip","application\/zip", "application\/x-zip-compressed","application\/s-compressed","multipart\/x-zip"], "7zip":["application\/x-compressed"],"xml":["application\/xml","text\/xml"], "svg":["image\/svg+xml"],"3g2":["video\/3gpp2"],"3gp":["video\/3gp","video\/3gpp"], "mp4":["video\/mp4"],"m4a":["audio\/x-m4a"],"f4v":["video\/x-f4v"],"flv":["video\/x-flv"], "webm":["video\/webm"],"aac":["audio\/x-acc"],"m4u":["application\/vnd.mpegurl"], "pdf":["application\/pdf","application\/octet-stream"], "pptx":["application\/vnd.openxmlformats-officedocument.presentationml.presentation"], "ppt":["application\/powerpoint","application\/vnd.ms-powerpoint","application\/vnd.ms-office", "application\/msword"],"docx":["application\/vnd.openxmlformats-officedocument.wordprocessingml.document"], "xlsx":["application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application\/vnd.ms-excel"], "xl":["application\/excel"],"xls":["application\/msexcel","application\/x-msexcel","application\/x-ms-excel", "application\/x-excel","application\/x-dos_ms_excel","application\/xls","application\/x-xls"], "xsl":["text\/xsl"],"mpeg":["video\/mpeg"],"mov":["video\/quicktime"],"avi":["video\/x-msvideo", "video\/msvideo","video\/avi","application\/x-troff-msvideo"],"movie":["video\/x-sgi-movie"], "log":["text\/x-log"],"txt":["text\/plain"],"css":["text\/css"],"html":["text\/html"], "wav":["audio\/x-wav","audio\/wave","audio\/wav"],"xhtml":["application\/xhtml+xml"], "tar":["application\/x-tar"],"tgz":["application\/x-gzip-compressed"],"psd":["application\/x-photoshop", "image\/vnd.adobe.photoshop"],"exe":["application\/x-msdownload"],"js":["application\/x-javascript"], "mp3":["audio\/mpeg","audio\/mpg","audio\/mpeg3","audio\/mp3"],"rar":["application\/x-rar","application\/rar", "application\/x-rar-compressed"],"gzip":["application\/x-gzip"],"hqx":["application\/mac-binhex40", "application\/mac-binhex","application\/x-binhex40","application\/x-mac-binhex40"], "cpt":["application\/mac-compactpro"],"bin":["application\/macbinary","application\/mac-binary", "application\/x-binary","application\/x-macbinary"],"oda":["application\/oda"], "ai":["application\/postscript"],"smil":["application\/smil"],"mif":["application\/vnd.mif"], "wbxml":["application\/wbxml"],"wmlc":["application\/wmlc"],"dcr":["application\/x-director"], "dvi":["application\/x-dvi"],"gtar":["application\/x-gtar"],"php":["application\/x-httpd-php", "application\/php","application\/x-php","text\/php","text\/x-php","application\/x-httpd-php-source"], "swf":["application\/x-shockwave-flash"],"sit":["application\/x-stuffit"],"z":["application\/x-compress"], "mid":["audio\/midi"],"aif":["audio\/x-aiff","audio\/aiff"],"ram":["audio\/x-pn-realaudio"], "rpm":["audio\/x-pn-realaudio-plugin"],"ra":["audio\/x-realaudio"],"rv":["video\/vnd.rn-realvideo"], "jp2":["image\/jp2","video\/mj2","image\/jpx","image\/jpm"],"tiff":["image\/tiff"], "eml":["message\/rfc822"],"pem":["application\/x-x509-user-cert","application\/x-pem-file"], "p10":["application\/x-pkcs10","application\/pkcs10"],"p12":["application\/x-pkcs12"], "p7a":["application\/x-pkcs7-signature"],"p7c":["application\/pkcs7-mime","application\/x-pkcs7-mime"],"p7r":["application\/x-pkcs7-certreqresp"],"p7s":["application\/pkcs7-signature"],"crt":["application\/x-x509-ca-cert","application\/pkix-cert"],"crl":["application\/pkix-crl","application\/pkcs-crl"],"pgp":["application\/pgp"],"gpg":["application\/gpg-keys"],"rsa":["application\/x-pkcs7"],"ics":["text\/calendar"],"zsh":["text\/x-scriptzsh"],"cdr":["application\/cdr","application\/coreldraw","application\/x-cdr","application\/x-coreldraw","image\/cdr","image\/x-cdr","zz-application\/zz-winassoc-cdr"],"wma":["audio\/x-ms-wma"],"vcf":["text\/x-vcard"],"srt":["text\/srt"],"vtt":["text\/vtt"],"ico":["image\/x-icon","image\/x-ico","image\/vnd.microsoft.icon"],"csv":["text\/x-comma-separated-values","text\/comma-separated-values","application\/vnd.msexcel"],"json":["application\/json","text\/json"]>'; $all_mimes = json_decode($all_mimes,true); foreach ($all_mimes as $key => $value) < if(array_search($mime,$value) !== false) return $key; >return false; > /* to save the file name and extension into database */ function database_saving($file)< $servername = "localhost"; $username = "root"; $password = ""; $dbname = "demo"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) < die("Connection failed: " . $conn->connect_error); > $sql = "INSERT INTO uploaded_files (file_name)VALUES ('$file')"; $conn->query($sql); $conn->close(); > // invoke upload_file function and pass your input as a parameter $encoded_string = !empty($_POST['base64_file']) ? $_POST['base64_file'] : 'V2ViZWFzeXN0ZXAgOik='; upload_file($encoded_string);
Third Step: Call the API throughout Postman
Send a base64 string throughout postman, when API loaded it will invoke Upload_file() function, which decode the file, extract the mime type dynamically using finfo_buffer extension, also extract extension by mime using mime2ext() function, add a unique name for the file, finally save it into PHP server and MySQL server
Important Note: To use finfo_buffer() function you should insure that you already enable fileinfo module in your server
Final words
I hope this tutorial helps you to understand how it easily uploads files into PHP server and I hope to add more tutorials as soon as possible about React native and Redux because nowadays I am so excited about this subject.
Your tutorial was very helpful. I found an issue in the code $decoded_file = base64_decode($encoded_string); It should be like: $filedata = explode(‘,’, $encoded_string); $decoded_file = base64_decode($filedata[1]); Thanks!
How to upload base64 to file in PHP
In this tutorial, we will let you know how to handle the image encoded with Base64 and write the image to folder.
While we have working with API for mobile or web application , You will notice that they will send the format of images in Base64 encoded. So in that case, you will need to move the Base64 encoded image to server as a image file.and have to save it in the folder
Example Core PHP:
Upload base64 to file in Codeigniter
Are you looking for a way to save a PNG image server-side, from a base64 data string, or unable to upload to a base64 encoded image using Codeigniter? We can help you with that.
We are creating some function for using base64 string check is valid or not and size and file type
create file application/libraries/Base64fileUploads.php
$/', $s)) return false; // Decode the string in strict mode and check the results $decoded = base64_decode($s, true); if(false === $decoded) return false; // Encode the string again if(base64_encode($decoded) != $s) return false; return true; > public function du_uploads($path,$base64string)< if( $this->is_base64($base64string) == true )< $base64string = "data:image/jpeg;base64,".$base64string; $this->check_size($base64string); $this->check_dir($path); $this->check_file_type($base64string); /*=================uploads=================*/ list($type, $base64string) = explode(';', $base64string); list(,$extension) = explode('/',$type); list(,$base64string) = explode(',', $base64string); $fileName = uniqid().date('Y_m_d').'.'.$extension; $base64string = base64_decode($base64string); file_put_contents($path.$fileName, $base64string); return array('status' =>true,'message' =>'successfully upload !','file_name'=>$fileName,'with_path'=>$path.$fileName); >else< print_r(json_encode(array('status' =>false,'message' => 'This Base64 String not allowed !')));exit; > > public function check_size($base64string)< $file_size = 8000000; $size = @getimagesize($base64string); if($size['bits'] >= $file_size)< print_r(json_encode(array('status' =>false,'message' => 'file size not allowed !')));exit; > return true; > public function check_dir($path) < if (!file_exists($path)) < mkdir($path, 0777, true); return true; >return true; > public function check_file_type($base64string)< $mime_type = @mime_content_type($base64string); $allowed_file_types = ['image/png', 'image/jpeg', 'application/pdf']; if (! in_array($mime_type, $allowed_file_types)) < // File type is NOT allowed // print_r(json_encode(array('status' =>false,'message' => 'File type is NOT allowed !')));exit; > return true; > >
Example Codeigniter :
Call this class Codeigniter in controller
$base64file = new Base64fileUploads(); $return = $base64file->du_uploads($this->data['document'],$document_front_site);