I have a Problem with Insert in Database. It Insert only the first Uploaded Image :/ Here is my PHP Code:
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
$file_ary = reArrayFiles($_FILES['files']);
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
foreach($file_ary as $key => $file){
static $i = 1;
if($file['error'] == 4){
continue;
}elseif(!in_array(exif_imagetype($file['tmp_name']), $allowedTypes)){
$error = '<span style="color:red">Filename '.$file['name'].' <b>type</b> is not allowed.</span><br>';
}elseif($file['size'] > 2097152){
$error = '<span style="color:red">Filename '.$file['name'].' exceeds maximum allowed <b>size</b></span>.<br>';
}else{
$getfilename= $file["name"];
$FileName="U[$user->id].$getfilename";
$time = time();
$output_dir = "uploads/";
if(!file_exists("uploads/".$FileName)){
move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
}else{
$FileName="$time.$getfilename";
move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
}
mysql_query("INSERT INTO ads_pictures (path, filename, timestamp) VALUES('".$output_dir."', '".$FileName."', '".$time."')");
}
$i++;
}
And this is the HTML Code:
<form method="post" enctype="multipart/form-data" action="">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input id="image" type="file" name="files[]" accept="image/*">
<input name="submit" class="btn submit" value="Upload" type="submit">
</form>
It Should normally Insert all Uploaded Files to Database but Unfortanetly it insert only the First selected file. Thank you for Help.
Have you considered replacing this:
foreach($file_ary as $key => $file){
static $i = 1;
with this:
$i = 1;
foreach($file_ary as $key => $file){
?
let us know if that helped.
Related
I am doing a form with multiple files upload, for each file input there is a title input and I want to match the title with the file in order to be able to rename the file with the title.
I don't know how to match indexes of the two arrays to be able to do this.
Could someone help me? Thx
Here is my code so far ...
PHP :
$target_dir = 'files/';
if(isset($_POST['title']) && !empty($_POST['title'])){
$total_titles = count($_POST['title']);
for($key = 0; $key < $total_titles; $key++) {
// Clean retrieved client data
$pageName= $_POST['titles'];
}
// Check files
if(isset($_FILES['userfile']['name'])) {
// Count the number of uploaded files
$total_files = count($_FILES['userfile']['name']);
// Loop on uploaded files
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['userfile']['name'][$key]) && $_FILES['userfile']['size'][$key] > 0) {
$original_filename = $_FILES['userfile']['name'][$key];
// Get the file extension
$extension = pathinfo($original_filename, PATHINFO_EXTENSION);
// Get filename without extension
$filename_without_extension = basename($original_filename, '.'.$extension);
// Generate new filename
$new_filename = str_replace(' ', '_', $filename_without_extension) . '_' . '.' . $extension;
// Upload the file with new name
move_uploaded_file($_FILES['userfile']['tmp_name'][$key], $target_dir . $new_filename);
}
}
}
}
HTML
<div class="container">
<div class="row justify-content-center">
<!-- Page names -->
<form class="form col-xl-6" action="" id="page_list_section" method="post" enctype="multipart/form-data">
<input type="text" name="title[]" placeholder="Title" >
<input type="file" name="userfile[]" >
<input type="text" name="title[]" placeholder="Title" >
<input type="file" name="userfile[]" >
<input type="submit" name="Submit" value="Upload" >
</form>
</div>
</div>
Here is the match:
for($key = 0; $key < $total_files; $key++) {
$title = $_POST['title'][$key];
$filename = $_FILES['userfile']['name'][$key];
}
I am working on a project to be able to upload files to an Amazon S3 bucket from a website using PHP.
However, I am hitting an issue where it comes with the following error:
fopen(uploadDoc/1.jpg): failed to open stream: No such file or
directory
I am looping through the multiple files to upload them individually like so:
if (isset($_FILES['files']))
{
for ($i = 0; $i < 10; $i++)
{
if (!empty($_FILES['files']['name'][$i]))
{
$name = $_FILES['files']['name'][$i];
$tmp_name = $_FILES['files']['tmp_name'][$i];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if ($ext == 'zip') { $temp_file_path = "uploadZip/{$name}"; $s3Key = "zip"; }
else { $temp_file_path = "uploadDoc/{$name}"; $s3Key = "docs"; }
try
{
$body = fopen($temp_file_path, 'rb');
$s3->putObject([
'Bucket' => AWS_BUCKET,
'Key' => "{$s3Key}/{$name}",
'Body' => $body,
'ACL' => "public-read"
]);
}
catch (S3Exception $e)
{
die('There was an error uploading ' . $e->getMessage());
}
fclose($body);
unlink($temp_file_path);
}
}
}
When I have tried to upload a single file using the same code but not in a loop, it works fine, so I am really confused.
Below is the form being used to upload the files:
<form action="" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input id="file" type="file" name="files[]"><br>
<input name="upload" type="submit" value="Upload" class="general-btn blue">
</form>
Any help will be greatly appreciated
I have discovered that I have made some errors in my code.
Firstly, I have missed one line of code from within the PHP code snippet provided above, this is:
if ($ext == 'zip') { $temp_file_path = "uploadZip/{$tmp_file_name}"; $s3Key = "zip"; }
else { $temp_file_path = "uploadDoc/{$tmp_file_name}"; $s3Key = "docs"; }
move_uploaded_file($tmp_name, $temp_file_path);
try
The second error made was within the HTML code snippet above, which was giving all the inputs the same file ID, by changing the IDs to have a different ID the files upload successfully with no errors
Thanks
I am wanting to have multiple fields on one form that can insert files.
I have the below script, but I want to be able to identify what field the inserted file belongs to in the saved name.
<form action="" method="post" enctype='multipart/form-data' id="form" name="form">
Input 1<input type="file" name="upload[]" >
Input 2<input type="file" name="upload[]" >
Input 3<input type="file" name="upload[]" >
<button id="submit-button">Upload</button>
</form>
<?php
//if(isset($_POST['submit']) && !empty($_POST) ){
$count = 0;
$max_file_size = 5000000;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['upload']['name'] as $f => $name) {
$path = 'documents'; //path of directory
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['upload']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
else {
// No error found! Move uploaded files
//$name_of_file = $_FILES['username']['name'][$f];
$temp_name = $_FILES['upload']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}
At the moment it just saves the files into the one location, so I cant differentiate them and identify which field they are from.
can anyone please help?
I have worked it out. I have taken the comments above and placed an Text input field at each of the File Fields. These could also be hidden fields if you need set names.
Then I scroll through them and save the names and apply those names on the server side.
Thanks to the comments, they helped me see the solution.
<form action="" method="post" enctype='multipart/form-data' id="form" name="form">
<input type="text" name="input0" value=""><input type="file" name="upload[]" ><br><br>
<input type="text" name="input1" value=""><input type="file" name="upload[]" ><br><br>
<input type="text" name="input2" value=""><input type="file" name="upload[]" ><br><br>
<button id="submit-button">Upload</button>
</form>
<?php
$count = 0;
$max_file_size = 500000000000;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
$x = 0;
$input = "input";
while ($x <= 2){
$field_name = $input.$x;
$field[$x] = $_POST[$field_name];
$x++;
}
foreach ($_FILES['upload']['name'] as $f => $name) {
$path = 'documents'; //path of directory
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['upload']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
else {
$temp_name = $_FILES['upload']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$field[$count]"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}
I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs
I have the following code which works and uploads but it will not cycle through the array to upload every file, just the first file.
<form method="post" enctype="multipart/form-data" action="http://<?php echo $pageURL;?>">
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input type="submit" class="button" name="addMaterials" value="Add" />
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>
I need it to cycle through my documents[] file array.
Example print_r() of the documents array:
Array (
[name] => Array ( [0] => AcroRd32.exe )
[type] => Array ( [0] => application/x-msdownload )
[tmp_name] => Array ( [0] => C:\xampp\tmp\phpE8BD.tmp )
[error] => Array ( [0] => 0 )
[size] => Array ( [0] => 1343112 )
)
Any help appreciated.
you can use my updated code and as per my demo it is working perfect for multiple file upload
<?php
if(isset($_FILES['documents'])){
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"galleries/".time().$file_name);
}
}else{
echo "<form enctype='multipart/form-data' action='test1.php' method='POST'>";
echo "File:<input name='documents[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>
For anyone trying to do it with a single file php function (i`m using classes, but you can change to a function):
html:
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
php:
if (isset($_FILES['foto'])) {
$arquivo = array();
foreach ($_FILES['foto']["name"] as $file=>$key) {
// the empty input files create an array index too, so we need to
// check if the name exits. It means the file exists.
if (!empty($_FILES['foto']["name"][$file])) {
$arquivo ["name"] = $_FILES['foto']["name"][$file];
$arquivo ["type"] = $_FILES['foto']["type"][$file];
$arquivo ["tmp_name"] = $_FILES['foto']["tmp_name"][$file];
$arquivo ["error"] = $_FILES['foto']["error"][$file];
$arquivo ["size"] = $_FILES['foto']["size"][$file];
$foto = new foto(); // create an obj foto
// $arquivo means file, it`s our file format as a single $_file['file']
if ($foto -> upload($arquivo)) { // if its uploaded than save
$foto -> save();
}
}
}
}
on my foto class:
public function upload($foto) {
$upload_dir = "D:/xampp/htdocs/prova/fotos/";
$file_dir = $upload_dir . $foto["name"];
$move = move_uploaded_file($foto["tmp_name"], $file_dir);
$this -> arquivo = $foto["name"]; // use this to save to db later
// this serves to return true if the file is uploaded
$retorno = ($move) ? 1 : 0;
return $retorno;
}
Try with this code for multifile upload
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
In PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
To show the file name using javascript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
it's easy to upload multiple files, follow these steps.
use array notation means square brackets with the name of the input like this
<input type="file" id="indtbl_logo[]" name="indtbl_logo[]" multiple />
you can loop throught this using $_FILES Global Variable
foreach ($_FILES['indtbl_logo']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['indtbl_logo']['name'][$key];
$file_size = $_FILES['indtbl_logo']['size'][$key];
$file_tmp = $_FILES['indtbl_logo']['tmp_name'][$key];
$file_type = $_FILES['indtbl_logo']['type'][$key];
echo $file_name;
echo "<br>";
}
Try this way of loop your documents array()
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmpName) {
$file_name = $_FILES['documents']['name'][$key];
$file_type = $_FILES['documents']['type'][$key];
$file_size = $_FILES['documents']['size'][$key];
$file_tmp = $_FILES['documents']['tmp_name'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>
File upload using multiple input fields.
HTML
<form action="" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
PHP
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
?>