Uploading Large Images

Recently I was working on scripting the back end of a commercial site in PHP5. In this case the back end user interface permits users to upload rather large image files so that the files can be processed for ‘Zoomify’( a fast way of showing a highly detailed “zoomable” image). After making sure the process was secure, I also needed to change a few settings in the php.ini file in order for the system to allow files sizes of over 2 megs (the standard PHP5 default).

It is generally not wise to make these changes in the php.ini file itself unless you have a very good reason. The preferred way would be to make the required change at execution time for the particular script you happen to be running only. This gives you better control over site operations and security. To do this you use the “ini_set()”  function.
To demonstrate how to do this, I will show you the code for the four changes I needed to make to my script to accommodate the large image uploads. First, I defined global variables that determine what the setting should be.

Defineing Globals in PHP
Defineing Globals in PHP

I do this so that later if I chose to edit the settings I can do so from my configuration file and not have to hunt through the script to make the changes. Also this allows me to duplicate the setting elsewhere if needed. The setting are as follows:

Use ini_set() to change settings in the php.ini file.

Also, If you are using a form to upload the file, do not forget to make the MAX_FILE_SIZE directive large enough to accommodate your file size. By the way, do not rely on MAX_FILE_SIZE as any sort of security measure.

Once I made these settings on my local testing server, all worked well. However, after the site was in the “live” pre production mode, the large file sizes would return an error. I knew it was not the file size issue because I had already compensated for that. What tipped me off to the problem was the fact that, every once in a while the file would upload with no error. That is when I realized it was not only a “memory limit” issue but also a timing issue. This did not show up at first because it takes much longer for a file to upload to a remote server than to the local server.

Settings we do not often deal with are easy to forget about and that was the case this time. Once I remembered to reset the “max_execution_time”  to the appropriate amount of seconds, the files uploaded just fine.

As mentioned above, the maximum execution time limit is set in the php.ini file. The line of code in the php.ini file is:

Set the max_execution time in the php.ini file.
Set the max_execution time in the php.ini file.

With this little line of code in your PHP script, you are now afforded 180 seconds of time to run your program. You can adjust the seconds as you wish by simply changing the number.

I hope this helps!

Leave a Reply

Your email address will not be published.