To Encode and Decode Image Path in PHP, we use 3 main PHP inbuilt functions,
file_get_contents()
Function:- The
file_get_contents()
function is PHP inbuilt function that can help to read files into a string. This function uses the memory mapping technique to doing this which is also supported by the server.
- The
file_put_contents()
Function:- This function can create a new file if not available with the same name if the file is available then it overwrites that. The file can be an image or any type of file.
base64_encode()
Function:- The
base64_encode()
is also a PHP built-in function, which used to encode the data with MIME base64. MIME (Multipurpose Internet Mail Extensions). It encodes the string in base64 which takes 33% more space than the original data.
- The
base64_decode()
Function:- This function is vise versa of the base64_encode() function. It decodes the data which encode with MIME base64 type.
Here we use these PHP built-in function to encrypt and decrypt the image path in PHP. You can check the below example and source code.
Encrypt Image Path in PHP
1 2 3 4 5 6 7 |
<?php $image=file_get_contents("testImage.png"); $encrypted=base64_encode($image); echo '<img src="data:image/gif;base64,'.$encrypted.'" />'; ?> |
Code Explanations:
- Here we use a normal PNG image, to read we use file_get_contents() function.
- Than we encrypt the image path using base64_encode() function.
- On the last line we show the image which generated from encryption URL.
Show Decrypt Image and Path in PHP
1 2 3 4 5 6 7 8 9 10 |
<?php $encrypted = ''; //encrypted image from above code or any base64 encoded text $decrypted=base64_decode($encrypted); //file_put_content put decoded image with that name you can change it according to you. file_put_contents("testImage.png",$decrypted); echo '<img src="testImage.png" />'; ?> |
Here is the output image of both, Encrypt Image Path in PHP and as well as Show Decrypt Image and Path in PHP.
Copy and paste above code and check it out, if you facing any issue with these than please feel free to comment.
Want to check more about file_put_content and other function, https://www.php.net/manual/en/function.file-put-contents.php
Also Check:
- Export MySQL Data to Excel in PHP Using Ajax
- How to Get HTML Tag Value in PHP
- How to Keep Value After Page Reload in PHP
- Count Number of Visits Using PHP Cookies
Happy Coding..!
Base64 IS NOT ENCRYPTION! Please, change your article to replace encrypt/decrypt with encode/decode.
Thanks for the clarification.
But if you want to use other methods like
openssl_encrypt
or PHP Blob at the end you have to usebase64_encode()
for decryption.It’s not clear to me what you mean by “use
base64_encode()
for decryption”. The main purpose of Base64 is encoding binary and other non-ASCII data as ASCII, and yes, that’s very often used in conjunction withopenssl_encrypt
and such.