jQuery/PHP File Upload Times Out Before Loading Next Page - php

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.

Related

AWS S3 PhPdolphin integration

So my goal was it to implement Amazon S3 image uploads to the PhPDolphin script, unfortunately I've run into a few Issues, if I add the code in the script just doesn't load and since the script doesn't have an error log I'm clueless as to what went wrong, for licensing reasons I'm unable to publish the entire script here but I will post a snipped of the affected area.
/includes/classes.php [Default (Just a small snippet of the 4000 lines of code within this file)]
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
move_uploaded_file($tmp_value[$key], '../uploads/media/'.$finalName);
}
}
// Implode the values
$value = implode(',', $value);
}
And then my edited version that is supposed to upload the images automatically to Amazon S3.
/includes/classes.php [edited] (the s3 code is on the far bottom of the snippet)
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
if (!class_exists('S3'))require_once('S3.php');
//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'myaccesskey');
if (!defined('awsSecretKey')) define('awsSecretKey', 'mysecretkey');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
S3::outObject(
'$tmp_value[$key]',
'zepstrca',
'.$finalName);',
S3::ACL_PUBLIC_READ
array(),
array(),
S3::STORAGE_CLASS_STANDARD
);
}
// Implode the values
$value = implode(',', $value);
}
And yes I did add my own access and secret key :)
Any help would be greatly appreciated and will be credited!
Links to the products and API used in this:
[PhPDolphin] [S3.php API on Github]
This is how you can use the library i am using, i hope it will fix your problems (make sure the folder on the bucket actually exists otherwise just upload something to the root of the bucket)
require_once 'S3.php';
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putObjectFile('/folderOnServer/picture.jpg', awsBucket, '/folderOnBucket/newName.jpg');

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
}

how can I add imaging handling got this script effectively

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
}

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;
}

loop for multi-image upload to sql DB

I've edited this code to go from 1 image upload to 2, but it's ugly--basically just duplicated the previous variables. I want to get up to 8 images, and imagine there's a way to create an array and put it through a loop instead of making an individual instance for each image.
Thanks for any insight..
This is my code so far:
<?PHP
include("inc/header.php");
$back = "<a href='sell.php'>Click Here To Go Back And Try Again</a>";
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0 || $_FILES['userfile2']['size'] > 0 )
{
$title = $_POST['title'];
$description = $_POST['description'];
$category = $_POST['category'];
$price = $_POST['price'];
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$password = $_POST['password'];
// PICTURE UPLOAD SYSTEM
$imagename = basename($_FILES['userfile']['name']);
$imagename2 = basename($_FILES['userfile2']['name']);
if(empty($imagename) || empty($imagename2)) {
$error = 1;
echo"<h2 class='error'>The name of the image was not found.</h2>".$back;
}
if($error != 1 && $noimg != 1)
{
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
$filename2 = stripslashes($_FILES['userfile2']['name']);
$extension2 = substr(strrchr($filename2, '.'), 1);
$extension2 = strtolower($extension2);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
}
if (($extension != "jpg") && ($extension2 != "jpg") && ($extension != "jpeg") && ($extension != "jpeg") && ($extension != "png") && ($extension2 != "png") && ($extension != "gif") && ($extension2 != "gif"))
{
//print error message
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>'.$back.'';
$errors=1;
}
else
{
$time = time();
$newimage = "photos/" . $time . $imagename;
$newimage2 = "photos/" . $time . $imagename2;
$result = #move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
$result2 = #move_uploaded_file($_FILES['userfile2']['tmp_name'], $newimage2);
if(empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error moving the uploaded file.</h2><br/>".$back."";
}
// insert to SQL
$date = date("Y-m-d G:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, price, name, number, email, password, picture, picture2, date, views, authorized ) VALUES ('', '$title', '$description', '$category', '$price', '$name', '$number', '$email', '$password', '$newimage', '$newimage2', '$date', '0', '0')";
mysql_query($query) or die(mysql_error());
}
If you force the inputs into an array by using
<input type='file' name='file[]' />
<input type='file' name='file[]' />
<input type='file' name='file[]' />
then use the following function I found from file-upload.multiple.php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
You will be able to loop through the array very easily, hardly noticing you dealing with multiple files.
if (isset ($_POST['upload'])) {
extract ($_POST, EXTR_PREFIX_ALL, 'post');
$file_ary = reArrayFiles ($_FILES['file']);
$error = 0;
foreach ($file_ary as $file) {
// Test a file is uploaded for each input
if ($file['size'] == 0 || empty ($file['name'])) {
$error = 1;
break;
// Note: If not all input slots are required to be filled,
// replace the above with:
// continue;
// This will stop running this step of the loop here
// and start the next one.
}
// Test file format
if (!in_array ($file['type'], array (
'image/jpg', 'image/png',
'image/jpeg', 'image/gif')) {
$error = 2;
break;
}
}
if (!$error) { // True is returned if value is not 0;
$newpath = 'photos/'.time();
foreach ($file_ary as $file) {
$res = #move_uploaded_file($file['tmp_name'],
$newpath.'-'.$file['name']);
unlink ($file['tmp_name']);
if (!$res) {
$error = 3;
break;
}
}
}
if (!$error) {
$res = mysql_query(' ... insert query ... ');
if (!$res) {
$error = 4;
}
}
if ($error) {
// If you wanted to be super thorough, you could loop through
// and make sure that if any files did get moved that they
// were deleted.
$msg = "";
switch ($error) {
case 1: $msg = 'File not found.'; break;
case 2: $msg = 'Incorrect file format.'; break;
case 3: $msg = 'Error moving uploaded file.'; break;
case 4: $msg = 'Database query failed. '.mysql_error(); break;
default: $msg = 'Error';
}
echo "<h2 class='error'>$msg</h2><a href='sell.php'>Try Again.</a>";
}
}
check out: http://www.php.net/manual/en/features.file-upload.multiple.php
One hard-coded way I've done it in the past is:
<input type="file" name="file_1" />
<input type="file" name="file_2" />
<input type="file" name="file_3" />
and then when submitted:
foreach($_FILES as $file) {
// file actions
}

Categories