To Encrypt and Decrypt Image Path in PHP, we use 3 main PHP inbuilt functions,
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.
- 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()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.
- 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
<?php $image=file_get_contents("testImage.png"); $encrypted=base64_encode($image); echo '<img src="data:image/gif;base64,'.$encrypted.'" />'; ?>
- 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
<?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
- 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