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');
Related
I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}
I'm building a version control system in PHP. I almost have a fully working system and am currently adding features. My code below renames a file as "filename_Ver 0.01" and increments by .01 if the user selects a minor revision from the html selectbox. If it's a major revision, the file gets renamed as filename_Ver 1 and increments by 1 for each major version. If I combine both, let's say a major and a minor revision I end up with a file named "filename_Ver 1.01.ext"
Displaying the filename in a PHP table is easy enough but I'd like to optionally just display the version number say in a seperate table field called "Version". How would I strip that from the filename so I can add that to the database? I know I'd have to do something within the while loop to get what I want out. $file = $dr.$fName.'_'.'Ver '.$i.$ext; I want it to display something like the following:
FileName | Version
test_Ver 0.1 | 0.1
test_Ver 0.2 | 0.2
test_Ver 1 | 1
test_Ver 1.1 | 1.1
function update_file_name_major($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
}
function get_file_name_major_latest($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file)){
$exist = TRUE;
return $i;
}
$i++;
}
return 0;
}
function update_file_name_minor($file, $latest_major = 0)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = str_replace(end(explode("/",$file)), '', $file);
$arr = explode('/',$file);
$fName = current(explode(".",end(explode("/",$file))));
$exist = FALSE;
$i = (float) $latest_major. '.01';
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i += 0.01;
}
return $file;
}
if ( isset( $_POST['addfile'] ) ) {
// variables
define('UPLOAD_DIR', 'repository/');
$fileName = $_FILES['file'];
$file_type = $_FILES['file']['type'];
$projectname=$_POST['projectname'];
$comments=$_POST['comments'];
if($_POST['rev_type'] == 'Minor') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$latest_major = 0;
if(update_file_name_major(UPLOAD_DIR.$fileName['name']) != UPLOAD_DIR.$fileName['name']){
$latest_major = get_file_name_major_latest(UPLOAD_DIR.$fileName['name']);
--$latest_major;
}
$updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name'], $latest_major);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_minor($fileName['name'], $latest_major);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a minor revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
elseif($_POST['rev_type'] == 'Major') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_major($fileName['name']);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a major revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
} //main if
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>
I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>
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
}