how can I add imaging handling got this script effectively - php

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}

See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().

Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}

you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Related

PrestaShop: allow customers to upload PDF, AI and EPS files as product customization

I am running Prestashop 1.6.1.7 and I have the following pictureUpload() method that allows users to upload files of their choosing. By default Prestashop allows uploads of GIF, JPG, JPEG or PNG only.
I'm trying to allow users the ability to upload a few more types (pdf, ai and eps specifically)
Here is the pictureUpload() method in the productController override:
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
//$file_name = md5(uniqid(rand(), true));
$file_name = $file['name']; // In this
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
}
}
return true;
}
This is looking to the ImageManager class, which has this method (that I have updated the error message on):
public static function validateUpload($file, $max_file_size = 0, $types = null)
{
if ((int)$max_file_size > 0 && $file['size'] > (int)$max_file_size) {
return sprintf(Tools::displayError('Image is too large (%1$d kB). Maximum allowed: %2$d kB'), $file['size'] / 1024, $max_file_size / 1024);
}
if (!ImageManager::isRealImage($file['tmp_name'], $file['type']) || !ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
return Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png, .pdf, .ai, .eps'); //I Updated This - this is the error kicking off when I try to upload AI
}
if ($file['error']) {
return sprintf(Tools::displayError('Error while uploading image; please change your server\'s settings. (Error code: %s)'), $file['error']);
}
return false;
}
The place where that method fails is pointing to two additional methods posted below. I updated the isRealImage method to try and allow the types I wanted through, but it still fails (and I commented where it fails).
public static function isRealImage($filename, $file_mime_type = null, $mime_type_list = null)
{
// Detect mime content type
$mime_type = false;
if (!$mime_type_list) {
//I UPDATED THIS LIST TO ALLOW FOR OTHER FILETYPES
$mime_type_list = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'application/illustrator', 'application/ai', 'application/eps', 'application/x-eps', 'image/eps', 'image/x-eps', 'application/pdf', 'application/acrobat', 'application/x-pdf', 'text/pdf', 'text/x-pdf');
}
// Try 4 different methods to determine the mime type
if (function_exists('getimagesize')) {
$image_info = #getimagesize($filename);
//HERE IMAGE_INFO IS SHOWING AS 'FALSE' SO IT GOES NO FURTHER WHEN UPLOADING A .AI FILE
if ($image_info) {
$mime_type = $image_info['mime'];
} else {
$file_mime_type = false;
}
} elseif (function_exists('finfo_open')) {
$const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$finfo = finfo_open($const);
$mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$mime_type = mime_content_type($filename);
} elseif (function_exists('exec')) {
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($filename)));
if (!$mime_type) {
$mime_type = trim(exec('file --mime '.escapeshellarg($filename)));
}
if (!$mime_type) {
$mime_type = trim(exec('file -bi '.escapeshellarg($filename)));
}
}
if ($file_mime_type && (empty($mime_type) || $mime_type == 'regular file' || $mime_type == 'text/plain')) {
$mime_type = $file_mime_type;
}
// For each allowed MIME type, we are looking for it inside the current MIME type
foreach ($mime_type_list as $type) {
if (strstr($mime_type, $type)) {
return true;
}
}
return false;
}
I also updated the isCorrectImageFileExt method:
public static function isCorrectImageFileExt($filename, $authorized_extensions = null)
{
// Filter on file extension
if ($authorized_extensions === null) {
//ADDED ALLOWED TYPES I WANT
$authorized_extensions = array('gif', 'jpg', 'jpeg', 'jpe', 'png', 'pdf', 'ai', 'eps');
}
$name_explode = explode('.', $filename);
if (count($name_explode) >= 2) {
$current_extension = strtolower($name_explode[count($name_explode) - 1]);
if (!in_array($current_extension, $authorized_extensions)) {
return false;
}
} else {
return false;
}
return true;
}
Thoughts on this?
Help on this?
You have gone too deep :). This is the pictureUpload method of ProductController that I've already made, you don't need others overrides. With my override you can upload pdf, ai, cdr and eps, but obviously you can change with your needs.
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
$file_name = md5(uniqid(rand(), true));
// Bad check, but rapid
$extension = substr($file['name'], -3, 3);
if($extension == 'jpg' OR $extension == 'gif' OR $extension == 'png'){
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
} elseif ($extension == 'pdf' OR $extension == '.ai' OR $extension == 'cdr' OR $extension == 'eps') {
$file_name = $file_name.'.'.str_replace('.', '', $extension);
if (!move_uploaded_file($file['tmp_name'], _PS_UPLOAD_DIR_.$file_name)) {
return false;
}
chmod(_PS_UPLOAD_DIR_.$file_name, 0777);
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
} else {
$this->errors[] = Tools::displayError('This format is not accepted');
}
}
}
return true;
}
After that you have to customize product.tpl, the cart summary of your template, and the backoffice order detail :)
Another solution if you do not want to hack your PrestaShop installation, which is not recommended if you want to be able to upgrade PretaShop safely, is to develop or use an existing module.
This module on the PrestaShop marketplace is probably what you are looking for:
https://addons.prestashop.com/en/front-office-features-prestashop-modules/88383-upload-any-file-type-in-product-customization.html

Image fields are uploading php and other files to upload folder

My script is not working properly. If i upload a php file instead of jpg file then it should not upload php files to upload folder, i want to allow only image files. Please correct my script.
Here is my code Thanks !
<?php
include "inc.php";
ob_start();
if(!isset($_SESSION['ocer']) && trim($_SESSION['ocer'])!=''){
header("Location: admin.php?l=1");
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title=addslashes(mysql_real_escape_string($_REQUEST['title']));
$des=addslashes(mysql_real_escape_string($_REQUEST['des']));
$location=addslashes(mysql_real_escape_string($_REQUEST['location']));
$state=addslashes(mysql_real_escape_string($_REQUEST['state']));
$status=mysql_real_escape_string($_REQUEST['status']);
$userid=mysql_real_escape_string($_REQUEST['userid']);
$date1=mysql_real_escape_string($_REQUEST['date1']);
chmod('upload', 0777);
if($_FILES['file_name1']['name']!="")
{
$file_name1=$_FILES['file_name1']['name'];
$ext=getExtension($file_name1);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name1=mktime().'thumb1'.'.'.$ext;
copy($_FILES['file_name1']['tmp_name'],"upload/".$file_name1);
}
}
if($_FILES['file_name2']['name']!="")
{
$file_name2=$_FILES['file_name2']['name'];
$ext=getExtension($file_name2);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name2=mktime().'thumb2'.'.'.$ext;
copy($_FILES['file_name2']['tmp_name'],"upload/".$file_name2);
}
}
if($_FILES['file_name3']['name']!="")
{
$file_name3=$_FILES['file_name3']['name'];
$ext=getExtension($file_name3);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name3=mktime().'thumb3'.'.'.$ext;
copy($_FILES['file_name3']['tmp_name'],"upload/".$file_name3);
}
}
if($_FILES['file_name4']['name']!="")
{
$file_name4=$_FILES['file_name4']['name'];
$ext=getExtension($file_name4);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name4=mktime().'thumb4'.'.'.$ext;
copy($_FILES['file_name4']['tmp_name'],"upload/".$file_name4);
}
}
if(trim($title)!="" && trim($des)!=""){
$sql_ins="insert into `jobs` set title='$title',des='$des',location='$location',state='$state',date1='$date1',userid='$userid',status='$status',newsimg='$file_name1',newsimg2='$file_name2',newsimg3='$file_name3',newsimg4='$file_name4'";
$rs=mysql_query($sql_ins) or die(mysql_error());
$lid=mysql_insert_id();
$notice="job";
}
header("location: admin.php?done=1");
?>
try the following lines
$ext = pathinfo($_FILES["file_name3"]["name"], PATHINFO_EXTENSION);
if($ext...)// your if else condition
{}
else
{}
Part 1 :
$valid_mime_types = array(
"image/gif",
"image/png",
"image/jpeg",
"image/pjpeg",
);
if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 2 :
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($file_extension, $valid_file_extensions)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 3 :
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}

jQuery/PHP File Upload Times Out Before Loading Next Page

So I am developing the following image upload script, based off an existing open-source script. It's currently viewable live here: http://images.oneightynyc.com/
Now if you take any series of regular sized images (under 5mb) and proceed to upload them, the upload process goes just fine. Uploads the files, and brings you to a page that displays the link codes to those files. However let's say you upload a few large images, like the following:
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_005b.jpg
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_003b.jpg
The uploads happen in the process, however the script never brings you to the uploaded page. The only way I am aware that the upload has actually taken place is if I browse to the Gallery page and see that the files are listed there.
Here is the uploader.php file which handles the upload:
<?
//ob_start();
session_start();
$auth_id=$_SESSION['userid'];
if (!$auth_id || empty($auth_id) || $auth_id==""){
$auth_id = 0;
}
require_once("config.php");
require_once("limits.php");
require_once("ftp.class.php");
require_once("func.php");
$link = mysql_connect($db_server, $db_user, $db_password) or die("Could not connect to the database.");
mysql_select_db($db_name) or die("Could not select the database.");
if ($config[Uploads] == 0) {
$msg= "<center><b><br><br><br>Uploads are temporarily disabled by the site admin</center></b>";
}
else if ($config[Uploads] == 1 && !$auth_id) {
$msg= "<center><b><br><br><br>You have to Register before you will be able to upload photos.</center></b>";
}
$query = "select count(*) as total from ftp where status=1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$total=$row[total];
}
if($total<=0)
{
$no_server="1";
$ftpid=0;
$url=$server_url."/images/";
}
else
{
$query = "select * from ftp where status=1 ORDER BY RAND() limit 1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$no_server="0";
$ftpid=$row['ftpid'];
$path=$row['name'];
$url=$row['dir'];
$host=$row['host'];
$user=$row['user'];
$pass=$row['ftppass'];
}
}
// get variables for fields on upload screen
$tos = $_POST['tos'];
$prv = $_POST['prv'];
if($prv!="1")
$prv=0;
$uploaderip = $_SERVER['REMOTE_ADDR'];
$messages="";
$msg="";
$newID="";
$FileName="";
$FileFile="";
$FileUrl="";
$FileUrlLink="";
$FiletnUrl="";
// check for blocked ip address
if ($uploaderip != "") {
$query = "select ip from blocked where ip = '$uploaderip'";
$result = mysql_query($query) or die("Query failed.");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$msg= "Your IP address (".$uploaderip.") has been blocked from using this service.";
}
}
if ($config[AcceptTerms]=="1"){
if ($tos=="")
{
$msg= "You must check the box stating you agree to our terms.";
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
}
if($msg=="")
{
// check for a file
for($i=0;$i<=14;$i++)
{
$err="0";
$thefile = $_FILES['thefile'.$i];
if ($thefile['name']!="")
{
// check for valid file extension
$path_parts = pathinfo($thefile['name']);
$file_ext = strtolower($path_parts['extension']);
if ($err == "0")
{
// check for valid file type
if (!in_array_nocase($file_ext, $valid_file_ext))
{
$messages.= "|<em>".$thefile['name']."</em> is not in a valid format (".$valid_mime_types_display.")";
$err="1";
}
}
if ($err == "0") {
// check for valid image file
$imageinfo = getimagesize($_FILES['thefile0']['tmp_name']);
if(!eregi('image',$imageinfo['mime'])) {
$messages.="|". "Sorry, This is not a valid image file!";
$err="1"; } }
if ($err == "0")
{
// check for valid file size
if ($thefile['size'] > ($max_file_size_b))
{
$filesizemb =($thefile['size']/1048576);
$filesizemb = number_format($filesizemb, 3);
$messages.="Sorry but this image size is ".$filesizemb." MB which is bigger than the max allowed file size of ".$max_file_size_mb." MB.";
$err="1";
}
}
// save the file, if no error messages
if ($err == "0")
{
// replace special chars with spaces
$thefile['name'] = eregi_replace("[^a-z0-9.]", " ", $thefile['name']);
// Replace multiple spaces with one space
$thefile['name'] = ereg_replace(' +', ' ', $thefile['name']);
// Replace spaces with underscore
$thefile['name'] = str_replace(' ', '_', $thefile['name']);
// Replace hyphens with underscore
$thefile['name'] = str_replace('-', '_', $thefile['name']);
// Replace multiple underscores with one underscore
$thefile['name'] = ereg_replace('_+', '_', $thefile['name']);
$path_parts = pathinfo($thefile['name']);
// if php < 5.2
if(!isset($path_parts['filename'])){
$path_parts['filename'] = substr($path_parts['basename'], 0,strpos($path_parts['basename'],'.'));
}
$thefile['name'] = strpos($path_parts['filename'], '.');
$thefile['name'] = substr($path_parts['filename'], 0, 22); // limit file name length to 22 chars from the beginning
$thefile['name'] = $thefile['name'] . "." . strtolower($path_parts['extension']);
// Generate prefix to add to file name
$prefix = rand(99,999);
// Add prefix to file name
$newFileName = $prefix . $thefile['name'];
// SAVE THE PICTURE
$FileName.="|". newImageName($thefile['name']);
$FileFile.="|". $server_dir . $newFileName;
$newFile = $server_dir . $newFileName;
$newFileUrl = $url . $newFileName;
$FileUrl.="|". $url . $newFileName;
$newFileUrlLink = $server_save_directory . $newFileName;
$FileUrlLink.="|". $newFileName;
if (in_array_nocase($file_ext, $valid_file_ext))
{
$lx = 3;
if ($file_ext == "jpeg") {
$lx = 4; }
$tnFileName = substr($newFileName, 0, strlen($newFileName) - $lx) . "jpg";
$tnFileName = str_replace('.', '_tn.', $tnFileName);
$tnFile = $server_dir . $tnFileName;
$FiletnUrl.="|". $url . $tnFileName;
$tnFileUrl = $url . $tnFileName;
}
else
{
$tnFileName = "";
$tnFile = "";
$tnFileUrl = "";
}
$filesize = $thefile['size'];
$newID = "";
if (!#copy($thefile['tmp_name'], $newFile))
{
$messages.="|". "Please check site settings in admin panel and set proper value for server local path.<br><br>Also please make sure the images folder is chmodded to 0777";
}
else
{
// add to database
if($auth_id)
$uid=$auth_id;
else $uid=0;
//ftpupload($host,$user,$pass,$path."/".$dir."/".$newFileName,$newFileUrl);
//ftpupload
if($no_server=="0")
{
$ftp =& new FTP();
if ($ftp->connect($host)) {
if ($ftp->login($user,$pass)) {
$ftp->chdir($path);
$ftp->put($newFileName,$newFile);
}
}
// unlink($newFile);
}
//ftpupload
$date_add=time();
$query = "INSERT INTO images (prv,ftpid,userid,filename, tn_filename, filepath, ip, filesize,added) VALUES ($prv,$ftpid,$uid,'$newFileName', '$tnFileName', '$url', '$uploaderip', $filesize,$date_add)";
mysql_query($query) or die("Database entry failed.");
$newID.="|". mysql_insert_id();
}
if ($file_ext == "jpeg" ||$file_ext == "jpg" || $file_ext == "png" || $file_ext == "gif" || $file_ext == "bmp")
{
if ($file_ext == "jpg")
{
$source_id = imagecreatefromjpeg($newFile);
}
if ($file_ext == "jpeg")
{
$source_id = imagecreatefromjpeg($newFile);
}
elseif ($file_ext == "png")
{
$source_id = imagecreatefrompng($newFile);
}
elseif ($file_ext == "gif")
{
$source_id = imagecreatefromgif($newFile);
}
elseif ($file_ext == "bmp")
{
$source_id = ImageCreateFromBMP($newFile);
}
$true_width = imagesx($source_id);
$true_height = imagesy($source_id);
}
}
}
}
mysql_close($link);
// create URL links to display to user
$showURL1 = false; // image on hosted page - image only
$showURL2 = false; // direct link to file - all
$showURL3 = false; // HTML for img - image only
$showURL4 = false; // [img][/img] tags - image only
$showURL5 = false; // thumbnail pic - image only
// determine flags
$showURL2 = true;
if ($file_ext == "jpg" || $file_ext == "jpeg"|| $file_ext == "gif" || $file_ext == "png" || $file_ext == "bmp") {
$showURL1 = true;
$showURL3 = true;
$showURL4 = true;
}
if ($file_ext == "jpg" || $file_ext == "gif" || $file_ext == "png"|| $file_ext == "jpeg" || $file_ext == "bmp") {
$showURL5 = true;
}
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
else
{
echo "<script language='javascript'>parent.uploaderror('".$msg."');</script>";
exit;
}
function newImageName($fname) {
$timestamp = time();
$new_image_file_ext = substr($fname, strlen($fname) - 3, strlen($fname));
if ($new_image_file_ext == "peg") {
$ext = ".jpg";
} else {
$ext = "." . $new_image_file_ext;
}
$newfilename = randString() . substr($timestamp, strlen(timestamp) - 4, strlen(timestamp)) . $ext;
return $newfilename;
}
function randString() {
$newstring="";
while(strlen($newstring) < 3) {
$randnum = mt_rand(0,61);
if ($randnum < 10) {
$newstring .= chr($randnum + 48);
} elseif ($randnum < 36) {
$newstring .= chr($randnum + 55);
} else {
$newstring .= chr($randnum + 61);
}
}
return $newstring;
}
function in_array_nocase($item, $array) {
$item = &strtoupper($item);
foreach($array as $element) {
if ($item == strtoupper($element)) {
return true;
}
}
return false;
}
?>
And the upload.js script which takes care of producing the uploaded page:
var cp = new cpaint();
cp.set_transfer_mode('get');
cp.set_response_type('xml');
cp.set_debug(1);
function uploaderror(msg)
{
alert(msg);
}
function showfile()
{
var countfld=1;
countfld=document.getElementById("countfld").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("f"+fld).style.display="block";
document.getElementById("countfld").value=countfld;
}
var file=document.getElementById("f"+fld).value;
if(file=="")
{
msg="Please fill this field.";
alert(msg);
document.getElementById("f"+fld).focus();
return false;
}
}
function showfileux()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function showfileu()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
fldx=fld-1;
fldxx=fld.value;
if(fldxx=="")
{
msg="Email Address cannot be left empty.";
alert(msg);
document.getElementById("u"+fldxx).select();
document.getElementById("u"+fldxx).focus();
return false;
}
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function uploadfile(id)
{
if(document.getElementById(id).value==1)
{
document.getElementById("showurl").style.display="none";
document.getElementById("showfl").style.display="block";
return true;
}
if(document.getElementById(id).value==2)
{
document.getElementById("showfl").style.display="none";
document.getElementById("showurl").style.display="block";
return true;
}
document.getElementById("countfldu").value="0";
document.getElementById("countfld").value="0";
}
function show_loading()
{
document.getElementById('loading').style.display = "block";
document.getElementById('newupload').submit;
document.getElementById('submit').disabled = true;
// return true;
}
function show_loading1()
{
document.getElementById('loading1').style.display = "block";
document.getElementById('newupload1').submit;
document.getElementById('submit').disabled = true;
}
function upload(msg,newID,messages,FileName,FileFile,FileUrl,FileUrlLink,FiletnUrl,page_url,server_url,site_name,HotLink)
{
var html='<div id="wrapper"><div style="width:760px;"><center><FONT SIZE="4" COLOR="#00A4B7">Photo Links</FONT></h4><br></center><span class="body"><form name="uploadresults" action="uploademail.php" method="post">';
if(newID)
{
html=html+'<input type="hidden" name="idx[]" value="'+newID+'">';
}
if(msg)
{
var getmsg = msg.split("|");
for(i=0;i<getmsg.length;i++)
{
if(getmsg[i] && getmsg[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmsg[i]+'</span><br>';
}
}
html=html+'<br><center>';
if(messages)
{
var getmessages = messages.split("|");
for(i=0;i<getmessages.length;i++)
{
if(getmessages[i] && getmessages[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmessages[i]+'</span>';
}
html=html+'</center>';
}
if(FileName)
{
var getFileName = FileName.split("|");
var getFileFile = FileFile.split("|");
var getFileUrl = FileUrl.split("|");
var getFileUrlLink = FileUrlLink.split("|");
var getFiletnUrl = FiletnUrl.split("|");
var getHotLink = HotLink.split("|");
for(i=0;i<getFileName.length;i++)
{
if(getFileName[i] && getFileName[i]!="on") {
html=html+'<center><br><img src="'+getFileUrl[i]+'" style="max-width: 550px;"" /><br><br>';
html=html+'<strong>Link to add tags and delete the photo <br><div align="center"><textarea name="url1[]" cols="80" rows="1" READONLY onfocus="javascript: this.select()">'+server_url+'/view2.php?filename='+getFileUrlLink[i]+'
Let me know what you think is causing this error, as this is the final step I need to fix.
I've had similar issue with creating excel files from large data bases. What it boils down to is that the PHP script exceeds the servers set time limit. There are multiple ways to delay/extend this from built in PHP functions, some or all may be used. I personally had use a combination of the ability with AJAX to allow it run in the backgroun and then redirect that page.
Here is the documentation on how to delay/extend it:
http://php.net/manual/en/function.set-time-limit.php
Here is the documentation on how check for a time out as well:
http://php.net/manual/en/function.connection-timeout.php
If you end up going the AJAX route as I did, I highly recommend going the jQuery route instead of vanilla JS.

error handling and image type cat get it to work

I been working on this image script for too long now, and I still can't seem to get two things to work - the image type and error handling (if the fields are empty). I have the code for this, but every place I try to add it, it doesn't work.
my code:
$error_message="";
$MaxSize = "600000";
if (isset($_POST['btn_update'])){
function createRandomPassword() {
$chars = "abcde!##%^fghijkmnoABCDEFGHIJKpqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWZ!##%^&";
srand((double)microtime()*10000000);
$i = 0;
$pass = '' ;
while ($i <= 19) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
if ($_FILES['aMyUploads0']['size'] > $MaxSize || $_FILES['aMyUploads1']['size'] > $MaxSize || $_FILES['aMyUploads2']['size'] > $MaxSize)
{
$error_message = "ERROR: File too big!";
}
$aMyUploads = array();
$password = createRandomPassword();
foreach($_FILES as $aFile)
{
$newLocation = 'uploads/'.$password .$aFile["name"];
if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
{
$aMyUploads[] = $newLocation;
}
else
{
$aMyUploads[] = '';
}
}
$error_message="Journal successfully saved.";
$connection = mysql_connect("localhost", "????", "???");
mysql_select_db("????", $connection);
$insert = "INSERT INTO photos (image1, image2, image3) VALUES
(
' ".$aMyUploads[0]." ',
' ".$aMyUploads[1]." ',
' ".$aMyUploads[2]." '
)";
$add_member = mysql_query($insert) or die(mysql_error());
}
code im trying to add with no luck:
//ERROR HANDLING CODE:
if(empty($aMyUploads[0]) || empty($aMyUploads[1]) || empty($aMyUploads[2]))
{
$error_message="Please fill in all fields.";
}
else
{
$error_message="Journal successfully saved.";
//IMAGE TYPE CODE:
$allowed_filetypes = array(".jpg", ".gif", ".jpeg", ".png");
$ext = substr($newLocation, strpos($newLocation,'.'), strlen($newLocation)-1);
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
Try this for checking required fields, inserted before the code that checks the file sizes.
// ERROR HANDLING CODE:
if (empty($_FILES) || empty($_FILES['aMyUploads0']) || empty($_FILES['aMyUploads1']) || empty($_FILES['aMyUploads2']))
{
// Handle error
}
And this for validating file types, inserted into your foreach.
// IMAGE TYPE CODE:
$allowed_filetypes = array("jpg", "gif", "jpeg", "png");
$ext = pathinfo($aFile['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_filetypes))
{
// Handle error
}

PHP: Image uploader error

Im making an image uploader, but i get the error: Only JPG, JPEG and PNG are allowed image types.
The uploader doesn't get the extension right. What do i do wrong?
The function to get the extension is at line 33. Ad from line 59 is where im trying to get the extension.
<?php session_start(); if ($_SESSION['username']) {} else { header("location:index.php"); exit(); } ?>
<?php
include 'db_connect.php';
$uploadSubmit = mysql_real_escape_string($_POST['imageSubmit']);
if ($uploadSubmit)
{
if ($_FILES['image'])
{
$contents = file_get_contents($_FILES['image']['tmp_name']);
if (stristr($contents, "<?php") || stristr($contents, "system(") || stristr($contents, "exec(") ||
stristr($contents, "mysql") || stristr($contents, "include(") || stristr($contents, "require(") ||
stristr($contents, "include_once(") || stristr($contents, "require_once(") || stristr($contents, "echo'") || stristr($contents, 'echo"'))
{
echo 'Are you really trying to hack this site? Enjoy your upload b&.';
$sql = "INSERT INTO banned (ip) VALUES ('".$_SERVER['REMOTE_ADDR']."')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
die();
}
}
else
{
$sql = "SELECT * FROM banned WHERE ip='".$_SERVER['REMOTE_ADDR']."'";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
$num_rows = mysql_fetch_row($result);
if ($num_rows[0] == 0)
{
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$I = strlen($str) - $i;
$ext = substr($str,$i+1,$I);
return $ext;
}
define ("MAX_SIZE","5000");
$error = 0;
$file = $_FILES['image']['name'];
if ($file = '')
{
echo 'You didn\'t select an image to upload.';
$error = 1;
}
else
{
$filename = stripslashes($file);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}
else
{
$size = filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo 'The max allowed filesize is 5MB.';
$error = 1;
}
$time = time();
$newImageName = 'wally-'.$time.'.'.$extension.'';
$imageFullPath = 'images/'.$newImageName.'';
if (!$errors)
{
if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageFullPath))
{
$error = 1;
}
}
if ($uploadSubmit && !$error)
{
include 'class.imageResizer.php';
$work = new ImgResizer($imageFullPath);
$work -> resize(125, "thumbs/".$newImageName."");
$uploader = $_SESSION['username'];
$sql = "INSERT INTO images (image, uploader, validated) VALUES ('$newImageName','$uploader','0')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
echo 'Your image has been uploaded and awaiting validation.';
echo 'The page will redirect in 2 seconds.';
echo '<meta http-equiv="Refresh" content="2;url=http://www.wallpapers.puffys.net">';
}
}
}
}
else
{
die("You are banned from uploading.");
}
}
}
?>
$i = strrpos($str,".");
if (!$i)
isn't a good way to test if the strrpos function returns a positive value.
You should use the === operator, like this :
$i = strrpos($str,".");
if ($pos === false)
Try using something like this:
$allowedExtensions = array("jpg","jpeg","png");
if (!in_array(end(explode(".",strtolower($file))),$allowedExtensions)) {
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}

Categories