Error when trying to upload multiple files to S3 using PHP - php

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

Related

php - naming Multiple file input fields on a form

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

Create a PHP contact form with multiple image upload

I need to create an html contact form which collects some data and uploads 8 images through a PHP script
This is my HTML:
<form action="formmail.php" onsubmit="return controlloform()" id="form" name="form" method="POST" enctype="multipart/form-data">
<input name="email" id="email" placeholder="Email address" type="text" value="" maxlength="40">
<input name="tel" id="tel" type="text" placeholder="Order number" value="" maxlength="20">
<textarea name="msg" placeholder="Message" value="" maxlength="300"></textarea>
Upload a photo:
<p>
<p>
<input name="file" id="file" class="button" type="file" value="">
<p>
<p>
<td colspan="2">
<input type="submit" class="button" value="Submit" />
</td>
</tr>
</table>
</form>
I don't know how to create the upload script, what I need to do is uploading 2 blocks of 4 images, check the extension of the file (only jpg and png allowed) and the size (max 500 kb for image).
I've already found some upload scripts (not 100% suitable for what I need) but I don't know how to include the upload part into the rest of the code
If anyone could help me would be great
Thanks a lot
This code make multiple upload
$total = count($_FILES['photo_file']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['photo_file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['photo_file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
if you want to check file size insert this code
if ($_FILES["photo_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
this code make validation
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['photo_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$uploadOk = 0;
}

Issues with Php Music File Uploader

So I'm trying to upload music files with php but the files aren't going to the folder, here's my code what are my mistakes and what am i missing
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="text" placeholder="File Name" name="file_name">
<input type="text" placeholder="Artist Name" name="artist_name">
<textarea rows="5" placeholder="Description" name="description"></textarea>
<input type="submit" class="btn btn-warning bgcolor" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit'])){
function GetMusicExtension($musictype)
{
if(empty($musictype)) return false;
switch($musictype){
case 'audio/mp3': return '.mp3';
default: return false;
}
}
if (!empty($_FILES["file"]["name"])) {
$file_name=$_FILES["file"]["name"];
$temp_name=$_FILES["file"]["tmp_name"];
$music_type=$_FILES["file"]["type"];
$size = $_FILES['file']['size'];
$ext= GetMusicExtension($music_type);
$musicname = $_POST['file_name'].$ext;
$target_path = "music/".$musicname;
if(move_uploaded_file($temp_name, $target_path)) {
$query = "insert into music(name,artist,description)
values('".$musicname."','".$_POST['artist_name']."','".$_POST['description']."')";
mysqli_query($link,$query) or die("error in $query == ----> ".mysqli_error($link));
}
}else{
exit('<script>alert("Error Saving Data... try again");</script>');
}
}
?>
PS: If i change the mime to an image mime and try uploading it uploads
UPDATE:
If i change post_max_size and upload_max_size it works. Thanks all.

Upload multiple images to a folder with each input having a different name

I am trying to upload multiple images to a folder using PHP using this tutorial I managed:
In the PHP form
<?php
$success = 0;
$fail = 0;
$uploaddir = 'uploads/';
for ($i=0;$i<4;$i++)
{
if($_FILES['userfile']['name'][$i])
{
$uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext))
{
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
$success++;
}
else
{
echo "Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}
else
{
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
?>
In the HTML form
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
Image4: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
As you can see in the HTML form the input name is userfile[] for all of them. Now in my HTML for the input names are as follows: picture01, picture02, picture 03, etc...
How can I modify the PHP code to have my input names {: picture01, picture02, picture 03} rather than userfile[].
Thanks.
UPDATE
I want the above to fit in my HTML Form
<form enctype="multipart/form-data" action="upload.php" method="post">
Picture 01<input id="picture01" name="picture01" type="file" ><br />
Picture 02<input id="picture02" name="picture02" type="file" ><br />
Picture 03<input id="picture03" name="picture03" type="file" ><br />
Picture 04<input id="picture04" name="picture04" type="file" ><br />
<input type="submit" value="Upload" />
</form>
This code is working locally. It uses a combination of your code and the example from php.net. You should probably use pathinfo to get the extension but that's a minor detail.
form.html
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
Image4: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>
upload.php:
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
$success = 0;
$fail = 0;
$uploads_dir = 'uploads';
$count = 1;
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
$uploadfile = "$uploads_dir/$name";
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpg|gif|png|bmp)/",$ext)){
$newfile = "$uploads_dir/picture".str_pad($count++,2,'0',STR_PAD_LEFT).".".$ext;
if(move_uploaded_file($tmp_name, $newfile)){
$success++;
}else{
echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}else{
echo "Invalid Extension.\n";
$fail++;
}
}
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
When you have change the names in the form, change the name when you try to get an array element of the file
ex.
echo $_FILES["picture$i"]['name'];
and change the for as this
for ($i=1;$i<=4;$i++)

kohana/php parse $_FILES vector

i want to parse a $_files vector in order to make a multiple upload.
i try like this:
for($i=0; $i < count($_FILES['product_image']);$i++){PRINT_R($_FILES['product_image'][$i]);
but it gives me the error: Undefined offset: 0 in /Users.... etc then the same for 1, 3, etc.
in the form i have: three fields:
<input id="product_image" type="file" name="product_image[]" >
<input id="product_image" type="file" name="product_image[]" >
<input id="product_image" type="file" name="product_image[]" >
i wonder where am i wrong? wht can't i parse the $_files vector?
Did you try using a foreach loop ?
See Example 3 for file upload on PHP site:
<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
EDIT:
Maybe your first loop could work like this:
$files_count = count($_FILES['product_image']['error']);
for($i = 0; $i < $files_count; $i++)
{
//...
}

Categories