Php base64 encode files

Base64 encode uploaded file then save in database

I want to base 64 encode uploaded file then save this into Blob type column of a table in MySQL database. I have tried built in PHP function base64_encode with file variable but this does not seem to work. Is there a way we can do this? The reason is that I do not want to use moveuploaded file into a folder. Thank you.

«The reason is that I do not want to use moveuploaded file into a folder.» — actually it is not the reason. Reason is what caused that

1 Answer 1

As @Sjoerd and @zerkms correctly point out, you do not need to do this — a blob column is be used to store raw binary data, so you can bypass the Base64 process and insert the raw data of the file.

If you want to store images in a database (which, by the way, I personally don’t like to do) it is better to store the raw data — Base64 encoding the data makes it larger, and means that it must be decoded before the image is rendered, which adds processing overhead.

Читайте также:  Checking java version cmd

This is how you can insert the raw binary data (assuming the MySQL extension):

$data = file_get_contents($_FILES['name_of_control']['tmp_name']); $data = mysql_real_escape_string($data); $query = " INSERT INTO table (`blob_column`) VALUES ('$data') "; mysql_query($query); 

If you really do want to Base64 encode it (in which case it could just be stored in a varchar), just just add a base64_encode() call:

$data = file_get_contents($_FILES['name_of_control']['tmp_name']); $data = base64_encode($data); // There is an argument that this is unnecessary with base64 encoded data, but // better safe than sorry :) $data = mysql_real_escape_string($data); $query = " INSERT INTO table (`varchar_column`) VALUES ('$data') "; mysql_query($query); 

Источник

Преобразование изображения в Base64 на PHP

Преобразование файла в Base64-изображение для вставки тег или CSS background производится по следующему формату:

Структура изображения Base64

Изображение для преобразования в base64

Для теста возьмем маленькое изображение: Для него в PHP нужно получить MIME, прочитать файл и закодировать полученные данные функцией base64_encode() . Т.к. функция getimagesize() не актуальна для SVG файлов, для них придется сделать исключение.

Результат:

Источник

php image file upload and convert to base64 without saving image

I know how to upload image file and save to other location by using the following code. However, I need to do in such a way that user upload image and automatically convert to base64 without saving that image in my location. How should I do?

"; $type = pathinfo($file_tmp, PATHINFO_EXTENSION); $data = file_get_contents($file_ext); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); echo "Base64 is ".$base64; if(in_array($file_ext,$allowed_ext) === false) < $errors[]='Extension not allowed'; >if($file_size > 2097152) < $errors[]= 'File size must be under 2mb'; >if(empty($errors)) < if( move_uploaded_file($file_tmp, 'images/'.$file_name)); < echo 'File uploaded'; >> else < foreach($errors as $error) < echo $error , '
'; > > // print_r($errors); > ?>

Use file_get_contents() to get the contents of the temporary uploaded file, base64_encode() to encode it, file_put_contents() to save the file. Although storing a base64 encoded representation of an image file sounds like a bad idea — with big files, you may run into RAM problems, and the resulting file will be 33% larger than the original. Why do that?

Yes. I need to test with that one. If I writing like this, I can’t get base64 string. Can you please guide me? $type = pathinfo($file_tmp, PATHINFO_EXTENSION); $data = file_get_contents($file_ext); $base64 = ‘data:image/’ . $type . ‘;base64,’ . base64_encode($data); echo «Base64 is «.$base64;

Источник

How to encode a PHP file with base64

🙂 I have one ridiculously silly question and most of you would like to reffer me to Google right away, but that didn’t helped me out within the first hour. I suppose I didn’t knew how to look for. I’m having a PHP file and I’d like to have it in base64 yet I can’t get it to work anyhow. 1) I encoded my PHP script to base64(and included the PHP tags). It’ll look as following : JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ== This kind of base64 won’t execute so I added the PHP tags to it although the encoded file already had it. Still didn’t worked out. Removed the tags from the base64 and tried again, but still didn’t worked. Then I tried adding the PHP tags and inside of them added : eval(gzinflate(base64_decode(‘base64 here’))); Still didn’t worked out anyhow. Is anyone here kind enough to tell the kiddo how to run a base64 encoded PHP file properly? Would be really appreaciated. 🙂

2 Answers 2

$source = "JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ= JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ= http://eaccelerator.net/" rel="noreferrer">this one or this one. They will crypt your codes and make them even faster!

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Sep 9, 2013 at 17:36
Add a comment |
2

If you are going to use base_64 to encode your php file then the encoded text need to seat in between the php tags including the base_64 tag.

Example: If your code is: JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ

Then your code should look like:

".base64_decode("JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ")); ?> 

Basically your basic code will look like this:

".base64_decode("Code Goes here")); ?> 

There are more simple tools that can give you this option Check this out: PHP Encoder & Decoder with Domain Lock

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.26.43546

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to Use Base64 Encoding in PHP

Sajal Soni

Sajal Soni Last updated Apr 19, 2021

In this quick article, we’ll discuss the basics of base64 encoding in the context of PHP. Basically, we’ll see how you could use PHP functions to transform data into the base64-encoded format.

What Is Base64 Encoding?

Base64 is an encoding of binary data in ASCII. Each character in the string represents six bits of information. Effectively it represents the binary data in base 64 representation. Check out this primer on number systems and bases if you need a refresher.

The primary use of Base64 encoding is to encode binary data to ASCII text, when you want to transfer such data over protocols that are specifically designed to handle textual data. This makes sure that the data remains intact while it’s transported. Specifically, Base64 is used for things like sending emails and uploading binary data in HTML forms.

Another common use of Base64 encoding is hashing. Of course, you’re not supposed to use Base64 encoding itself to generate hashes, since it can be easily decoded. Firstly, you generate a hash with the help of a hashing algorithm like SHA, and then you convert the resulting hash into the Base64-encoded format to display it. It’s really easy to compare two Base64-encoded checksums for integrity.

In the next section, we’ll discuss the built-in Base64 functions in PHP.

Base64 Functions in PHP

There are two main functions in PHP that deal with Base64 encoding. The base64_encode function allows you to encode data in the MIME Base64 format. On the other hand, the base64_decode function is used to decode the MIME Base64-encoded data.

Let’s go through each of these functions in detail.

base64_encode

Let’s go through the syntax of the base64_encode function.

base64_encode ( string $string ) : string 

The only argument you need to pass to the base64_encode function is the source string which you want to encode to MIME Base64.

This returns a Base64-encoded string. It’s important to note that the Base64-encoded data takes around 33% more space in memory than the original data.

base64_decode

Let’s go through the syntax of the base64_decode function.

base64_decode ( string $string , bool $strict = false ) : string|false 

The first argument is the Base64-encoded data which you want to decode.

The second argument is optional, but if you pass TRUE , it will perform strict checking. This means that if the Base64-encoded data contains characters from outside the Base64 alphabet, the decode function will return FALSE . This is useful for checking the integrity of the Base64-encoded string. On the other hand, if you want to discard invalid characters silently, just pass FALSE , which is the default value.

On successful decoding, the function returns the decoded string, otherwise it returns FALSE . It’s important to note that the base64_decode function may return binary data if the string in question was in the binary format before encoding.

In the next section, we’ll discuss how you can use built-in Base64 functions in PHP.

How to Encode and Decode Data With MIME Base64

In this section, we’ll go through a couple of examples to see Base64 functions in action.

Encode URL Parameters

More often than not, you’ll end up using the base64_encode function to encode parameters that contain URLs.

Let’s quickly see how it works with the following example.

$redirectUrl = 'https://www.example.com/some/other/url'; 
header('Location: https://www.example.com/redirect/' . base64_encode($redirectUrl)); 
//https://www.example.com/redirect/aHR0cDovL3d3dy5leGFtcGxlLmNvbS9zb21lL290aGVyL3VybA== 

As you can see, if we don’t use the base64_encode function, the resulting URL would look like https://www.example.com/redirect/http://www.example.com/some/other/url , which is invalid.

Base64-Encoded Checksum

As we discussed earlier, the base64_encode function comes in handy when converting binary data into an ASCII string.

Let’s have a look at the following example.

$base64_encoded_hash = base64_encode(hash_hmac('sha1', 'Source string to be hashed.', 'YOUR_TOP_SECRET_KEY', true)); 

In the above example, the hash_hmac function would return hashed binary data. So if you don't use the base64_encode function, it would be difficult to display the resulting binary data.

Email Attachments

In PHP, when you send an email with file attachments, you can encode the file contents into the Base64-encoded format. In fact, if you’re sending binary attachments, then it’s essential that you encode the attachment data instead of sending it in the raw format.

Let’s have a look at the following example.

$subject = 'Example of base64 encoded attachments'; 
$message = 'This email contains an image attachment.'; 
$headers .= "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-Type: multipart/mixed; boundary color: #90a959">. $boundary . "\r\n"; 
$headers .= "Multipart MIME example." . "\r\n"; 
$message.= "Content-Type: text/plain; charset=\"iso-8859-1\"" . "\r\n"; 
$message.= "Content-Transfer-Encoding: 8bit" . "\r\n"; 
$filecontents = file_get_contents($filename); 
$filecontents = chunk_split(base64_encode($filecontents)); 
$message.= "Content-Type: image/jpg; name=\"" . $filename . "\"" . "\r\n"; 
$message.= "Content-Transfer-Encoding: base64" . "\r\n"; 
$message.= "Content-Disposition: attachment" . "\r\n"; 
mail($mailto, $subject, $body, $headers); 

As you can see, we’ve used the base64_encode function to encode binary image data before it’s sent as an attachment.

In this way, you can use Base64 functions in PHP for various purposes.

Conclusion

In this quick article, we discussed how you can use Base64 functions in your day-to-day PHP development.

Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.

Sajal Soni

I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

Источник

Оцените статью