php developer near denver, colorado
// Use at your own risk. No warranty expressed or implied.
// Also requires http://www.hockinson.com/getimage.txt saved as getimage.php
/**
* After browsing for the first file, a prompt should appear to "Attach another file".
* Note there is some PHP mixed in with the Javascript in this page.
* If a target directory does not exist, an attempt is made to create the directory.
* Image uploads should be JPG/JPEG files, especially if inserting in MySQL.
* Resampling with compression will often save a lot of bytes.
* The `comment` fields are initially populated with the filename and
* optionally edited later to associate descriptions with the image.
* For a given pair of images (thumb and main) the
* `upld_time` field contains matching time() values.
# Table in which file information can be saved
# DROP TABLE IF EXISTS `my_upload_data`;
CREATE TABLE IF NOT EXISTS `my_upload_data` (
`upld_id` smallint(5) unsigned NOT NULL auto_increment,
`user_id` varchar(20) NOT NULL,
`user_name` varchar(20) NOT NULL default '',
`comment` text NOT NULL,
`upld_time` varchar(10) NOT NULL default '',
`dir` varchar(255) NOT NULL,
`filename` varchar(50) NOT NULL default '',
`ext` varchar(5) NOT NULL default '',
`mime_type` varchar(50) NOT NULL default '',
`category` enum('image','thumb','other') NOT NULL default 'image',
`html_tag` text NOT NULL,
`img_width` varchar(4) NOT NULL default '',
`img_height` varchar(4) NOT NULL default '',
`img_type_no` varchar(2) NOT NULL default '',
`img_type_txt` varchar(20) NOT NULL default '',
`img_src_attr` varchar(30) NOT NULL default '',
`hidden` enum('0','1') NOT NULL default '0',
`deleted` enum('0','1') NOT NULL default '0',
`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`upld_id`),
KEY `user_id` (`user_id`),
KEY `user_name` (`user_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# Table in which binary BLOB data can be saved
# DROP TABLE IF EXISTS `my_upload_binary`;
CREATE TABLE IF NOT EXISTS `my_upload_binary` (
`imgid` mediumint(6) NOT NULL auto_increment,
`user_id` mediumint(6) NOT NULL default '0',
`upld_time` char(10) NOT NULL,
`category` enum('image','thumb','other') NOT NULL default 'image',
`filename` char(255) NOT NULL default '',
`image_caption` char(255) NOT NULL default '',
`image` blob NOT NULL,
`image_width` smallint(5) unsigned NOT NULL default '0',
`image_height` smallint(5) unsigned NOT NULL default '0',
`image_type1` tinyint(2) unsigned NOT NULL default '0',
`image_type2` char(20) NOT NULL default '',
`img_attrib` char(30) NOT NULL default '',
`hidden` tinyint(1) unsigned NOT NULL default '0',
`deleted` tinyint(1) unsigned NOT NULL default '0',
`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`imgid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
**/
$cfg = array();
$cfg['debug'] = 0; // [0|1] See the function abort() where debugging scripts could be called
$cfg['comments'] = 1; // [0|1] Display certain comments during the upload process
$cfg['form']['suppress_options'] = 0; // use hidden INPUT fields to pass image manipulation values
// GET method default form values / options
$cfg['form']['max_width_thumb_start'] = 80; // drop down SELECT box settings
$cfg['form']['max_width_thumb_stop'] = 350; // drop down SELECT box settings
$cfg['form']['max_width_image_start'] = 400; // drop down SELECT box settings
$cfg['form']['max_width_image_stop'] = 800; // drop down SELECT box settings
$cfg['create_thumb'] = 1; // [0|1] set 0 to avert the creation of thumbnails
$cfg['max_width'] = 500; // uploaded originals will be resized downward to this pixel width
$cfg['max_width_thumb'] = 200; // thumbnail width (height will vary unless originals all have the same aspect ratio, 4:3 recommended)
$cfg['jpeg_compression'] = 75; // JPEG compression ratio percentage, 75 recommended although lower will sometimes work
$cfg['dir_imgs'] = 'images'; // directory relative to script location, target directory for images (closing slash appended later)
$cfg['dir_docs'] = 'other'; // directory relative to script location, target directory for non-images files (closing slash appended later)
// Handling of $cfg['dir_docs'] could be expanded below, to sort out DOC, TXT, RTF, CSV, etc., to different folders
$cfg['mkdir_perm'] = '0755';
$cfg['limit'] = 5; // File limit affecting Javascript below, and PHP
$cfg['allowed_image_extensions'] = array('gif', 'jpg', 'png', 'tif'); // lower case
$cfg['allowed_other_extensions'] = array('doc', 'txt', 'xls', 'rtf'); // lower case
$cfg['allowed_display_extensions'] = array_merge($cfg['allowed_image_extensions'], $cfg['allowed_other_extensions']);
$cfg['mysql']['hn'] = 'localhost'; // MySQL host name (usually localhost)
$cfg['mysql']['db'] = 'yourDatabase'; // MySQL database name
$cfg['mysql']['un'] = 'yourUsername'; // MySQL user name
$cfg['mysql']['pw'] = 'yourPassword'; // MySQL password
$cfg['mysql']['tb']['data'] = 'my_upload_data'; // MySQL image table
$cfg['mysql']['tb']['binary'] = 'my_upload_binary'; // MySQL image table
$cfg['mysql']['thumb'] = 0; // [0|1] Inserting images in MySQL is not recommended
$cfg['mysql']['image'] = 0; // [0|1] Inserting images in MySQL is not recommended
$cfg['delete_temp_file'] = 1; // [0|1] Delete temp files
$cfg['overwrite'] = 1; // [0|1] Overwrite existing files. Any value other than 1 causes an underscore to be appended to the filename (instead of overwriting existing files)
$cfg['max_file_size'] = 4096000; // Arbitrary, also affected by other system configuration variables. Maximum bytes as an integer (no commas); 2048000 is about 2-megabytes
// $cfg['upload_max_filesize'] = ini_get('upload_max_filesize')
// Do NOT alter $cfg['image']['type_ary']
$cfg['image']['type_array'] = array( '0' => 'None', '1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '4' => 'SWF', '5' => 'PSD', '6' => 'BMP', '7' => 'TIFF (Intel)', '8' => 'TIFF (Motorola)', '9' => 'JPC', '10' => 'JP2', '11' => 'JPX', '12' => 'JB2', '13' => 'SWC', '14' => 'IFF', '15' => 'WBMP', '16' => 'XBM' );
?>
';
for($i = 0; $i < $cfg['limit']; $i++){
if(isset($_FILES['toProcess']['tmp_name']["$i"]) && file_exists($_FILES['toProcess']['tmp_name']["$i"])){
unlink($_FILES['toProcess']['tmp_name']["$i"]);
}
}
if($cfg['debug']){
// See http://dbug.ospinto.com/
require_once('dev/dBug.php');
// new dBug($_FILES);
new dBug($GLOBALS);
}
echo "\n".'';
exit;
};
function append_filename($filename, $str = '_')
{
if(empty($filename)){
abort('Filename not specified');
}
$ext = strrchr($filename, '.');
return substr($filename, 0, -strlen($ext)).$str.$ext;
};
function filtered_filename($str)
{
// Rename the uploaded file to a Linux compatible filename.
// Replace accented characters with equivalents (hopefully!)
$str = strtr($str, "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa\xda\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf\xf8", "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNoOoOoOoOoOoOoouUuUuUuUyYyaAso");
// Force lower string
$str = trim(strtolower($str));
// Replace multiple spaces with one space
$str = ereg_replace(' +', ' ', $str);
// Replace spaces with underscore
$str = str_replace(' ', '_', $str);
// Replace hyphens with underscore
$str = str_replace('-', '_', $str);
// In case there was a space/hyphen next to an underscore
$str = ereg_replace('_+', '_', $str);
return trim(preg_replace('/[^[:lower:][:digit:]_\.]/', '', $str));
};
function save_image_data($dir, $file, $mime_type)
{
global $cfg;
// incoming $dir has a slash appended to it
$uri = $dir.$file;
// Executed upon successful upload
if(is_readable($uri)){
// Fetch image details again, instead of relying on variables determined earlier and passed to this function.
if(!@list($img_width, $img_height, $img_type_no, $img_src_attr) = getimagesize($uri)){
abort('Cannot obtain the image properties for '.$uri);
}else{
echo "\n".'
'.$qry);
}else{
// $last_insert_id = @mysql_insert_id();
}
}else{
abort('The uploaded file is not readable');
}
};
function image2myql($dir, $file, $mime_type, $category)
{
// Insert binary BLOB data and other image properties into MySQL.
// incoming $dir has a slash appended to it.
global $cfg;
$uri = $dir.$file;
// Optionally insert the uploaded image into MySQL (NOT RECOMMENDED)
// test for db connection
if(@is_readable($uri)){
$user_id = isset($_SESSION['sess_user_id']) ? $_SESSION['sess_user_id'] : 0;
if(!@list($img_width, $img_height, $img_type_no, $img_src_attr) = getimagesize($uri)){
abort('Cannot obtain the image properties for '.$uri);
}
// Cannot apply fclose() as expected (PHP error returned)
if($data = addslashes(@fread(@fopen($uri, "rb"), @filesize($uri)))){
$image_caption = $file;
$qry = sprintf("INSERT INTO `{$cfg['mysql']['tb']['binary']}` (`user_id`, `upld_time`, `category`, `filename`, `image`, `image_caption`, `image_width`, `image_height`, `image_type1`, `image_type2`, `img_attrib`)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
addslashes($user_id), $cfg['upld_time'], $category, addslashes($file), $data, addslashes($image_caption), $img_width, $img_height, $img_type_no, $mime_type, $img_src_attr);
if(!$res = @mysql_query($qry)){
abort('Cannot insert BLOB into MySQL: '.mysql_error());
}else{
$id = @mysql_insert_id();
echo "\n".'
MySQL Image ID #'.$id.' inserted into database. Do not re-load this page.
';
echo "\n".'
'.htmlentities('
');
echo "\n".'
';
}
//fclose($uri); // ToDo: research PHP fclose() failure
}else{
abort('fread() or fopen() failed for '.$uri);
}
}else{
abort('File is not readable by the function image2myql()');
}
};
// To Do: incorporate on GET mode also, relocate the abort() function
if(!$gd_exists = @get_extension_funcs('gd')){
abort('The required GD library does not appear to exist on the server');
}
// File error checking. $cfg['limit'] files may or may not have been submitted.
$num_errors = 0;
for($i = 0; $i < $cfg['limit']; $i++){
if(isset($_FILES['toProcess']['error'][$i]) && $_FILES['toProcess']['error'][$i] == 4){
$num_errors++;
}
}
if($num_errors){
abort('Error count = '.$num_errors.'. Either an empty Browse box was submitted, or an unknown error occurred during upload.');
}else{
// Connect to MySQL
$persistent = '';
if($persistent == (bool) ini_get('allow_persistent')){
if(!$cfg['dbh'] = mysql_pconnect($cfg['mysql']['hn'], $cfg['mysql']['un'], $cfg['mysql']['pw'])){
abort('Error mysql_pconnect: '.mysql_error());
}
}else{
if(!$cfg['dbh'] = mysql_connect($cfg['mysql']['hn'], $cfg['mysql']['un'], $cfg['mysql']['pw'])){
abort('Error mysql_connect: '.mysql_error());
}
}
if(!mysql_select_db($cfg['mysql']['db'], $cfg['dbh'])) {
abort('Error mysql_select_db: '.mysql_error());
}
// Comment out if not using UTF8
if(!mysql_query('SET NAMES UTF8')){ abort('Error SET NAMES UTF8: '.mysql_error()); }
if(!mysql_query('SET COLLATION_CONNECTION=UTF8_GENERAL_CI')){ abort('Error SET COLLATION_CONNECTION=UTF8_GENERAL_CI: '.mysql_error()); }
$num_files = count($_FILES['toProcess']['name']);
for($i = 0; $i < $num_files; $i++){
$file_err = $_FILES['toProcess']['error']["$i"];
$fsize = $_FILES['toProcess']['size']["$i"];
// Abort if the user clicked Submit without selecting a file
if($fsize == 0){
abort('Please use the Browse button to select a file');
}elseif($fsize > $cfg['max_file_size']){
abort('The uploaded file is larger than that of the maximum allowed file size.');
}
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 on this server.'); break;
case '2': abort('This file exceeds the maximum file size specified in the HTML form.'); 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.'); break;
case '4': abort('You did not upload anything. Please go back and Browse for a file to upload.'); break;
case '6': abort('Missing a temporary folder.'); break;
default: abort('An unknown error occurred.'); break;
}
}
$cfg['tmp_file_size'] = $_FILES['toProcess']['size']["$i"];
if($cfg['tmp_file_size'] > $cfg['max_file_size']){
abort('The uploaded file exceeds the configured '.number_format($cfg['max_file_size']).'-byte limit');
}
echo "\n".'';
if(isset($_FILES['toProcess']['tmp_name']["$i"]) && is_uploaded_file($_FILES['toProcess']['tmp_name']["$i"])){
// $_FILES['toProcess']['name']["$i"] contains the original filename
// $_FILES['toProcess']['tmp_name']["$i"] contains the temporary filename
// Alter the filename in an attempt to create a web friendly filename
$filename = filtered_filename($_FILES['toProcess']['name']["$i"]); // original filename without path
// extension should be initialized, then checked and $dir altered accordingly
$ext = '';
if(stristr($filename, '.')){
$ext = substr(strrchr($filename, '.'), 1); // returns characters found after the period
}
// Set the appropriate target directory for the uploaded file.
// Extend if anticipating a wide variety of uploads.
if($ext && in_array(strtolower($ext), $cfg['allowed_image_extensions'])){
$dir = $cfg['dir_imgs'];
}else{
$dir = $cfg['dir_docs'];
}
// If $dir is not found, attempt to create it
if(!is_dir($dir)){
if(!@mkdir($dir, $cfg['mkdir_perm'])){
abort('Cannot create directory: '.$dir);
}
}
$dir .= '/'; // add trailing slash
$uri = $dir.$filename;
if(!move_uploaded_file($_FILES['toProcess']['tmp_name']["$i"], $uri)){
abort('Cannot move '.$_FILES['toProcess']['tmp_name']["$i"].' to '.$uri);
}else{
// No errors on upload
$mime_type = $_FILES['toProcess']['type']["$i"]; // MIME type can be misleading in the case of PDF's generated as forced-download
if($ext && in_array(strtolower($ext), $cfg['allowed_other_extensions'])){
// non-image file, mime type could be switch()'ed here to append $dir and sort files into subdirectories.
echo "\n".'
';
$cfg['upload_is_image'] = 0;
$cfg['category'] = 'other'; // arbitrary value inserted in MySQL category field
data2mysql($mime_type, $dir, $filename, '', $cfg['category']);
}elseif($ext && in_array(strtolower($ext), $cfg['allowed_image_extensions'])){
// File is an image
$cfg['upload_is_image'] = 1;
// $image_uploads[] = $uri;
if(!list($img_width, $img_height, $img_type_no, $img_src_attr) = getimagesize($uri)){
abort('Cannot obtain the image properties for '.$filename);
}
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, however processing for the MIME type is not configured.');
break;
};
// Destroy $src_img when no longer needed and/or in the abort function
if(!$src_img = $createfunction($uri)){
abort('Cannot execute createfunction()');
}
$new_w = (int) ($img_width < $cfg['max_width_thumb'] ? $img_width : $cfg['max_width_thumb']);
$new_h = (int) (imagesy($src_img) / (imagesx($src_img) / $new_w));
// Destroy $dst_img when no longer needed and/or in the abort function
if(!$dst_img = imagecreatetruecolor($new_w, $new_h)){
abort('Cannot execute ImageCreateTrueColor()');
}
if(!imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, imagesx($src_img), imagesy($src_img))){
abort('Cannot execute ImageCopyResampled()');
}
// Conditional thumbnail. If the uploaded image is wider than the max. thumb width, make a thumbnail
if($cfg['create_thumb'] && $img_width > $cfg['max_width_thumb']){
echo $cfg['comments'] ? "\n".'