PHP uploads only one file when I need many - php

I need to run this code applying to each file uploaded:
$uploads_dir = 'tdump';
$tmp_name = $_FILES['upfiles']["tmp_name"];
$name = basename($_FILES['upfiles']["name"]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$filename="$uploads_dir/$name";
echo "$filename";
$mp3file=new CMP3File;
$mp3file->getid3($filename);
echo "Title: $mp3file->title<br>\n";
echo "Artist: $mp3file->artist<br>\n";
echo "Album: $mp3file->album<br>\n";
echo "Year: $mp3file->year<br>\n";
echo "Comment: $mp3file->comment<br>\n";
echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
I tried this so far:
$total = count($_FILES['upfiles']['name']);
print_r($total);
for ($i=0; $i < $total; $i++){
$uploads_dir = 'tdump';
$tmp_name = $_FILES['upfiles']["tmp_name"];
$name = basename($_FILES['upfiles']["name"]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$filename="$uploads_dir/$name";
echo "$filename";
$mp3file=new CMP3File;
$mp3file->getid3($filename);
echo "Title: $mp3file->title<br>\n";
echo "Artist: $mp3file->artist<br>\n";
echo "Album: $mp3file->album<br>\n";
echo "Year: $mp3file->year<br>\n";
echo "Comment: $mp3file->comment<br>\n";
echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
}
html code:
<form method="post">
<input name="upfiles[]" type="file" multiple/>
<input type="submit" name="send">
</form>
mp3file variable is getid3 library, don't focus on it. The thing I can't figure out in this whole bunch of code is how to loop through each uploaded file, get its name and save it. I think it should be for or foreach loop.

for($i=0; $i<your_no_of_files; $i++)
{
$tmp_name = $file["tmp_name"];
$name = basename($file["name"]).$i;
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$filename="$uploads_dir/$name";
echo "$filename";
$mp3file=new CMP3File;
$mp3file->getid3($filename);
echo "Title: $mp3file->title<br>\n";
echo "Artist: $mp3file->artist<br>\n";
echo "Album: $mp3file->album<br>\n";
echo "Year: $mp3file->year<br>\n";
echo "Comment: $mp3file->comment<br>\n";
echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
}**MAYBE THIS WILL WORK**

HTML example :
<input type="file" name="filename[]">
<input type="file" name="filename[]">
....
<input type="file" name="filename[]">
Try do like that, instead of "filename" use your.
PHP example :
if ($_FILES){
for ($i = 0; $i < count($_FILES['filename']['name']); $i++) {
//......
$tmp_name = $_FILES['filename']["tmp_name"][$i];
//......
}
}

in your form part edit the following attribute
<input name="userfile[]" type="file" />
this userfile array will store all your file in an array.
then use count() function to display the no of elements.
for e.g.
$no_of_files=count($_FILES['userfile']['tmp_name']);

Related

Submitted comment edit in textarea then save

SO, I am working on a short script that takes a user's "bug report" and saves it. Showing the comment at the bottom of the page with an Edit button for editing. I want for that button to take the user to another page with a textarea, their comment would be editable here and a Save button to save their report. I am not sure how to link to the exact comment the user would upload.
Like this:
This is what I have so far:
Bug Reports
<form method="POST" action="Bugs.php">
<p>Bug Name <input type="text" name="name" /><br />
Hardware Type <input type="text" name="hw" /><br />
OS <input type="text" name="os" /> <br />
Frequency of Occurence <input type="text" name="freq" /></p>
<p>Proposed Solutions<br />
<textarea name="sol" rows="6" cols="100"></textarea>
<input type="submit" name="submit" value="Create New Bug Report" /></p>
</form>
<?php
$Dir = "comments";
if (is_dir($Dir)) {
if (isset($_POST['submit'])) {
if (empty($_POST['name'])) {
$String = "Unknown Visitor";
}
else
$String = stripslashes($_POST['name']) . "|";
$String .= stripslashes($_POST['hw']) . "|";
$String .= stripslashes($_POST['os']) . "|";
$String .= stripslashes($_POST['freq']) . "|";
$String .= stripslashes($_POST['sol']);
$CurrentTime = microtime();
$TimeArray = explode(" ", $CurrentTime);
$TimeStamp = (float)$TimeArray[1] + (float)$TimeArray[0];
/* File name is " Comment.seconds.microseconds.txt" */
$SaveFileName = "$Dir/Comment.$TimeStamp.txt";
if (file_put_contents($SaveFileName, $String)>0)
echo "File \"" . htmlentities($SaveFileName) . "\" successfully saved.<br />\n";
else
echo "There was an error writing \"" . htmlentities($SaveFileName) . "\".<br />\n";
}
}
if (is_dir($Dir)) { //show submitted reports on page
$CommentFiles = scandir($Dir);
foreach ($CommentFiles as $FileName) {
if (($FileName != ".") && ($FileName != "..")) {
echo "From <strong>$FileName</strong><br />";
echo "<pre>\n";
$Comment = file_get_contents($Dir . "/" . $FileName);
echo $Comment . "<a href=edit.php>Edit</a>";
echo "</pre>";
echo "<hr />";
}
}
}
?>
You really need to put all this into a database it would be much easier.
However.. when you foreach all the comments in the folder add a $_GET variable with the file name like this:
echo $Comment . "Edit";
Then with edit section you can call urldecode($_GET['com_id']) to access the file name and edit the comment.

Trying to send the value of a radio button in a form to a php variable.

I tried the following code, and I can't figure out what I'm doing wrong. I know I'm breaking rules by having the form spread out amongst two different divs, but I don't know any other way around it.
<?php
echo '<form name="form" method="POST">';
$directory = '/var/www/admin/html/content';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
echo 'Files<br>';
while($it->valid()) {
if(!$it->isDot()) {
echo '<input type="radio" name="file_picked" value="content/' . $it->getSubPathName() . ' " id="file_picked" />' . $it->getSubPathName() . '</br>';
}
$it->next();
}
echo '<input type="submit" name="pickedName" value="Edit File" /></div>
<div class="editor">
<h1>SS Code Editor</h1>';
$file_picked = $_POST['file_picked'];
$edit_field = $_POST['edit_field'];
if(isset($_POST['pickedName'])) {
//get file contents and display in textarea box
$theData = file_get_contents($file_picked);
echo "<textarea name=\"edit_field\" id=\"edit_field\" cols=\"100\" rows=\"60\">";
echo $theData;
echo "</textarea><br />";
}
if(isset($_POST['submitChanges'])) {
//grab new textarea contents and put into file.
$theData = file_put_contents($file_picked, $edit_field);
//redraw textarea with new contents
$theData = file_get_contents($file_picked);
echo "<textarea name=\"edit_field\" id=\"edit_field\" cols=\"100\" rows=\"60\">";
echo $theData;
echo "</textarea><br />";
}
?>
<input type="submit" name="submitChanges" value="Save">
</form>
You have an extra space at the end of the checkbox input value :
Replace :
value="content/' . $it->getSubPathName() . ' " id="...
with :
value="content/' . $it->getSubPathName() . '" id="...
So file_get_contents($file_picked = $_POST['file_picked'])) don't find any file (with space at the end) and returns false, which is displayed as "" in the textarea.
Your value should be stored in $_POST['file_picked']

$_FILES undefined PHP upload form. Can't figure out [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting ‘undefined index’ error while trying to use $_FILE in PHP
I have made a php upload form for images. It uses session variables to determine the upload directory. There are two options for the uploads, the slider dir or the side dir so I have an if statement that determines the directory. If i remove this from the form then the whole thing works ok however with it in, $_FILES seems to not be declared and returns as an undefined index error.
The code can be found is as follows:
upload.php
<?php
include("resize-class.php");
$allowedExt = array('jpg', 'jpeg', 'JPG', 'JPEG');
$tmps = explode(".", $_FILES['file']['name']);
$extension = end($tmps);
session_start();
if ($_POST['dir'] == 'side'){
$dirent = $_SESSION['sideDir'];
}
else if($_POST['dir'] == 'slider'){
$dirent = $_SESSION['sliderDIR'];
}
else{
die();
}
echo $_POST['dir'];
print_r($_FILES);
if (($_FILES["file"]["type"] == "image/jpeg")&& ($_FILES["file"]["size"] < 4000000000)&& in_array($extension, $allowedExt)) {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
echo 'here';
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . " <br />\n";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br /> \n";
echo "Stored in: " . $_FILES["file"]["tmp_name"]. "<br />\n";
}
if (file_exists($dirent. $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . "already exists";
} else {
$fName = $_FILES["file"]["name"];
$tmpname = $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $dirent . $_FILES["file"]["name"]);
$number = FileCounter($dirent);
echo "Number of images in DIR: " . $number. " <br />\n ";
$number +1;
$resizeObj = new resize($dirent.$fName);
$resizeObj -> resizeImage(250, 150, 'crop');
$resizeObj -> saveImage($dirent.$number.".jpg", 100);
unlink ($dirent.$_FILES["file"]["name"]);
}
} else {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
function FileCounter($dir) {
$counter = 0;
$iterator = new DirectoryIterator(dirname($dir));
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getExtension() == "jpg") {
$counter++;
echo $counter . "\n";
}
}
}
return $counter;
}
?>
HTML FORM:
<form action="includes/upload.php" method="post">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<div class="styled-select">
<label for="dir"> Upload to:</label>
<select size="2" name="dir" multiple="yes" id="dir">
<option value="side" >Side Images</option>
<option value="slider" >Slider Images</option>
</select>
</div>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
I am guessing that there is either a really stupid error in my code that I am overlooking as I have been staring at it for an hour now or that there is something that I do not know about $_FILES and $_POST. (or possibly I have coded the form like a moron!).
Your form is missing
enctype="multipart/form-data"

php sending form data between files

I am new to php and form development and here's what I am trying to achieve:
Firstly i have a simple form to input just two text values:
Form1
<br>
<form action="gather.php" method="post">
Catalog:
<input type="text" name="folderName" maxlength="50">
<br>
File Name:
<input type="text" name="fileName" maxlength="50">
<br>
<input type="submit" name="formSubmit" value="Submit">
</form>
And now I have the second file called gather.php where i get theese two lines and use them to count files inside catalog etc.
<?php
if(isset($_POST['formSubmit'])){
$folderName = $_POST['folderName'];
$fileName = $_POST['fileName'];
$numberOfImages = count(glob($folderName . "/*.jpg"));
for($i = 1; $i <= $numberOfImages; $i++){
echo "<br><input type=\"text\" name=\"imie" . $i . "\"><br/>\n";
echo "<img src=\"" . $folderName . "/0" . $i . ".jpg\" height=\"50px\" width=\"50px\"><br><br>\n";
}
echo "\n<br>" . $folderName . "<br>" . $fileName . "\n";
}
?>
<br>
Final form
<br>
<form action="build.php" method="post">
<input type="submit" name="finalSubmit" value="Submit">
</form>
And this should get me to build.php file which looks more less like this:
<?php
if(isset($_POST['finalSubmit'])){
//loop and other stuff
$temp = $_POST['imie1'];
echo $temp;
}
?>
So the thing is that in this final file I'd like to get all the data that was put into text fields in the gather.php file. But I get the undefined index error on build.php saying there's nothing in the $_POST['imie1']. Can you tell me why is that? Is tehre a way to get this data from second file to the third file?
Edit: thx for the answers, as I can accept only 1 and multiple are the same I choose the user with least rep just to support her :)
You need to add the input inside the form tag, it won't be sent otherwise.
<br>
Final form
<br>
<form action="build.php" method="post">
<?php
if(isset($_POST['formSubmit'])){
$folderName = $_POST['folderName'];
$fileName = $_POST['fileName'];
$numberOfImages = count(glob($folderName . "/*.jpg"));
for($i = 1; $i <= $numberOfImages; $i++){
echo "<br><input type=\"text\" name=\"imie" . $i . "\"><br/>\n";
echo "<img src=\"" . $folderName . "/0" . $i . ".jpg\" height=\"50px\" width=\"50px\"><br><br>\n";
}
echo "\n<br>" . $folderName . "<br>" . $fileName . "\n";
}
?>
<input type="submit" name="finalSubmit" value="Submit">
</form>
Replace your gather.php with
<br>
Final form
<br>
<form action="build.php" method="post">
<?php
if(isset($_POST['formSubmit'])){
$folderName = $_POST['folderName'];
$fileName = $_POST['fileName'];
$numberOfImages = count(glob($folderName . "/*.jpg"));
for($i = 1; $i <= $numberOfImages; $i++){
echo "<br><input type=\"text\" name=\"imie" . $i . "\"><br/>\n";
echo "<img src=\"" . $folderName . "/0" . $i . ".jpg\" height=\"50px\" width=\"50px\"><br><br>\n";
}
echo "\n<br>" . $folderName . "<br>" . $fileName . "\n";
}
?>
<input type="submit" name="finalSubmit" value="Submit">
</form>
you was echo'ing the input boxes outside the form so now it will work
I think the <form> on the second form needs to come at the top of the file - it'll only submit elements inside the tag, so because you're generating your HTML and then opening the form, it's not being submitted.
<br>
Final form
<br>
<form action="build.php" method="post">
<?php
if(isset($_POST['formSubmit'])){
$folderName = $_POST['folderName'];
$fileName = $_POST['fileName'];
$numberOfImages = count(glob($folderName . "/*.jpg"));
for($i = 1; $i <= $numberOfImages; $i++){
echo "<br><input type=\"text\" name=\"imie" . $i . "\"><br/>\n";
echo "<img src=\"" . $folderName . "/0" . $i . ".jpg\" height=\"50px\" width=\"50px\"><br><br>\n";
}
echo "\n<br>" . $folderName . "<br>" . $fileName . "\n";
}
?>
<input type="submit" name="finalSubmit" value="Submit">
</form>

using a form variable with a file upload script

I am using this form as a file upload form(as part of a larger php script, $pk is sanitized in the actual thing):
<?php
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
echo '<form action="up.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="hidden" name="pk" value="$pk">
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
I am using the following(extremely trimmed) code to handle the upload. Any syntax errors are a result of the tabifier I used.
<?php
if (isset($_GET["pk"])) {
$pk = $_GET["pk"];
}
$con = mysqli_connect("localhost","x","x", "x");
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
move_uploaded_file($_FILES["file"]["tmp_name"],
"./" . $_FILES["file"]["name"]);
echo "Stored in: " . "./" . $_FILES["file"]["name"];
$fileQuery = "INSERT INTO FILES VALUES (?, ?)";
if ($fileInsert = $con->prepare($fileQuery)) {
$fileInsert->bind_param("ss", $pk, $_FILES["file"]["name"]);
$fileInsert->execute();
$fileInsert->close();
} else {
print_r($con->error);
}
?>
What I would like to know, is how do I access $pk. Is it already passed to the handling code with the form?
Suggestion: $pk is not set.
So try to use $_REQUEST['pk'] instead of _GET
Also, the single quotes in your echo won't evaluate $pk. Alter
input type="hidden" name="pk" value="$pk"
to
input type="hidden" name="pk" value="' . $pk . '"
Cheers, T.
$_POST['pk']
but you'll see $pk I guess, because you're using single quotes to echo the string.

Categories