php sending form data between files - php

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>

Related

PHP uploads only one file when I need many

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']);

Adding variables to database with a for loop

My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>

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']

PHP $_POST from dynamically generated form

I am creating a form based on a user selection of $node_number ... so the form looks like:
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title" . $n . "\" name=\"node_title" . $n . "\" />
<input id=\"node_comment" . $n . "\" name=\"node_comment" . $n . "\" type=\"textarea\" />
</fieldset>";
}
echo "<input type=\"hidden\" name=\"node_number\" value=\"" . $node_number . "\">
<button id=\"submit_node\" type=\"submit\">Submit</button>"
echo "</form>";
}
Which will create $node_number of versions of that form element. My question is how to dynamically name the form elements to be able to manage them easier when I am processing them. The way I'm doing it right now, by adding the $n iterator to the name attribute is not ideal I think.
I understand that I can declare the name="" attribute as an array like name[]="" ... in terms of giving each sub-element of the larger form a unique name.
I'm guessing I want a multi-dimensional array of the individual form segment ... just not sure how to best handle those within a form and within the $_POST variable.
Does anyone have any suggestions?
I think you can do it this way:
function createForm($node_number) {
echo '<form id="form" name="form" action="molecule_display.php" method="post">';
for ($n = 1; $n <= $node_number; $n++) {
echo '<fieldset class="step">
<input id="node_title'.$n.'" name="nodes['.$n.'][node_title]" />
<input id="node_comment'.$n.'" name="nodes['.$n.'][node_comment]" type="textarea" />
<button id="submit_node" type="submit">Submit</button></p>
</fieldset>';
}
echo '</form>';
}
And then get $_POST['nodes'] which will be multidimensional array, which you can iterate with foreach. You will get $_POST['nodes'][1] = array('node_title'=>... , 'node_comment'=>...); and so on.
If you use the array like you were saying in your post you should be able to access them pretty easily.
function createForm($node_number) {
echo "<form id=\"form\" name=\"form\" action=\"molecule_display.php\" method=\"post\">";
for ($n = 1; $n <= $node_number; $n++) {
echo "<fieldset class=\"step\">
<input id=\"node_title_" . $n . "\" name=\"node_title[" . $n . "]\" />
<input id=\"node_comment_" . $n . "\" name=\"node_comment[" . $n . "]\" type=\"textarea\" />
<button name=\"submit_node[" . $n . "]\" type=\"submit\">Submit</button></p>
</fieldset>";
}
echo "</form>";
}
I also changed the submit_node to a name and gave it an array value because an ID must be unique, which will cause errors if you are referencing it somewhere.
You could loop through the results like this:
foreach ($_POST['node_title'] as $key => $response) {
$title = $response;
$comment = (!empty($_POST['node_comment'][$key])) ? $_POST['node_comment'][$key] : "";
// Save title / comment here.
}
Since every form has its own submit button, nothing stops you from using name="node_title" in all of them. If you now add <input type="hidden" name="index" value="$n"> and read this first, your logic becomes very easy.

Categories