How To Insert Images Into MySQL Database
Note: this is not a complete project. No support is offered.
Related scripts might provide some ideas to those of you who building your own File Upload Application, or wanting to insert images in a MySQL database table. These examples may be missing some certain (minor) functions that are part of the CMS from which these examples were extracted.
These scripts were extracted a CMS in the scenario that a user is logged in and wants to upload both image files and non-image files. An attempt is made to sort the incoming files in subdirectories located under a ./upl/ directory (based on MIME type and/or filename extension). And, optionally insert an uploaded image and/or image thumbnail in MySQL.
Part 1 of 5 - Part 2 of 5 - Part 3 of 5 - Part 4 of 5 - Part 5 of 5
<?php
// upload.proc.php Processing script for image upload application
@require_once('upload.cfg.php');
@require_once('upload.func.php');
if(isset($_SERVER['HTTP_REFERER']) && !stristr($_SERVER['HTTP_REFERER'], $opts['domain'])){
abort('Unauthorized POST: '.$_SERVER['HTTP_REFERER']);
}
if(!@is_dir($opts['cfg']['dir_name'])){
abort('Cannot locate directory: '.$opts['cfg']['dir_name'], 1);
}
if(!@is_writable($opts['cfg']['dir_name'])){
abort('Cannot write to the directory: '.$opts['cfg']['dir_name'], 1);
}
if(!empty($_POST['comment'])){
foreach($_POST['comment'] as $key => $val){
if($val != ''){ $comment[$key] = trim(stripslashes(strip_tags($val))); }
}
}
if($opts['cfg']['comment_reqd'] == 1){
if(count($comment) == 0){
abort('Please enter a Caption for each uploaded file', 1);
}
}
foreach($_POST as $key => $val){
if($key != 'comment'){
$$key = trim(stripslashes(strip_tags($val)));
}
}
$uploaded_file_count = 0;
foreach($_FILES['toProcess']['error'] as $val){
if($val === 0){
$uploaded_file_count++;
}
}
echo $opts['debug'] > 0 && $uploaded_file_count > 0 ? "\n".'<p>File(s) to process: '.$uploaded_file_count.'</p>' : '';
if($uploaded_file_count === 0){
abort('No files uploaded', 1);
}
// Disallow unwanted image types
if(count($_FILES['toProcess']['type']) > 0){
foreach($_FILES[toProcess][type] as $val){
if(substr($val, 0, 6) == 'image/' && !in_array($val, $opts['cfg']['mime_img_restriction'])){
abort('This application is not configured to work with uploaded image files of MIME type '.$val, 1);
}
}
}
// Process $i files
for($i = 0; $i < $uploaded_file_count; $i++){
$opts['cfg']['dir_name'] = './upl';
$opts['temp_filename'] = $_FILES['toProcess']['tmp_name']["$i"];
$filename = $_FILES['toProcess']['name']["$i"];
echo $opts['debug'] > 0 ? "\n".'<p>Original filename: '.$filename.'</p>' : '';
$fsize = $_FILES['toProcess']['size']["$i"];
echo $opts['debug'] > 0 ? "\n".'<p>Original file size: '.$fsize.'</p>' : '';
if($fsize == 0){
abort('Please use the Browse button to select a file', 1);
}elseif($fsize > $opts['image']['max_file_size']){
abort('The uploaded file is too large', 1);
}
$mime_type = $_FILES['toProcess']['type']["$i"]; // MIME type can be misleading in the case of PDF's generated as forced-download
echo $opts['debug'] > 0 ? abort('$mime_type = '.$mime_type) : '';
if(empty($mime_type)){
abort('Cannot determine the type of file', 1);
}
echo $opts['debug'] > 0 ? "\n".'<p>File type: '.$mime_type.'</p>' : '';
// Do not add a slash to the path/directory name *yet*
if(!@is_dir($opts['cfg']['dir_name'])){
// Due to security issues, most web hosts prohibit PHP scripts from making directories (writable)
if(@mkdir($opts['cfg']['dir_name'], 0777, TRUE)){
echo "\n".'<p>Creating directory:<br>'.$opts['cfg']['dir_name'].'</p>';
}else{
abort('Cannot create directory: '.$opts['cfg']['dir_name'], 1);
}
}
if(!@is_writable($opts['cfg']['dir_name'])){
abort('Write permission denied: '.$opts['cfg']['dir_name'], 1);
}
// Now it is time to add a trailing slash to the configured path
$opts['cfg']['dir_name'] .= '/';
// Check the uploaded filename has an extension.
// PREVIOUSLY LOCATED BELOW: if($file_err != 0 || $fsize == 0){
echo $opts['debug'] > 0 ? "\n".'<p>File extension: '.$file_ext.'</p>' : '';
if(!$file_ext = strrchr($filename, '.')){
abort('The filename extension is missing from '.$filename, 1);
}
$ext_test = substr(strtolower($file_ext), 1);
echo $opts['debug'] > 0 ? "\n".'<p>$ext_test = '.$ext_test.'</p>' : '';
if(!in_array($ext_test, $opts['cfg']['allowed_ext'])){
$allowed = implode(', ', $opts['cfg']['allowed_ext']);
abort('The filename extension '.$file_ext.' was not found in the configured list of allowed filename extensions: '.$allowed, 1);
}
// Evaluate the MIME type. Redirect certain MIME types into folders below $opts['cfg']['dir_name']
$opts['upload_is_image'] = 0; // See switch($mime_type)
switch($mime_type)
{
Case 'image/bmp':
Case 'image/gif':
Case 'image/jpg':
Case 'image/jpeg':
Case 'image/pjpeg':
Case 'image/png':
Case 'image/x-png':
$opts['cfg']['dir_name'] .= 'imgs';
$opts['upload_is_image'] = 1;
$upl_sub_dir = get_cgi_var('upl_sub_dir');
if(empty($upl_sub_dir)){
abort('Please go back and select a destination folder (album)', 1);
}
if('default' != $upl_sub_dir){
$opts['cfg']['dir_name'] .= '/';
$opts['cfg']['dir_name'] .= $upl_sub_dir;
}
break;
default:
// If not an image file, analyze the filename extension.
// $mime_type is not the best directory-slecting method
// (e.g. a PDF created by forced download does not indicate PDF file type)
switch($ext_test)
{
Case 'avi':
Case 'mpeg':
Case 'mpg':
$opts['cfg']['dir_name'] .= 'video';
break;
Case 'doc':
$opts['cfg']['dir_name'] .= 'msword';
break;
Case 'pdf':
$opts['cfg']['dir_name'] .= 'pdf';
break;
Case 'ppt':
$opts['cfg']['dir_name'] .= 'msppt';
break;
Case 'swf':
$opts['cfg']['dir_name'] .= 'swf';
break;
Case 'txt':
$opts['cfg']['dir_name'] .= 'text';
break;
Case 'csv':
Case 'xls':
$opts['cfg']['dir_name'] .= 'msexcel';
break;
Case 'wav':
$opts['cfg']['dir_name'] .= 'audio';
break;
default:
$opts['cfg']['dir_name'] .= 'other';
break;
};
break;
}; # End switch
// Having altered the path, check for existence of the new directory name
if(!@is_dir($opts['cfg']['dir_name'])){
abort('Cannot locate directory: '.$opts['cfg']['dir_name'], 1);
}
if(!@is_writable($opts['cfg']['dir_name'])){
abort('Write permission denied: '.$opts['cfg']['dir_name'], 1);
}
// Add the slash
$opts['cfg']['dir_name'] .= '/';
echo $opts['debug'] > 0 ? "\n".'<p>Target directory: '.$opts['cfg']['dir_name'].'</p>' : '';
$file_err = $_FILES['toProcess']['error']["$i"];
// Abort if the user clicked Submit without selecting a file
if($file_err != 0 || $fsize == 0){
switch($file_err){
case '1': abort('This file, at '.number_format($fsize).' bytes, exceeds the maximum allowed file size allowed by this server.', 1); break;
case '2': abort('This file exceeds the maximum file size specified in your HTML form', 1); break;
case '3': abort('File was only partially uploaded. This could be the result of your connection being dropped in the middle of the upload.', 1); break;
case '4': abort('You did not upload anything.<br><br>Please go back and Browser for a file to upload.', 1); break;
case '6': abort('Missing a temporary folder.', 1); break;
default: abort('An unknown error occurred.', 1); break;
}
}
$opts['tmp_file_size'] = $_FILES['toProcess']['size']["$i"];
if($opts['tmp_file_size'] > $opts['image']['max_file_size']){
abort('The uploaded file exceeds the configured '.number_format($opts['image']['max_file_size']).'-byte limit', 1);
}
// extra check to prevent file attacks.
if(!@is_uploaded_file($opts['temp_filename'])){
abort('The uploaded file does not appear to be a valid upload.', 1);
}
// Copy the uploaded file from the temporary directory to its final destination.
if(!@move_uploaded_file($opts['temp_filename'], $opts['cfg']['dir_name'].$filename)){
abort('Unable to move '.$opts['temp_filename'].' to '.$opts['cfg']['dir_name'].$filename, 1);
}
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Temporary file copied to '.$opts['cfg']['dir_name'].$filename.'</p>' : '';
$safe_filename = filtered_filename($filename);
if(@rename($opts['cfg']['dir_name'].$filename, $opts['cfg']['dir_name'].$safe_filename)){
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Renaming "'.$filename.'" as "'.$safe_filename.'"</p>' : '';
$filename = $safe_filename;
}else{
abort('Cannot rename '.$filename.' as '.$safe_filename, 1);
}
// Process image files differently from other types of files
if($opts['upload_is_image'] == 0){
if(@is_file($opts['cfg']['dir_name'].$filename)){
echo "\n".'<p>File uploaded: '.$opts['cfg']['dir_name'].$filename.'</p>';
echo "\n".'<p>Here is the HTML for your web link:<br><br>';
$html_tag = '<a href="'.$opts['cfg']['dir_name'].$filename.'" title="'.$filename.'" target="_blank">'.$filename.'</a>';
echo htmlspecialchars($html_tag);
echo "\n".'<br><br>Here is the actual link: '.$html_tag;
echo '</p>';
echo "\n".'<p><a href="./index.php?s=24" title="Upload Files">Upload Files</a></p>';
if(!execute_upld_log($comment[$i], $mime_type, $opts['cfg']['dir_name'], $filename, $html_tag, 'other')){
$opts['error_msg'] .= 'Execution of execute_upld_log() failed'."\n";
}
}else{
abort('Cannot locate file: '.$opts['cfg']['dir_name'].$filename, 1);
}
}elseif($opts['upload_is_image'] == 1){
// Create thumbnail first, then resample the main image
if(!@list($img_width, $img_height, $img_type_no, $img_src_attr) = getimagesize($opts['cfg']['dir_name'].$filename)){
abort('Cannot obtain the image properties for '.$filename, 1);
}
switch($mime_type)
{
Case 'image/gif':
$createfunction = 'imagecreatefromgif';
break;
Case 'image/jpg':
Case 'image/jpeg':
Case 'image/pjpeg':
$createfunction = 'imagecreatefromjpeg';
break;
Case 'image/png':
Case 'image/x-png':
$createfunction = 'imagecreatefrompng';
break;
default:
abort('Unsupported MIME file type: '.$mime_type.' Your file may have uploaded OK but cannot be processed further.', 1);
break;
}; # End switch
if(!$src_img = $createfunction($opts['cfg']['dir_name'].$filename)){
abort('Cannot execute createfunction', 1);
}
$new_w = (int) ($img_width < $max_width_thumb ? $img_width : $max_width_thumb);
$new_h = (int) (imagesy($src_img) / (imagesx($src_img) / $new_w));
if(!$dst_img = @imagecreatetruecolor($new_w, $new_h)){
abort('Cannot execute ImageCreateTrueColor', 1);
}
if(!@imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img))){
abort('Unable to make ImageCopyResampled', 1);
}
// If the uploaded image is wider than the max. thumb width, make a thumbnail
if($create_thumb == 1 && $img_width > $max_width_thumb){
$opts['category'] = 'thumb';
echo $opts['debug'] > 0 ? "\n".'<p>Creating thumbnail...</p>' : '';
$thumbnail_filename = append_filename($filename, '_thumb');
// If thumbnail name already exists, append again???
if($opts['cfg']['overwrite'] != 1){
if(@file_exists($opts['cfg']['dir_name'].$thumbnail_filename)){
$thumbnail_filename = append_filename($thumbnail_filename, '_');
}
}
if(!@ImageJpeg($dst_img, $opts['cfg']['dir_name'].$thumbnail_filename, $jpeg_compression)){
abort('Cannot execute ImageJpeg for '.$dst_img, 1);
echo $opts['debug'] > 0 ? "\n".'<p>FAIL: thumbnail image</p>' : '';
}else{
display_image_details($opts['cfg']['dir_name'], $thumbnail_filename, $mime_type, $comment[$i]);
if($mysql_thumb > 0){
image2myql($opts['cfg']['dir_name'], $thumbnail_filename, $mime_type, $comment[$i], $opts['category']);
}
}
echo $opts['debug'] > 0 ? "\n".'<p>Processing large image...</p>' : '';
if(@imagesx($src_img) > $max_width){
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Reducing image width by '.(imagesx($src_img) - $max_width).' pixels ('.imagesx($src_img).' --> '.$max_width.')</p>' : '';
}else{
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Original image width maintained at '.imagesx($src_img).' pixels</p>' : '';
}
}
// Create full size image
$opts['category'] = 'image';
$main_image_filename = append_filename($filename, '_main');
if($opts['cfg']['overwrite'] != 1){
if(@file_exists($opts['cfg']['dir_name'].$main_image_filename)){
$main_image_filename = append_filename($main_image_filename, '_');
}
}
$new_w = (int) ($img_width > $max_width ? $max_width : $img_width);
$new_h = (int) ($img_width > $max_width_thumb ? @imagesy($src_img) / ( @imagesx($src_img) / $new_w ) : $img_height);
echo $opts['debug'] > 0 ? '<p>$new_w = '.$new_w.', $new_h = '.$new_h.'</p>' : '';
if(!$dst_img = @ImageCreateTrueColor($new_w, $new_h)){
abort('Cannot execute ImageCreateTrueColor', 1);
}
if(!$res = @ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img))){
abort('Cannot execute ImageCopyResampled using '.$src_img, 1);
}
if(!@ImageJpeg($dst_img, $opts['cfg']['dir_name'].$main_image_filename, $jpeg_compression)){
abort('Cannot execute ImageJpeg for '.$dst_img, 1);
}
display_image_details($opts['cfg']['dir_name'], $main_image_filename, $mime_type, $comment[$i]);
if($mysql_image > 0){
image2myql($opts['cfg']['dir_name'], $main_image_filename, $mime_type, $comment[$i], $opts['category']);
}
if($opts['cfg']['delete_original'] > 0 && file_exists($opts['cfg']['dir_name'].$filename)){
if(@unlink($opts['cfg']['dir_name'].$filename)){
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Deleting '.$filename.' ('.number_format($opts['tmp_file_size']).' bytes)</p>' : '';
}else{
echo $opts['comment']['verbose'] > 0 ? "\n".'<p>Unable to delete original: '.$filename.' ('.number_format($opts['tmp_file_size']).' bytes)</p>' : '';
}
}else{
display_image_details($opts['cfg']['dir_name'], $filename, $mime_type, $comment[$i]);
echo $opts['debug'] > 0 ? "\n".'<p>OK: displayed image details 3 above</p>' : '';
}
}
if(@file_exists($opts['temp_filename'])){
unlink($opts['temp_filename']);
}
}
?>