kohana/php parse $_FILES vector - php

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++)
{
//...
}

Related

how can send array in html forms to php

I want to send uploaded files address from html to php with array and then moved the uploaded files to images from tmp and checked their size
<form method="post" enctype="multipart/form-data" name="form1" id="form1" action="upload.php">
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="file" name="Img[]" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
<?php
$name=rand('0123456789',5).'jpg';
$files=array($_POST['Img[]']);
echo '<pre>';
print_r($files);
if($_FILES['$files[0]']['type'] == 'image/pjpeg'){
move_uploaded_file($_FILES[$files[]]['tmp_name'],'image/'.$name);
echo "success";
}
?>
I want to upload files with form
Input file elements never store in the $_POST array. You have to loop through the $_FILES array to get the file elements
if(isset($_POST['submit']))
{
for ($i=0; $i < count($_FILES['Img']['tmp_name']) ; $i++) {
$name=rand('0123456789',5);
if($_FILES['Img']['type'][$i] == 'image/jpeg')
{
move_uploaded_file($_FILES['Img']['tmp_name'][$i],'image/'.$name . '.jpg');
}
echo "success";
}
}
In this solution you can increase the number of input files with the same name as Img
Try this
<?php
if(isset($_POST['submit']))
{
foreach($_FILES['Img'] as $Img) {
$name=rand('0123456789',5);
if($Img['type'] == 'image/jpeg')
{
move_uploaded_file($Img['tmp_name'],'image/'.$name . '.jpg');
}
echo "success";
}
}
?>

FILE INPUT INSERT INTO BD WITH MOVE_TO_FILE

This is more of a question to gain a more clear understanding. If I insert from a form like:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
into the DB for a link and it's successful:
$file = "INSERT INTO ('foo') VALUES ('FOO', NOW())";
just an example:
yet in the php script:
$_FILE['fileToUpload']['name'];
$_FILE['fileToUpload']['tmp_name'];
since the tmp_name folder only holds upload files in an array, which than I would have to use either a foreach or for loop search the loop of files, this than makes the INSERT INTO db difficult.
Question is how can I separate the search results from the array and than insert each one into the database?
HERE"S THE CODE:
<?php
$con = mysqli_connect("localhost","root","","acc1");
if(mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}else{
echo 'Connected!';
}
if(isset($_POST['submit']) && !empty($_FILES['fileBC']['name'] && !empty($_FILES['fileB']['name'] && !empty($_FILES['fileBR']['name']) ))){
$file = "image/";
$name = $_FILES['fileBC']['name'];
$data = $_FILES['fileBC']['tmp_name'];
$fileV = "video/";
$nameV = $_FILES['fileBR']['name'];
$dataV = $_FILES['fileBR']['tmp_name'];
$fileB = "book/";
$nameB = $_FILES['fileB']['name'];
$dataB = $_FILES['fileB']['tmp_name'];
if(move_uploaded_file($data,$file.$name)){
$ins_name = $con->query("INSERT INTO fileimages (fileBC, fileBR, fileB) VALUES ('$name','$nameB', '$nameV')");
}if($ins_name){
echo 'success!';
}else{
echo 'error';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/fontawesome.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<script>
function mymodal(){
$('#myModal').modal('show');
}
</script>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<div class="form-group">
<label class="text-primary">Book Cover:</label>
<input class="form-control" type="file" name="fileBC" accept="image/*" >
</div>
<div class="form-group">
<label class="text-primary">Book:</label>
<input class="form-control" type="file" name="fileB" accept=".epub, .mobi, .pdf, .prc, .azw, .bbeb" >
</div>
<div class="form-group">
<label class="text-primary">Book Reading:</label>
<input class="form-control" type="file" name="fileBR" accept="video/*" >
</div>
<button name="submit">upload</button>
</form>
<p></p>
<ol>
</ol>
</body>
</html>
This is an example you can adept it as per your need.
<form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>
PHP code is like
<?php
if (isset($_POST['submission'] && $_POST['submission'] != null) {
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
//Your insert statement goes here
}
}
}
}
?>

Error when trying to upload multiple files to S3 using 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

Upload multiple files with a php script

I've been modify this php script but it won't work, it always fail. It managed to create the folder, but it fails to move the files from the temporary folder to the right one, the function move_uploaded_file return always false. This is the code:
<?php
include 'connection.php';
include '../empty.html';
session_start();
if(isset($_FILES['filearray'])){
$name_array = $_FILES['filearray']['name'];
$tmp_name_array = $_FILES['filearray']['tmp_name'];
$type_array = $_FILES['filearray']['type'];
$size_array = $_FILES['filearray']['size'];
$error_array = $_FILES['filearray']['error'];
$titlealbum=$_POST['titoloalbum'];
$username=$_SESSION['username'];
$path="../users/".$username."/".$titlealbum."/";
echo $path;
mkdir($path,0777);
$total=count($tmp_name_array);
for($i=0; $i<$total; $i++){
$rightpath=$path.$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $rightpath)){
echo $name_array[$i]." upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]." into".$path."<br>";
}
}
}
else
echo "Files not found";
?>
This is the html form:
<form id="albumform" style="display:none" enctype="multipart/form-data" action="scripts/albumupload.php" multiple="multiple" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name="titoloalbum" type="text" required><br><br>
Cover: <input name="userfile" type="file">
<br><br>Select your songs:<br />
<input name="filearray[]" type="file" value="10000000" /><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input type="submit" value="Send files" />
</form>
I know that this form kinda sucks, but i don't like the multiple selection with a signle "input". Thanks in advice
You have error in your code :
$total=count($tmp_name_array);
change this to
$total=count($name_array);
You are using count function with wrong variable.
Also remove so many file types with same name from the form. Either name them different.
<input name="filearray[]" type="file" value="10000000"/><br />
You could use the following commented algorithm for Multiple-Files upload:
PHP
<?php
// FILENAME: albumupload.php
include 'connection.php';
include '../empty.html';
session_start();
$filesArray = isset( $_FILES['filesArray'] ) ? $_FILES['filesArray'] : null;
$titleAlbum = isset($_POST['titoloalbum']) ? isset($_POST['titoloalbum']) : null;
$arrFilesData = array();
if( $filesArray && !empty($filesArray) ){
$arrFilesKeys = array_keys($filesArray['name']);
$arrFilesNames = $filesArray['name'];
$arrFilesTypes = $filesArray['type'];
$arrFilesTmpNames = $filesArray['tmp_name'];
$arrFilesErrors = $filesArray['error'];
$arrFilesSizes = $filesArray['size'];
foreach($arrFilesKeys as $intKey=>$strKeyName){
$tempFileData = new stdClass();
$tempFileData->key = $strKeyName;
$tempFileData->name = $arrFilesNames[$strKeyName];
$tempFileData->type = $arrFilesTypes[$strKeyName];
$tempFileData->tmp_name = $arrFilesTmpNames[$strKeyName];
$tempFileData->error = $arrFilesErrors[$strKeyName];
$tempFileData->error = $arrFilesSizes[$strKeyName];
$arrFilesData[$strKeyName] = $tempFileData;
}
// UPLOAD THE FILES:
if($titleAlbum){
$username = trim($_SESSION['username']);
$path = __DIR__ . "/../users/" . $username . "/" . $titleAlbum;
//CREATE UPLOAD DIRECTORY IF IT DOESN'T ALREADY EXIST...
if(!file_exists($path)){
mkdir($path, 0777, TRUE);
}
// LOOP THROUGH THE FILES OBJECT ARRAY AND PERFORM FILE-UPLOAD
foreach($arrFilesData as $fileKey=>$objFileData){
$rightPath = $path . DIRECTORY_SEPARATOR . $objFileData->name;
if(move_uploaded_file($objFileData->tmp_name, $rightPath)){
echo $objFileData->name . " upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ". $objFileData->name ." into". $path . "<br>";
}
}
}
}
In this case, your HTML Form is expected to look like this:
HTML
<form id="albumform" style="" enctype="multipart/form-data" action="scripts/albumupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name = "titoloalbum" type="text" required><br><br>
Cover: <input name = "filesArray[userfile]" type="file">
<br><br>Select your songs:<br />
<input name="filesArray[file_1]" type="file" value="" /><br />
<input name="filesArray[file_2]" type="file" value=""/><br />
<input name="filesArray[file_3]" type="file" value=""/><br />
<input name="filesArray[file_4]" type="file" value=""/><br />
<input type="submit" value="Send files" />
</form>

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++)

Categories