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?
Related
I want to insert multiple file names into $NewFileNames array and then pass the complete array only once and with all filenames assigned to it, so I tried at first looping in this way using an increment variable
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
so, this code is not working in the right way because it inserts each file name to the array $NewFileNames and then calls the js script function start in line 39 several times
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
but this is not what I'm trying to accomplish in this project I want the array to carry all the file names and call the javascript function start($Files) only once so, obviously the problem is with the first for loop so I thought using foreach will be easier and match what i want to do
so this is what i tried :
<?php
require "prepare.php";
$allowUpload = true;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
$maxfilesize = 80000000;
if (isset($_FILES['uploadedFile'])) {
$myFile = $_FILES['uploadedFile'];
$fileCount = count($myFile["name"]);
// for ($i = 0; $i < $fileCount; $i++) {
foreach($_FILES['uploadedFile'] as $file) {
$tmpFilePath = $file['tmp_name'];
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "uploads/" . $file['name'];
$NewFileNames = array();
array_push($NewFileNames,$newFilePath);
$imageFileType = pathinfo($newFilePath,PATHINFO_EXTENSION);
if (file_exists($newFilePath))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($file["size"] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload){
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
if (!empty($NewFileNames)){
$Files = json_encode($NewFileNames);
echo '<script>start('.$Files.');</script>';
}
}
}
}
}
}
?>
and this code is given this error
Warning: Undefined array key "tmp_name"
I have a html form + php for uploading 3 pdfs similarly. while uploading i have to cut the names of the files. For instance instead of AB_2020_02_02.pdf i want to have it changed in AB.pdf - for all three files simultaneously. I tried with rename($original_filename, substr($original_filename, 2) . '.pdf'); Any other ideas?
This is the entire code:
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
rename($original_filename, substr($original_filename, 2) . '.pdf');
$target = $target_dir . basename($original_filename);
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
$target_dir = '';
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$rename = explode('_',$original_filename);
$target = $target_dir . $rename[0].".pdf";
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
Rename directly in move_uploaded_file(...)
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$target = $target_dir . substr($original_filename, 2).'.pdf' ;
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
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 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;
}
}
}
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;
}