Uploading files to a LAMP stack and keep track of it with a CMS
December 22, 2014
Uploading files to a LAMP stack and keep track of it with a CMS Part 1
This is technically a continuation of Dave’s tutorial on how to create a Blog with LAMP here, and I’ve added my own twist and turned it into a small CMS by allowing users to upload photos and keep track of their uploads. I will be referencing a lot of the files back to what was created on Dave’s tutorial
If we are continuing from the tutorial, we should have a completed admin console that looks like this:
The upload script
Lets create the upload script, which will handle the interaction of the post request that has the files attached to it. Along with storing the file we will also add the metadata from the request’s body and store it in the MySQL database
Lets first define a few variables such as the extensions that we will allow for upload, we will define it in an array called $allowedExts. Next we will store the temp file name into an array that is done by parsing the period before the extesnion using the explode command, so we will define it in $temp. Our extension will naturally use the the end of the array assuming the file was named correctly to store the extension of the file, we will define this use $extension. From the request we will assume the form will also contain an title and description field which we will parse from the request body. I’ve defined the two with $imgTitle and $imgeDesc.
Your variables should look like this
Now that we’ve checked some basic request body information we can now move on to verifying that the file isn’t too large and that the file type from the request header matches one of the cases and the extension is valid and within our $allowedExts array. We will require a title for every image file that is uploaded so we will print an error if the title is missing.
We added to the above code we will now check for any errors that could have occured during the upload, of which we will send back and not continue the upload.
After the file has gone through our extensive verification we can finally move on to the most crucial step of the file upload, which is to move the file from the temporary folder to the permenant folder in /img/upload. We accomplish this using the move_upload_file command. We will also be using parameterized sql statements to store and track the uploaded files. The MySQL database will hold the title, description, and the file path.
The end script should look something like this with the authentication and included header files for styling