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"
Related
I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.
Below is the code I used in order to upload files into a directory. It works fine. My main question is:
I have tried to do so below:
function get_unique_filename($name) {
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date= $date->getTimestamp();
$newname ="bogen_". substr(hash('ripemd160',$date),0,12) .".".$imgExt;
return $newname;
}
function upload(){
$valid_formats = array("jpg", "png");
$max_file_size = 1024*3000;
$path = "../uploads/images/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $name){
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue;
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
// No error found! Move uploaded files
else{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$this->get_unique_filename($name))){
$count++; // Number of successfully uploaded file
// save name to database
$this->name = $newname;
if($this->create()){
// successfully added to databaes
}
}
}
}
}
}
}
when upload Multi files i'll get same filename and files...how can fix it:
You have to check if file exists with same name and if exists then you have to rename the file.
function get_unique_filename($name) {
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date = $date->getTimestamp();
$dir = "../uploads/images/";
$i = 0;
do {
$newname ="bogen_". substr(hash('ripemd160',$date),0,12);
$image_name = $newname . ($i > 0 ? "_($i)" : "") . "." . $imgExt;
$i++;
$path = $dir . $image_name;
} while(file_exists($path));
return $newname;
}
in get_unique_filename($name)
+add : sleep(1);
function get_unique_filename($name) {
sleep(1);
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date= $date->getTimestamp();
$newname ="bogen_". substr(hash('ripemd160',$date),0,12) .".".$imgExt;
return $newname;
}
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?
I added multiple file upload on my website, but I noticed, that uploaded files eat much RAM on the server and it does not decrease for 1-2 days. I think the reason is incorrect PHP code... I tried to unset all variables but it didn't help. That's my code:
<?php
if(isset($_POST['upload'])){
if(count($_FILES['files']['name']) > 0){
for($i=0; $i<count($_FILES['files']['name']); $i++) {
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
if($tmpFilePath != ""){
$max_filesize = 10000288;
if(filesize($_FILES['files']['tmp_name'][$i]) > $max_filesize)
die('File is too large.');
if($_FILES['files']['type'][$i] != "image/jpeg" AND $_FILES['files']['type'][$i] != "image/png")
die('This is not available format.');
$shortname = $_FILES['files']['name'][$i];
$filePath = "img/uploaded_images/full/" .date('d-m-Y-H-i-s').'-'.$_FILES['files']['name'][$i];
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
$tmpFilePath = NULL;
$allowed_filetypes = NULL;
$max_filesize = NULL;
$filePath = NULL;
$_FILES['files']['name'][$i] = NULL;
$shortname = NULL;
$_FILES['files']['tmp_name'][$i] = NULL;
unset( $tmpFilePath);
unset($allowed_filetypes);
unset($max_filesize);
unset($filePath);
unlink($_FILES['files']['name'][$i]);
unset($_FILES['files']['name'][$i]);
unset($shortname);
unset($_FILES['files']['tmp_name'][$i]);
}
}
}
$_FILES = NULL;
unset($_FILES);
}
} ?>
This is my code:
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
}
My problem is that in this way, Images are uploaded in a random way.
But I need that images are uploaded in the order I select them. Any tips? Thank you