Uploading multiple files via PHP and posting information to MYSQL database - php

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

Related

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.
Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content.
Is this a PHP bug ?
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
public function criarLista($nome,$file){
// ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT
if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
move_uploaded_file($file, "uploads/lista.txt");
$file = file_get_contents("uploads/lista.txt");
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file("uploads/lista.txt");
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
echo $Linha."</br>";
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
FIXED this adding this on top of the function :
ini_set('auto_detect_line_endings',true);
I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.
What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.
Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).
Hope this helps!
$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file; // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";
$alert_upload_successful = "UPLOAD SUCCESSFUL";
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false'))
die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
// I found this mac to be sending a .zip file, not a standard one..... :(
$uploadOk = 0;
$mac_file = 0;
if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
{
$zip = new ZipArchive;
if($zip->open($zipfile) === true){
// echo "basename is $basename<BR>";
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
// look for the file we really want (in our case, any sort of img file)
if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg' || $fileinfo['basename'] == $basename . '.gif') {
$imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
$files[]=$fileinfo['basename'];
// echo "file added to the list <BR>";
}
// echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
// CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE
if($fileinfo['basename'] == "__MACOSX")
$mac_file = 1;
// echo "mac_file is $mac_file ";
}
if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
{
// echo "imglist = ";print_r($imglist);
// echo "files = ";print_r($files);
foreach($files as $key => $value)
{
if ($imglist[0]==$value) {$file = $imgfile;}
$upgrade += file_exists('maps/'.$file);
// echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
// more 'FUNNY BUSINESS' to work the Mac file....
if($mac_file){
$extracted = $zip->extractTo('maps/',$basename."/".$value);
rename("maps/$basename/$value","maps/$file");
}
else {
$extracted = $zip->extractTo('maps/',$value);
rename("maps/$value","maps/$file");
}
}
// AND A BIT MORE.....
if($mac_file){
rmdir ("maps/$basename");
}
$zip->close();
$imgcount=0;$mapcount=0;$uploadOk=1;
$html = file_get_html('maps/'.$mapfile);
$imgck = strpos($html,'<img ');
if(($imgck===false) || $imgck<>0) {
$uploadOk += 2;
}
// echo "uploadOk is $uploadOk<br>";
if($uploadOk==1)
{
$mapname = pathinfo('maps/'.$mapfile);
// echo "mapfile is $mapfile, mapname = ";print_r($mapname);
}
}
else $uploadOk += 20;
}
}
if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
else echo $action_failed_text . " ".$uploadOk;
// delete the original .zip file (and any that are in the 'maps/' folder)
array_map('unlink', glob("maps/*.zip"));
}
else
{
echo "Sorry, there was an error uploading your file.";
echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

PHP/MySQL - Data entered twice when doing single upload

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

Updating table images using for loop

hi i am trying to update images using for loop as i used while inserting them. but it is just updating one values on all records. please
<?php session_start();
require_once("SubmitController/sale_property_controller.php");
$objproperty = new sale_property_controller();
if (count($_FILES['upload']['name']) > 0) {
//Loop through each file
for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = date('d-m-Y-H-i-s') . '-' . $_FILES['upload']['name'][$i];
//save the url and the file
$filePath = "../img/saleproperty/" . $shortname;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $filePath)) {
$_SESSION['Property_images'][] = $shortname;
}
}
}
}
if(!$_SESSION['Property_images']){}else{
foreach ($_SESSION['Property_images'] as $items => &$item ) {
$property_id=$_GET['id'];
$objproperty->Updateproimg($property_id, $item);
}
}
?>
this is my function
function Updateproimg($property_id, $item)
{
$sql="update images_property set images='".$item."' where property_id='".$property_id."' ";
$this->update($sql);
}
I feel you have to take count on count($_FILES['upload']) instead of $_FILES['upload']['name'];
$count = count($_FILES['upload'])
for($i=0; $i<=$count; $i++) {
$tmpFilePath = $_FILES['upload'][$i]['tmp_name'];
}
Are you trying multiple file upload?

Stripping Filename in PHP

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

How to I convert normal php function into codeigniter function

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

Categories