Create Executable Images

Introduction

  1. In this tutorial you will learn how to create executable image file
  2. Using the image you can perform any programmatic logic behind displaying an image
  3. The image created using PHP may not look unusual except the file extension will be .php
  4. We will overcome this drawback with Apache’s htaccess file with rewrite rules to masquerade our PHP file as image file

Prerequisite

  1. Though you can use any image library like ImageMagick for this masquerading technique but we are planned to use GD image library
  2. GD is an open source graphics library
  3. GD library ‘s PHP official documentation link: GD Documentation

Verification

  1. To check whether your server have installed PHP extension GD, execute the following command in your terminal/CLI php -i | grep 'GD'
  2. 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 the GD
  3. If search not found the GD library then your server don’t have GD library

GD Installation

  1. If GD library is not installed follow this section else skip it
  2. Installing for Debian based distro but you can follow the same command for red hat based distro by instead of using apt package manager use yum
  3. Package installation command: sudo apt install php-gd
  4. Once installed, GD library is activated and available in PHP CLI
  5. To make the GD module available as extension in Apache server execute the following command to restart with newly installed extensions are loaded
  6. Command: sudo systemctl restart apache2
  7. Verify once again as described in the Verification section to confirm GD installed

Basic image on the fly

  1. 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
  2. In line 4 we call color allocating function imagecolorallocate($handle, 0, 255, 0)
  3. Where function imagecolorallocate accepts four parameters as follows handle, red, green, blue color’s value between 0 and 255
  4. In line 6 we call the function imagefilledrectangle(...) with first parameter as $handle an 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
  5. In line 9 we call the function header which is used to send a raw HTTP header to the called client side
  6. In header function call we pass the image type JPEG as content
  7. So the script will me considered as image and rendered as image
  8. In line 10 we call the function imagejpeg which have one mandatory parameter resource handle and two optional parameters $filename the path where dynamic image to be saved and $quality quality of the generated image by default it is 75 (minimum 0 and maximum 100)
  9. Finally on line 12 we call the another GD function imagedestroy destroy an image resource and free up the space
  10. 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
  11. Next we use this in HTML file

  1. Use like the above image tag by replacing URL of src attribute to your server URL path
  2. Once embedded the image i.e. your PHP script in HTML file refresh the page in browser
  3. You will see the green colored big rectangle image

Dynamic captcha image

  1. Let’s leverage what you learned in the previous section to create something more useful
  2. A random string generator which can be used as captcha validator
  3. The final script will display captcha string and some user’s client side details
  4. 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

  1. In the above script most of logics between line 1 and 17 are explained in basic usage section
  2. In line 11 and 12 we call the GD function imagestring(...)
  3. The function requires six parameters they are $image the image resource’s handle, $font variable predefined font size between 1 and 5 or load registered fonts, $x x coordinate of upper left corner, $y y coordinate of upper left corner, $string the string to be written or rendered (here we pass our random string by calling the helper function rand_string or show render last accessed time in ATOM standard using date predefined constant), $color Color identifier generated by imagecolorallocate

Random string generator helper function

  1. Let’s see helper function rand_string($length = 6)
  2. In line 23 we define the function rand_string with optional parameter $length with default value 6
  3. In line 26 we call the function range three times with arguments for start and end parameters are 0-9, a-z, A-Z
  4. range function 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
  5. Then three arrays are merged in to a single array using function array_merge and assigns it to the local variable $master_list
  6. In line 27 we call the array function shuffle by passing our $master_list array as parameter which will shuffle the array (Warning: this function uses new key so be cautious while using with associative array)
  7. In line 29 we call the function array_slice with 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
  8. So if we pass value 10 for the parameter $length then the default value of 6 is override into 10 and return 10 element from the shuffled array
  9. Which is assigned to the variable $sub_element
  10. In line 30 we make use of the variable $sub_element which is used as the argument for the function implode
  11. The implode function will convert our array into a string and assign it to the variable $to_string
  12. The implode function 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 this implode($array, $glue) though without glue is acceptable
  13. Finally in line 32 we return the random string generated by our helper function rand_string

GD function use cases

  1. The use cases for GD is so many though this tutorial is for masquerading php script to image will share some use cases
  2. You can use it add dynamic watermark over the image
  3. You can use it to adjust the alpha channel or transparency of the image
  4. You can create random collage of the image
  5. To reduce the image quality (we used it to deliver low quality of the image to basic subscriber and high quality for premium user)
  6. 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)
  7. As the image is dynamic you can control the access, expiry of the image
  8. 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
  9. Write copyright with dynamic year as watermark
  10. To track user activity many ad based company uses dynamic images for analytics

Masquerading file extension from php to jpeg

  1. First create a file .htaccess in your tutorial project root directory
  2. Then add the given below snippet in your .htaccess file

  3. When you opened the PHP script URL as https://myhost.com/image.jpg if it throws not found error then your .htaccess is not called
  4. So you have to troubleshoot the configuration file which is in the path /etc/apache2/apache2.conf
  5. Open the file as a root user and find the following snippet in the configuration file
  6. Change the line AllowOverride None to AllowOverride All and save the file
  7. Once you reconfigured apache2.conf file restart the apache server by running the following command sudo systemctl restart apache2 to reflect the .htaccess
  8. Reload dynamic masqueraded image page (https://myhost.com/image.jpg)
  9. If still problem persists enable the rewrite module by executing the following command sudo a2enmod rewrite and restart the apache server once again

.htaccess brief explanation

  1. First of all our .htaccess file 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
  2. RewriteEngine On enables runtime rewrite engine
  3. RewriteBase / will be used as a relative path for our rewrite rule need more details here’s the link RewriteBase purpose
  4. RewriteRule ^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

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

Comments

6 responses to “Create Executable Images”

  1. Useful.how to create games?

    1. Rock, Could you please explain more about your question so that I can give my suggestion.

  2. Nice

    1. Anto, Thanks for your appreciation.

  3. Great blog! Do you have any recommendations for aspiring writers?

    I’m hoping to start my own blog soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like
    Wordpress or go for a paid option? There are so many choices out
    there that I’m totally confused .. Any ideas? Many thanks!

    1. Alex, welcome to the writers club.

      I recommend you to read many books and daily get to know a new word. There is no shortcut for anything you have to turmoil to catch your goals.

      Start your blog today itself don’t delay the process. I suggest a WordPress (WP) blog. If you’re good at PHP and know what is template hierarchy, hooks, filters, etc., you can adjust your desired website needs by yourself even if you’re not good in coding skills no problem you can control most of the thing in WP Admin panel and using some third-party plugins.

      Feel free to ask if you have more queries.