To upload an image, use this code:
<input name="picture" type="file">
That will create a text box with the "Browse" button beside where you can browse for the file to upload.
Then, when you get to the action page, you will have a new array called $FILES. Do a print_r($FILES); to check it out. You will get an output similer to:
Array
(
[picture] => Array
(
[name] => picname.jpg
[type] => image/pjpeg
[tmp_name] => C:\WINNT\TEMP\php305.tmp
[error] => 0
[size] => 88024
)
)
So now you know where the image has been uploaded to, and the name of it. You will then have to copy (or move) the file to where you want it, and rename it accordingly.
This is the code that I use to do it:
# Copy the uploaded file to the pictures directory, renaming it with the tool id #
if (!empty($_FILES[picture][name])) {
$destination = "./pictures/" . $_POST['tool_id'] . ".jpg";
copy_and_resize($connection, $_FILES[picture][tmp_name], $destination);
}
The function "copy_and_resize" is used to do just that. I use it to resize the picture if it's too big, and copy and rename it to the appropriate location.
# This function takes the $source file, resizes it, and saves it to the destination
function copy_and_resize($connection, $source, $destination) {
#echo "Source: $source, Destination: $destination<br>";
## CONFIG ##
$picture_location= $source;
$picture_save= $destination;
$size=600; // size in pixel u want the picture to come out
# Only resize if the original width or height is greater then the size we want
# (so only resize if the pic is too big)
$img_src = ImageCreateFromjpeg ($source);
$true_width = imagesx($img_src); // actual width of the original picture
$true_height = imagesy($img_src); // actual height of the original picture
if ($true_width >= $size or $true_height >= $size) {
$img_des=resize_img($picture_location,$size);
} else {
$img_des = $img_src;
}
# imagejpeg($img_des); // only show thumbnail picture
imagejpeg($img_des,$picture_save); // show and save the picture
}
function resize_img($picture_location,$size) {
Header("Content-Type: image/jpeg");
$img_src = ImageCreateFromjpeg ($picture_location);
$true_width = imagesx($img_src); // actual width of the original picture
$true_height = imagesy($img_src); // actual height of the original picture
if ($true_width >= $true_height) {
$width=$size;
$height = ($width/$true_width)*$true_height;
} else {
$height=$size;
$width = ($height/$true_height)*$true_width;
}
$img_des = ImageCreateTrueColor($width,$height);
imagecopyresized ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width, $true_height);
return $img_des;
}