To check whether your server have installed PHP extension GD, execute the following command in your terminal/CLI php -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 the GD
If search not found the GD library then your server don’t have GD library
GD Installation
If GD library 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 apt package manager use yum
Once installed, GD library is activated and available in PHP CLI
To make the GD module 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 Verification section to confirm GD installed
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 imagecolorallocate accepts four parameters as follows handle, red, green, blue color’s value between 0 and 255
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
In line 9 we call the function header which is used to send a raw HTTP header to the called client side
In header function call we pass the image type JPEG as content
So the script will me considered as image and rendered as image
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)
Finally on line 12 we call the another GD function imagedestroy destroy 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 src attribute 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 $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
Let’s see helper function rand_string($length = 6)
In line 23 we define the function rand_string with optional parameter $length with default value 6
In line 26 we call the function range three times with arguments for start and end parameters are 0-9, a-z, A-Z
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
Then three arrays are merged in to a single array using function array_merge and assigns it to the local variable $master_list
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)
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
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
Which is assigned to the variable $sub_element
In line 30 we make use of the variable $sub_element which is used as the argument for the function implode
The implode function will convert our array into a string and assign it to the variable $to_string
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
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 .htaccess in your tutorial project root directory
Then add the given below snippet in your .htaccess file
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
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 None to AllowOverride All and save the file
Once you reconfigured apache2.conf file restart the apache server by running the following command sudo systemctl restart apache2 to reflect the .htaccess
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
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
RewriteEngine On
enables runtime rewrite engine
RewriteBase / will be used as a relative path for our rewrite rule need more details here’s the link RewriteBase purpose
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
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
Rock, Could you please explain more about your question so that I can give my suggestion.
Anto B
Nice
admin
Anto, Thanks for your appreciation.
alex
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!
admin
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.
Comments
6 responses to “Create Executable Images”
Useful.how to create games?
Rock, Could you please explain more about your question so that I can give my suggestion.
Nice
Anto, Thanks for your appreciation.
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!
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.