Introduction
- In this tutorial you will learn how to create executable image file
- Using the image you can perform any programmatic logic behind displaying an image
- The image created using PHP may not look unusual except the file extension will be
.php - We will overcome this drawback with Apache’s htaccess file with rewrite rules to masquerade our PHP file as image file
Prerequisite
- Though you can use any image library like
ImageMagickfor this masquerading technique but we are planned to useGDimage library GDis an open source graphics libraryGDlibrary ‘s PHP official documentation link: GD Documentation
Verification
- To check whether your server have installed PHP extension
GD, execute the following command in your terminal/CLIphp -i | grep 'GD' - If you are uncomfortable with CLI you can create a PHP file in your webserver with calling the function
phpinfo();and load the page in browser and search for theGD - If search not found the
GDlibrary then your server don’t have GD library
GD Installation
- If
GDlibrary is not installed follow this section else skip it - Installing for Debian based distro but you can follow the same command for red hat based distro by instead of using
aptpackage manager useyum - Package installation command:
sudo apt install php-gd - Once installed,
GDlibrary is activated and available in PHP CLI - To make the
GDmodule available as extension in Apache server execute the following command to restart with newly installed extensions are loaded - Command:
sudo systemctl restart apache2 - Verify once again as described in the
Verificationsection to confirmGDinstalled
Basic image on the fly
- In line 2 we call the GD function
imagecreatetruecolor(640, 480)which create an image 640 px wide and 480 px height and assign this resource to a handle variable$handle - In line 4 we call color allocating function
imagecolorallocate($handle, 0, 255, 0) - Where function
imagecolorallocateaccepts four parameters as followshandle, red, green, bluecolor’s value between 0 and 255 - In line 6 we call the function
imagefilledrectangle(...)with first parameter as$handlean image resource, second parameter as x’s start coordinate integer value, third parameter as y’s start coordinate, fourth and fifth parameters are x’s and y’s end coordinate to form the rectangle, Last sixth parameter as color identifier value which is$green - In line 9 we call the function
headerwhich is used to send a raw HTTP header to the called client side - In
headerfunction call we pass the image typeJPEGas content - So the script will me considered as image and rendered as image
- In line 10 we call the function
imagejpegwhich have one mandatory parameter resource handle and two optional parameters$filenamethe path where dynamic image to be saved and$qualityquality of the generated image by default it is 75 (minimum 0 and maximum 100) - Finally on line 12 we call the another GD function
imagedestroydestroy an image resource and free up the space - Hurray! We created basic dynamic image which is in memory image i.e. it is in volatile layer RAM instead of persistent storage like HDD or SSD
- Next we use this in HTML file
- Use like the above image tag by replacing URL of
srcattribute to your server URL path - Once embedded the image i.e. your PHP script in HTML file refresh the page in browser
- You will see the green colored big rectangle image
Dynamic captcha image
- Let’s leverage what you learned in the previous section to create something more useful
- A random string generator which can be used as captcha validator
- The final script will display captcha string and some user’s client side details
- For this upgraded code we use most of the code in our basic image creation php file and use a helper function to generate random string
- In the above script most of logics between line 1 and 17 are explained in basic usage section
- In line 11 and 12 we call the GD function
imagestring(...) - The function requires six parameters they are
$imagethe image resource’s handle,$fontvariable predefined font size between 1 and 5 or load registered fonts,$xx coordinate of upper left corner,$yy coordinate of upper left corner,$stringthe string to be written or rendered (here we pass our random string by calling the helper functionrand_stringor show render last accessed time in ATOM standard using date predefined constant),$colorColor identifier generated byimagecolorallocate
Random string generator helper function
- Let’s see helper function
rand_string($length = 6) - In line 23 we define the function
rand_stringwith optional parameter$lengthwith default value6 - In line 26 we call the function
rangethree times with arguments for start and end parameters are 0-9, a-z, A-Z rangefunction return the array of elements from start to end here it fetches properly the sequence of integer, small and capital alphabet using ASCII code range- Then three arrays are merged in to a single array using function
array_mergeand assigns it to the local variable$master_list - In line 27 we call the array function
shuffleby passing our$master_listarray as parameter which will shuffle the array (Warning: this function uses new key so be cautious while using with associative array) - In line 29 we call the function
array_slicewith first parameter as an array which is used as a source for the sliced array, the second parameter is offset from where the offset should be started we passed 0 so it will start from first element (Array’s index starts from zero), the third parameter is for the total element in the sliced array which is dynamically controlled by the optional parameter of our function - So if we pass value
10for the parameter$lengththen the default value of6is override into10and return 10 element from the shuffled array - Which is assigned to the variable
$sub_element - In line 30 we make use of the variable
$sub_elementwhich is used as the argument for the functionimplode - The implode function will convert our array into a string and assign it to the variable
$to_string - The
implodefunction is little bizarre because it accepts first parameter as glue to join an array if only one parameter (array datatype) given to implode it will join all elements and form the string and reordering the argument is possible but it is deprecated so don’t call like thisimplode($array, $glue)though without glue is acceptable - Finally in line 32 we return the random string generated by our helper function
rand_string
GD function use cases
- The use cases for GD is so many though this tutorial is for masquerading php script to image will share some use cases
- You can use it add dynamic watermark over the image
- You can use it to adjust the alpha channel or transparency of the image
- You can create random collage of the image
- To reduce the image quality (we used it to deliver low quality of the image to basic subscriber and high quality for premium user)
- To create image in various resolution (We used to save various resolution image in S3 using AWS elastic transcoder and lambda but same can be achieved for image using GD)
- As the image is dynamic you can control the access, expiry of the image
- Can be used for ethical hacking that’s why many email client won’t allow images download automatically if user need image they can take the risk and allow image to load
- Write copyright with dynamic year as watermark
- To track user activity many ad based company uses dynamic images for analytics
Masquerading file extension from php to jpeg
- First create a file
.htaccessin your tutorial project root directory - Then add the given below snippet in your
.htaccessfile - When you opened the PHP script URL as
https://myhost.com/image.jpgif it throws not found error then your.htaccessis not called - So you have to troubleshoot the configuration file which is in the path
/etc/apache2/apache2.conf - Open the file as a root user and find the following snippet in the configuration file
- Change the line
AllowOverride NonetoAllowOverride Alland save the file - Once you reconfigured
apache2.conffile restart the apache server by running the following commandsudo systemctl restart apache2to reflect the.htaccess - Reload dynamic masqueraded image page (
https://myhost.com/image.jpg) - If still problem persists enable the rewrite module by executing the following command
sudo a2enmod rewriteand restart the apache server once again
.htaccess brief explanation
- First of all our
.htaccessfile is a basic one so don’t use this file as a production one but you use this snippet for any reference to change the file name or extension based on certain regular expression RewriteEngine Onenables runtime rewrite engineRewriteBase /will be used as a relative path for our rewrite rule need more details here’s the link RewriteBase purposeRewriteRule ^image\.jpg image.php [L,QSA]is main rule which will rewrite URL from php extension to jpg likewise you can rename to anything like gif, bmp, etc., for more details RewriteRule purpose
Sample dynamic image

Conclusion
- Finally you learned the masquerading technique using Apache httpd server
- You learned about GD library and it’s use cases
- You learned how to created dynamic image on the fly