Here is the normal php function which is used in codeigniter which uploads the picture from an android device. I want someone to help to convert into codeigniter function to make it work.
private function uploadImages(){
//get the data from the $_POST and $_FILES
$postKeyPairs = $_POST;
$files = $_FILES['files'];
$titles = "";$description = "";
//fetch the titles
if(array_key_exists('title',$postKeyPairs)){
$titles = $postKeyPairs['title'];
}
//get the description
if(array_key_exists('description',$postKeyPairs)){
$description = $postKeyPairs['description'];
}
//the root file path for the uploaded images
$file_path = "uploads/";
//count the number of files to upload
for($i = 0; $i < count($files['name']); $i++){
//make sure the filename is unique
$filename = basename($files['name'][$i]);
//get the proper filepath for the individual files
$file_path = $file_path.$filename;
//get the title for the current image
if(isset($titles[$i]) && $titles[$i] != null){
$imageTitle = $titles[$i];
}
else{
$imageTitle = "NA";
}
//and get the image description
if(isset($description[$i]) && $description[$i] != null){
$imageDescp = $description[$i];
}
else{
$imageDescp = "NA";
}
//upload the file into the file system
if(!move_uploaded_file($files['tmp_name'][$i], $file_path)){
//any exception occurs
throw new Exception("Couldn't upload image ".$files['name'][$i]);
}
}
return true;
}
Related
My problem is when I select multiple files, it renames all the selected files to the same, but I want to rename each selected files a bit differently and insert into the MySQL and the local folder.
For example
First Selected File Would be:
1_$date_$rand_.png
Second Selected File Would be:
2_$date_$rand_.pnp
And so on...
I also tried with random number but it will rename each selected file to the same as well. I can't figure out how should I do it with loop.
My php code to rename a file and upload into database:
$rand = rand(0, 99999);
$date = date('Y_m_d-H_i_s-a', time());
$count = 0;
$path = "../../images/"; // Upload directory=
$filename = $date."_".$rand.'.';
foreach ($image as $f => $imgname) {
$ext = end((explode(".", $imgname)));
mysqli_query($conn,"INSERT INTO images(name)
VALUES ('$filename$ext')");
if(move_uploaded_file($_FILES["image"]["tmp_name"][$f], "$path/$filename$ext")) {
$count++; // Number of successfully uploaded files
}
}
Use file_exists() and a counter
$rand = rand(0, 99999);
$date = date('Y_m_d-H_i_s-a', time());
$count = 0;
$fileCounter = 0;
$path = "../../images/"; // Upload directory=
$filename = $date."_".$rand.'.';
foreach ($image as $f => $imgname) {
$ext = end((explode(".", $imgname)));
$fileCounter=1;
$fullFilename = "$filename$fileCounter$ext" ;
while(file_exists($path . '/'. $fullFilename)){
$fileCounter ++;
$filename = "$filename$fileCounter$ext" ;
}
mysqli_query($conn,"INSERT INTO images(name) VALUES ('$fullFilename')");
if(move_uploaded_file($_FILES["image"]["tmp_name"][$f],$path . '/'.$fullFilename )) {
$count++; // Number of successfully uploaded files
}
}
I have 2 separate PHP functions to post form data and upload images. I want to combine both functions so I can have data and upload images in the same form.
1.
public function PostStep2()
{
$user = $this->check_profile();
$id = $user['id'];
if ($_POST)
{
$_POST['profile'] = '1';
$this->model->_update('user_details', $_POST, array("id"=>$id));
redirect('ProfileStep3');
}
else
{
err('Something wrong');
}
}
2.
public function PostStep3()
{
$user = $this->check_profile();
$id = $user['id'];
$upload = false;
for ($i=0; $i < 5; $i++)
{
$file_name = md5(date('YmdHms')).basename($_FILES['img']['name'][$i]);
$path = dirname(__FILE__);
$new_path = strrpos($path, "controller");
$new_path = substr($path, 0,$new_path-1);
// $path = $new_path.UPLOAD.'files/'.$file_name;
$path = $new_path.'/resources/uploads/files/'.$file_name;
$fileName = strtolower($_FILES['img']['name'][$i]);
$allowedExts = array('jpg','JPG','jpeg','JPEG','png','PNG');
$extension = explode(".", $fileName);
$extension = end($extension);
if(in_array($extension, $allowedExts))
{
Make a single file that the form will submit to.
<form action='seperatefile.php' method='post'>
Seperatefile.php, paste all of the functions and uploading parameters.
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');
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
I am trying to upload multiple files to the server, while inputting upload information into a database. For some reason only the first or last file is being put into the DB but I can not for the life of me figure out why!
Any help appreciated - thanks!
public function processNewUploads()
{
$language = OW::getLanguage();
$osuploadBOL = OSUPLOAD_BOL_Service::getInstance();
//Loop through each file that was uploaded
for($i=0; $i < count($_FILES['uploads']['tmp_name']); $i++){
/* check if there is a file in the array
for($i=0; $i < count($_FILES['uploads']['tmp_name']); $i++){
if(!is_uploaded_file($_FILES['uploads']['tmp_name'][$i]))
{
OW::getFeedback()->error($language->text('osupload','no_files_selected'));
OW::getApplication()->redirect(OW::getRouter()->urlForRoute('base_index'));
} */
//Check to see if there was an error
if($_FILES['uploads']['error'][$i] > 0){
$error = $_FILES['uploads']['error'][$i];
}else{
$error = 0;
}
//Prepare information to enter into database//
//If the user is logged in then get the userId
if(OW::getUser()->isAuthenticated()) {
$fileOwner = OW::getUser()->getId();
} else {
$fileOwner = 0;
}
//Get the IP of the uploader
$fileOwnerIp = $_SERVER['REMOTE_ADDR'];
//Get the raw file name
$rawFileName = $_FILES['uploads']['name'][$i];
//Get the unique file name
$uniqueFileName = uniqid('',true);
//Get the upload time
$uploadTimeStamp = time();
//Get the file extension
$fileExtension = explode(".", $_FILES['uploads']['name'][$i]);
$n = count($fileExtension) - 1;
$fileExtension = '.'.strtolower($fileExtension[$n]);
//Get the size of the file
$fileSize = $_FILES['uploads']['size'][$i];
//Get the display name of the file
$fileDisplayName = $rawFileName;
//Insert the file information into the database
$sql = 'INSERT INTO ' . OSUPLOAD_BOL_OsuploadDao::getInstance()->getTableName() . " (fileOwner,fileOwnerIp,rawFileName,uniqueFileName,uploadTimeStamp,fileExtension,fileSize,fileDisplayName,error)
VALUES ('$fileOwner','$fileOwnerIp','$rawFileName','$uniqueFileName.$fileExtension','$uploadTimeStamp','$fileExtension','$fileSize','$fileDisplayName','$error')";
OW::getDbo()->Insert($sql);
if(!$error > 0){
//Move the new upload as long as there was not an error with it
$fileToMove = $_FILES['uploads']['tmp_name'][$i];
$osuploadBOL->moveNewUpload($fileToMove,$uniqueFileName,$fileExtension);
continue;
}else{
//If there was an error just go to the next file
continue;
}
}
}
}
HTML:
<input name="uploads[]" id="uploads" type="file" multiple="">
This is just a quick knock-up of yours, there may be errors.
Use a foreach instead I think:
public function processNewUploads()
{
$language = OW::getLanguage();
$osuploadBOL = OSUPLOAD_BOL_Service::getInstance();
//Loop through each file that was uploaded
foreach($_FILES as $key => $file){
$error = $file['error'] ?
/*
if($file['error']){
$error = $file['error'];
}else{
$error = 0;
}
*/
//If the user is logged in then get the userId
if(OW::getUser()->isAuthenticated()) {
$fileOwner = OW::getUser()->getId();
} else {
$fileOwner = 0;
}
//Get the IP of the uploader
$fileOwnerIp = $_SERVER['REMOTE_ADDR'];
//Get the raw file name
$rawFileName = $file['name'];
//Get the unique file name
$uniqueFileName = uniqid('',true);
//Get the upload time
$uploadTimeStamp = time();
//Get the file extension
$fileExtension = explode(".", $file['name']);
$n = count($fileExtension) - 1;
$fileExtension = '.'.strtolower($fileExtension[$n]);
//Get the size of the file
$fileSize = $file['size'];
//Get the display name of the file
$fileDisplayName = $rawFileName;
//Insert the file information into the database
$sql = 'INSERT INTO ' . OSUPLOAD_BOL_OsuploadDao::getInstance()->getTableName() . " (fileOwner,fileOwnerIp,rawFileName,uniqueFileName,uploadTimeStamp,fileExtension,fileSize,fileDisplayName,error)
VALUES ('$fileOwner','$fileOwnerIp','$rawFileName','$uniqueFileName.$fileExtension','$uploadTimeStamp','$fileExtension','$fileSize','$fileDisplayName','$error')";
OW::getDbo()->Insert($sql);
if(!$error > 0){
//Move the new upload as long as there was not an error with it
$fileToMove = $file['tmp_name'];
$osuploadBOL->moveNewUpload($fileToMove,$uniqueFileName,$fileExtension);
continue;
}else{
//If there was an error just go to the next file
continue;
}
}
}