I'm going to attempt to answer your questions:
Question 1
That part is actually simple. To create a file upload form, your HTML needs to look like that:
<form enctype='multipart/form-data' action='CodeTool.php' method='POST'>
File: <input name='picture' type='file'/>
<input type='submit' value='Upload'/>
</form>
Your form needs to have enctype='multipart/form-data'
and the method
needs to be POST
. Then, to read the upload file, you can simply use the following. I've also added some basic validation to make sure that the file is an image.
if(isset($_FILES['picture'])) {
echo "File has been uploaded under temp file " . $_FILES['picture']['tmp_name'];
// Let's check if the file is an image:
$fileData = file_get_contents($_FILES['picture']['tmp_name']);
// Using imagecreatefromstring, that way you don't need to
// guess the image format.
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
echo " and is a valid image";
} else {
echo " and is not a valid image";
}
}
Question 2
To create a thumbnail image, you can use GD (or ImageMagick, but it is not included in the default configuration) as such... Let's continue from the imagecreatefromstring
if
statement:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
// Let's create a 100x100 thumbnail
$width = imagesx($img);
$height = imagesy($img);
$boxSize = min($width,$height);
$boxX = ($width / 2) - ($boxSize / 2);
$boxY = ($height / 2) - ($boxSize / 2);
$thumb = imagecreatetruecolor(100, 100);
imagecopyresampled($thumb, $img, 0, 0, $boxX, $boxY, 100, 100, $boxSize, $boxSize);
//$thumb is now a 100x100 thumbnail
}
Question 3
Here you have 2 options. You can either store your images in the file system or in the database. To store your image in the file system, you can do the following:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
move_uploaded_file($_FILES['picture']['tmp_file'], 'somefile.jpg');
// the code from the previous example
imagejpeg($thumb, 'somefile_thumb.jpg');
}
I personally prefer using the database to store the images as it is easier to keep referential integrity and makes backup simpler (backup the database and you are done). It's a bit slower, but the difference is really not that great:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
// the code from the previous example
$tmp_thumb = tempnam(sys_get_temp_dir(), 'thumb');
imagejpeg($thumb, $tmp_thumb);
$thumbData = file_get_contents($tmp_thumb);
mysql_query("INSERT INTO images (original, thumb) VALUES ('" . mysql_real_escape_string($fileData) . "', '" . mysql_real_escape_string($thumbData) . "');");
}
The fields needs to be BLOB
.