2009/08/21
osCommerce Image Uploads
Recently, someone posted in the osCommerce forums looking for a way to upload product images into folders. I found a post that I made six years ago: Setting upload image destination in categories.php, Admin change. Surprisingly, the post was remarkably accurate with the more modern osCommerce RC2a, even the line numbers were only a couple places off. The replacement code does not seem to need updating.
The way that this code works is that it adds a new text input next to the existing file input (for both product and category images). It then uses the functionality in the upload class that osCommerce provides to rename the image to whatever name is put in the text input. If the name includes a / and the directory structure exists, it will save the image into that directory.
When you upload a file with PHP, PHP/Apache stores the file in a temporary directory. So you then have to tell it to move the file from the temporary directory to the real directory. The parse method in the osCommerce upload class finds the temporary location. The save method then moves the file to its intended destination.
The added code has three main tasks: it adds the text input to the appropriate forms (three forms; one for products and two for categories); it changes the image saving to use the new image destination; and it modifies the database updates to use the image destination rather than the name of the uploaded file (if the image destination is present or if no file is uploaded).
The net result of this is that with the code, you can not upload a file and blank out the image destination (which defaults to the location of the previous image) to remove an image from a product (or category). In the regular code, there is no way to do this. Upload an image with a blank destination, which causes the image filename to be used and the image to be placed in the base images directory. Or you can upload an image with the destination set, which renames the image to the destination, which may be in a sub-folder of the images directory.
The one drawback to how this works is that it is currently necessary to create the directory separately (possibly via FTP). A reasonable enhancement might be to have it do a mkdir to create the directory on the fly. Not sure how that would work with safe mode though.