php count variable outside loop being reset - php

I've set $count as counter outside foreach loop, but it seemed to be reset everytime. This php is used to upload multiple files.
$count = 0;
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
echo "<script>alert(".$count.");</script>"; to observe the counter , and if upload three files it will alert '1' three times. Also, I added $count to upload filename, for example , filename 1.jpg,2.jpg , after uploading ,the filename will become 1.jpg1, 2.jpg1, it supposed to be 1.jpg1,2.jpg2. what is wrong with my loop?
html code:
<form method="post" action="ImagesUpload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
</form>

Are you using AJAX to upload?
I added a submit button to your code and it worked.
Also, are you sure you are selecting more than one file?
See modified code:
HTML
<form method="post" action="upload.php" id="myForm1" enctype="multipart/form-data">
<input name="my_file[]" id="file-fr" type="file" class="file" data-preview-file-type="text" multiple>
<input type="submit" >
</form>
PHP
$count = 0;
if(isset($_FILES["my_file"])){
print_r($_FILES["my_file"]);
foreach ($_FILES["my_file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$count++;
echo "<script>alert(".$count.");</script>";
$tmp_name = $_FILES["my_file"]["tmp_name"][$key];
$name = basename($_FILES["my_file"]["name"][$key]);
move_uploaded_file($tmp_name, "upload/". $SN."/".$name .$count);
echo json_encode(array('id' => 'message', 'data' => 'successful'));
}
}
}
Both blocks of code are in the same file.

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

How to upload an array of files?

I'm trying to build an array of files by submitting a form several times, then move those files to a directory, but it's not working. Every uploads just overrides the previous and then it doesn't even move that one (the upload_to_file() function doesn't do anything)
HTML:
<form id="form" action="home.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="8000000">
<input class="upload_btn" type="file" name="images[]" id="image_file">
<input type="submit" id="img_submit" class="form_button" name="submit_image" value="upload"/>
</form>
It is important that there is only one upload button which can be used to upload many files.
I need them to be stored in an array so I can display their ['name'] anywhere with a loop.for ($i = 0; $i < count($_FILES['images']['name']); $i++){}
Then once another form is submitted it calls a function to move each file in the array to a directory.
Function inside an included php file:
function upload_to_file(){
$image_paths = array();
$target_dir = "uploads/images/";
$path = $target_dir . basename($_FILES['images']['name'][0]);
if(isset($_FILES['images']['name'][0]) && $_FILES['images']['size'][0] > 0)
{
if (move_uploaded_file($_FILES['images']['tmp_name'][0], $path)) {
$image_paths[0] = "uploads/images/";
}
}
return $image_paths;
}
I'm only testing it with the first element in the array, but will need to make a loop later.
Here is the program, which help you to upload multiple files. in the code "sub" is the submit button name. "upload" is the name of file controller, the uploaded files are stored in the directory called "img" that you have to create on your root folder.
<?php
if (isset($_POST['sub'])) {
if (count($_FILES['upload']['name']) > 0) {
for ($i=0; $i<count($_FILES['upload']['name']); $i++) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "") {
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
}
}
}
}
echo "<h1>Uploaded:</h1>";
if(is_array($files)){
echo "<ul>";
foreach($files as $file){
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
HTML Code is given
<form action="" enctype="multipart/form-data" method="post">
<input id='upload' name="upload[]" type="file" multiple="multiple" />
<input type="submit" name="sub" value="Upload Now">
</form>

HTML form data to PHP script

What small background I have is in Python. I've never used PHP before, so I'm somewhat lost. What I'm trying to do is upload files through an HTML form and then parse the files with a PHP script and display the results back to the user.
This is my HTML:
<html>
<form enctype='multipart/form-data' action='read.php'
method='POST'>
<input type='hidden'/>
Choose a file to upload: <input name='uploadedfile' type='file' multiple /><br />
<input type='submit' value='Upload File' />
</form>
</html>
it seems to work, but I could be missing something obvious.
My PHP script is
<?php
if ($_FILES['uploadedfile']['name'] !==false)
file_get_contents($_FILES);
foreach (glob($_FILES["uploadedfile"]["name"]) as $file) {
if (is_uploaded_file($file['temp_name']))
$file_handle = fopen(file, "r");
while (feof($file_handle)) {
$e = array("code", "money", "notes", "date2");
$n = 0;
$line = fgets($file_handle);}
foreach($line as $value) {
if ($n=0);
if (strpos($line, 'Sent:') !==false);{
array_push($e, $line);}
if (strpos($line, 'REFERENCE NUMBER:') !==false) ;{
$n = 1;
array_push($e, $line);}
if ($n<40);{
array_push($e, $line);
$n = $n+1;}
echo $e;}}
?>
It doesn't do anything, and I'm not even sure whether the files are going through or if I just don't know how to access them. Any help would be appreciated.
If you would like to upload multiple files, you need to set name of input as array:
<input name='uploadedfile[]' type='file' multiple />
And then you can read all uploaded files in cycle:
<?php
foreach ($_FILES['uploadedfile']['error'] as $i => $error) {
if ($error === UPLOAD_ERR_OK) {
$file_handle = fopen($_FILES['uploadedfile']['tmp_name'][$i], 'r');
// your code here
} else {
// check error number: http://php.net/manual/en/features.file-upload.errors.php
}
}

php multiple image upload and display each image

i'm struggle with some multiple image upload script.
what i implement to do is , upload multiple image then save each image saved path to variable
so i use later for display .
but when i run script i only can save first upload image path value.
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<input type="file" name="pictures[]" /><br>
<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];
$ext = substr(strrchr($name, "."), 1);
$randName = md5(rand() * time());
$pathimg = "images/$randName.$ext";
move_uploaded_file($tmp_name, $pathimg );
echo '<img src="'.$pathimg.'"; >' ;
}
}
?>
this is upload path ''
for example if i upload 3 images then i want to save this 3 image uploaded path to variable each. so each variable will be $A, $B, $C
or if i upload 4 images i also want to this 4 image path to variable each then use for later
please enlighten me! thanks
Why do you expect errors while uploading.
Change
foreach ($_FILES["pictures"]["error"] as $key => $error) {
to
foreach ($_FILES["pictures"] as $key => $tempFile) {
Also, after successful upload, append the images into an array.
$arr = array();
foreach ($_FILES["pictures"] as $key => $tempFile) {
// YOUR CODE
$arr[] = '<img src="'.$pathimg.'"; >' ;
}
And print it in a loop.
if (! empty($arr)) {
foreach ($arr as $img) {
echo '<img src="'.$img.'"/>';
}
}

Uploading files with PHP

I am using a form for users to upload files to my website. I want to allow them to upload multiple photos at once, so I am using the HTML5 "multiple" attribute.
My HTML:
<form method="post" action="save.php">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
But, for some reason when I run the script, I get an error saying undefined index: uploads. And an error saying that I have an invalid argument supplied for foreach(). What could I be dong wrong?
Thanks
UPDATE
Okay, setting the enctype="mulitpart/form-data" worked. Now, I am having trouble with moving the file. I am getting the error move_uploaded_file() expects parameter 1 to be string, array given. What am I doing wrong here?
Thanks again
You need the proper enctype to be able to upload files.
<form method="post" enctype="multipart/form-data" action="save.php">
try this html code: <form method="post" action="save.php" enctype="multipart/form-data">
Then in PHP:
if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
} else {
echo 'some error message!';
}
In order to upload files in the first place, you need enctype="multipart/form-data" on your <form> tag.
But, when you upload multiple files, every key in $_FILES['uploads'] is an array (just like $_FILES['uploads']['name']).
You need to get the array key when looping, so you can process each file. See the docs for move_uploaded_file for more deatils.
<?php
foreach ($_FILES['uploads']['name'] as $key=>$file) {
echo $file."<br/>";
$file = time().$file;
$target = UPLOADPATH.$file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with query 2');
}
index.html
<form method="post" action="save.php" enctype="multipart/form-data">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="Upload Image"/>
</form>
save.php
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {
$file_name = time() . $_FILES['uploads']['name'][$x];
$file_tmp = $_FILES['uploads']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>

Categories