I'm doing some tests with forms and ran into a snag, I have a very simple test script that works, but the problem is that my FILE field in the form is not getting submitted to the $_POST array for some reason, if I take out encode="multipart/form-data" it does, otherwise I just get the other fields. Here is the script:
<?PHP
print_r($_POST);
echo"<br>";
print_r($_FILES);
$name = $_FILES["img1"]["name"];
$tmp_name = $_FILES["img1"]["tmp_name"];
$uploads_dir = "uploads";
echo "<br>TEMP NAME:</b>";
echo $tmp_name;
move_uploaded_file($tmp_name, "$uploads_dir/$name");
?>
<html>
<body>
<br><br>
-------------------------
<form name="test" id="test" action="index.php" method="post" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="title" id="title">
<br>
<label>File</label>
<input type="file" name="img1" id="img1" size="40">
<br>
<input type="submit" value="submit">
</form>
The output is:
POST ARRAY: Array ( [title] => some title )
FIELS ARRAY: Array ( [img1] => Array ( [name] => chicken.jpg [type] => image/jpeg [tmp_name] => /tmp/phpcrBLw9 [error] => 0 [size] => 30940 ) )
TEMP NAME:/tmp/phpcrBLw9
As you can see, the POST only has the title, not the file name, I need it to have both for programming reasons, is there a way to do that without having to cheat / have hidden fields or edited values manually?
You will not be able to see $_FILES inside $_POST. They are different superglobals, if you vardump($_FILES); you will see that it stores all the information about the uploaded file, like size, tmp name etc. This is how PHP has been built, and the only thing you can do about it is access the name using
$_FILES['img1']['name']
You can access the name of the uploaded file here:
$_FILES["img1"]["name"]
Related
This question already has answers here:
Get all variables sent with POST?
(6 answers)
How to grab all variables in a post (PHP)
(5 answers)
How do I get the key values from $_POST?
(6 answers)
Retrieve post array values
(6 answers)
How to get an array of data from $_POST
(3 answers)
Closed 5 years ago.
I have an HTML-form with 3 inputs of type text and one input of type submit, where a name of an animal is to be inserted into each textbox. The data should then be inserted into a PHP-array.
This is my HTML-form:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal1" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal2" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal3" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
And this is my much experimental PHP-code:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1"];
$farmAnimals = $_POST["animal2"];
$farmAnimals = $_POST["animal3"];
}
// As a test, I tried to echo the saved data
echo $farmAnimals;
?>
This does not work, as the data doesn't magically turn into an array, unfortunately, which I thought it would.
I have also tried this:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1", "animal2", "animal3"];
}
echo $farmAnimals;
?>
This gives me an error message. How can I insert this data into a PHP-array?
First initialize the $farmAnimals as array, then you can push elements
if (isset ($_POST["send"])) {
$farmAnimals = array();
$farmAnimals[] = $_POST["animal1"];
$farmAnimals[] = $_POST["animal2"];
$farmAnimals[] = $_POST["animal3"];
print_r($farmAnimals);
}
Try this:
$string = "";
foreach($_POST as $value){
$string .= $value . ",";
}
Or this:
$string = implode(',', $_POST);
If you change the text field names to animal[] then you have an array of animal names when it is posted
<form action='Test.php' method='post'>
<input type='text' placeholder='Enter animal one...' name='animal[]' />
<input type='text' placeholder='Enter animal two...' name='animal[]' />
<input type='text' placeholder='Enter animal three...' name='animal[]' />
<input type='submit' value='Submit' name='send' id='send'>
</form>
You can then process that array in php easily for whatever end purpose you have - the output of which would be like this:
Array
(
[animal] => Array
(
[0] => giraffe
[1] => elephant
[2] => rhinocerous
)
[send] => Submit
)
To access these animals as an array in their own right you could do:
$animals=array_values( $_POST['animal'] );
Try naming your input fields like this:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal[0]" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal[1]" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal[2]" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
This way you be able to access those values in your PHP code like this:
if(isset($_POST["send"])) {
$farmAnimals = $_POST["animal"];
}
var_dump($farmAnimals);
// Array( [0] => Animal1, [1] => Animal2, [2] => Animal3 )
// Where Animal1,... are the values entered by the user.
// You can access them by $farmAnimals[x] where x is the desired index.
Tip: You can use empty() to check a variable for existance and if it has a "truthy" value (a value which evaluates to true). It will not throw an exception, if the variable is not defined at all. See PHP - empty() for details.
Futher reference about the superglobal $_POST array, showing this "array generating name" approach: https://secure.php.net/manual/en/reserved.variables.post.php#87650
Edit:
I just saw, that you actually overwrite your $farmAnimals variable each time. You should use the array(val1, val2, ...) with an arbitray amount of parameters to generate an numeric array.
If you prefer an associative array do this:
$myArray = array(
key1 => value1,
key2 => value2,
....
);
To append a value on an existing array at the next free index use this syntax:
// This array contains numbers 1 to 3 in fields 0 to 2
$filledArray = array(1,2,3);
$filledArray[] = "next item";
// Now the array looks like this:
// [0 => 1, 1 => 2, 2 => 3, 3 => "next item"]
I've designed one HTML form as follows :
<form action="sample_test.php" method="post">
<input type="text" name="fileName" value="8.png" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink[]">
<input type="text" name="fileName" value="2_OnClick_OK.jpg" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink[]">
<input type="submit" name="Submit" value="Submit File">
</form>
Then the code in sample_test.php is as follows :
<?php
print_r($_POST); die;
?>
The output I got is as follows :
Array ( [fileName] => 2_OnClick_OK.jpg [fileLink] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ [Submit] => Submit File )
But this is not the desired output. I want the desired output array to be printed in following manner:
Array
(
[8.png] => Array
(
[0] => https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd
)
[2_OnClick_OK.jpg]
(
[0] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ
)
)
For now I've just demonstrated with two elements only but in real situations hundreds of such elements could present on the form.
So what changes do I need to make in my HTML as well as PHP code? Please help me.
Thanks in advance.
What you ask is impossible by just modifying the HTML code, because you would like a value (of fileName) to become an index in the array you get. That's impossible, the index will always be the name of the input.
However, if you have a look here : POSTing Form Fields with same Name Attribute , you will be able to get arrays of fileName and fileLink, and I'm pretty sure you can do something from there.
A few things wrong, but you are close. Make the name field an array instead of the id - plus your ids need to be unique.
<input type="text" name="fileName[]" value="8.png" id="fileName1">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink1">
<input type="text" name="fileName[]" value="2_OnClick_OK.jpg" id="fileName2">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink2">
Not tested, but should do the trick.
I am trying to fetch some form data but something interrupts,
<?php
if(isset($_POST['submit'])){
$data = $_POST;
}
?>
<form action = "page.php" method="post">
Username<input type="username" name="username"/><br/>
Password<input type="text" name="password"/><br/>
<input type="submit" name="submit"/>
</form>
okay, the above outputs to
Array ( [username] => '' [password] => '' [email] => '' [submit] => Submit )
Okay, if i am to send this into database. i should be sending it without the key submit and value submit. How do you do it?
Unset it.
if ( isset($_POST['submit']) ) {
unset($_POST['submit']);
}
A better practice would be to save it to a new variable and make changes there.
I'm trying to get a multidimensional array to store the info from three separate elements (caption, image, and subfolder). The three elements are descriptions from photos that individuals may upload onto my site. I've built an initial page that asks the visitor how many photos they intend to upload and from which country(an input type=select). Based upon their response on that initial form, the second page uses a loop to generate the appropriate number of , , and elements. Once the second form is submitted the intention is to upload the info to the server which it does. The second objective is to store that information inside the multidimensional array such as below in order to upload into a MySQL table. My dilemma is in getting the image names presumably from ($_FILES['image']['name']) to insert themselves into my multidimensional array. The captions '' insert themselves into the multidimensional array as does the country name ('name=subfolder']) but not the image names. I'd greatly appreciate anyone willing to help with this.
Thank you.
Array ( [caption] => Array ( [0] => Nice Simple Picture [1] Another Nice Simple Picture=> )
[image] => [subfolder] => Array ( [0] => Italy ) [upload] => UPLOAD )
Here's a bit of how I've attempted to go about this..
<?php
$file=$_FILES['image']['name'];
$expected = array('image','subfolder','caption');
foreach ($_POST as $key => $value) {
if (in_array ($key, $expected)) {
${$key} = mysql_real_escape_string($value); }}
$sql = "INSERT INTO images (file_name, country, caption)
VALUES ('$image', '$subfolder', '$caption')";
$result = mysql_query($sql) or die (my_sql_error()); }
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="form1" name="form1" method="POST"
enctype="multipart/form-data">
<?php
for ($i=0; $i<$imgnumb; $i++) {
echo "<input type=\"file\" name=\"image[".$i."]\" /> <input type=\"text\"
name=\"caption[".$i."]\" /><br />"; }
?>
<br />
<input value="<?php echo $file; ?>" name="image" type="hidden" />
<input value="<?php echo $location; ?>" name="subfolder" type="hidden" />
<input value="<?php echo $_POST['caption']; ?>" name="caption" type="hidden" />
<input type="submit" name="upload" id="next" value="UPLOAD" />
</form>
I am working on a project at the moment, that allows the user to create any number of news headlines, articles and images, the only rule with this system is that a headline must have an article and an image. My question is on my form when I submit I get 2 arrays one is the $_POST and the other is $_FILES.
$_POST
Array
(
[campaign_title] => Another multiple test
[campaign_keyword] => Another multiple test
[introduction] => Another multiple test
[campaign_headline] => Array
(
[0] => Another multiple test headline 1
[1] => Another multiple test headline 2
)
[article] => Array
(
[0] => Another multiple test article 1
[1] => Another multiple test article 2
)
[save_multiple] => Save
)
$_FILES
Array
(
[article_image] => Array
(
[name] => Array
(
[0] => Intro-artists.gif
[1] => textbg1.png
)
[type] => Array
(
[0] => image/gif
[1] => image/png
)
[tmp_name] => Array
(
[0] => /private/var/tmp/phpwDAkGJ
[1] => /private/var/tmp/phpmvrMDg
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 2841
[1] => 56506
)
)
)
Basically the method after submitting the form is the data is saved to a database, the 3 items of the post are saved in one table, the headlines and articles are saved in another table (sent with the id of the row just inserted) and then finally the images are saved, again sent with id of the first saved row.
I am having trouble understanding how I make sure the right images gets saved with the right ID, the DB saves are done by looping through the headlines and articles, but as the images are in a different array I cannot do this and make sure they are getting saved with right foreign id, can I merge the files into the post? Currently the solution I have for the headlines and articles is this,
foreach ($data['campaign_headline'] as $key => $headline) {
addMailerMultipleRelatedContent($mailerId, $headline, $data['article'][$key]);
}
function addMailerMultipleRelatedContent($mailerId, $headline, $article) {
extract($data);
//die(print_r($id));
$id = addRelatedMultipleContent($data['introduction'], $headline, $article,
$mailerId, mktime(), mktime());
}
function addRelatedMultipleContent($introduction, $headline, $content,
$mailer_id, $created_at, $updated_at){
$query = "INSERT INTO `mailer_content` (`id`, `introduction`, `headline`,
`content`, `mailer_id`,`created_at`, `updated_at`) VALUES ";
$query .= "(NULL, '" . makeSafe($introduction) . "', '" .
makeSafe($headline) . "', '" . makeSafe($content) . "', '" .
makeSafe($mailer_id) . "', " . makeSafe($created_at) . ", " .
makeSafe($updated_at) . ");";
$result = runInsert($query, __FUNCTION__);
//die(print_r($result));
return $result;
}
Is there away for me to work with images at the same time?
EDIT:
The HTML form,
<form method="post" action="/admin/editmultiple" enctype="multipart/form-data">
<fieldset class="toplined">
<label>Campaign Title</label>
<input type="text" name="campaign_title" value="<?echo (isset($mailers['mailer_title'])) ? $mailers['mailer_title'] : $_POST['campaign_title'];?>" class="extrawideinput" />
</fieldset>
<fieldset class="toplined">
<label>Campaign Type:</label>
<label>Multiple</label>
</fieldset>
<fieldset class="toplined">
<label>Campaign Keyword:</label>
<div class="forminputblock">
<input type="text" name="campaign_keyword" value="<?echo (isset($mailers['mailer_header'])) ? $mailers['mailer_header'] : $_POST['campaign_keyword'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Introduction</label>
<div class="forminputblock">
<input type="text" name="introduction" value="<?echo (isset($mailers['introduction'])) ? $mailers['introduction'] : $_POST['introduction'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Headline</label>
<div class="forminputblock">
<input type="text" name="campaign_headline[]" value="<?echo (isset($mailers['headline'])) ? $mailers['headline'] : $_POST['campaign_headline'];?>" class="extrawideinput" />
</div>
</fieldset>
<fieldset class="toplined">
<label>Image:</label>
<input type="file" name="article_image[]">
</fieldset>
<fieldset class="toplined">
<label>Story:</label>
<div class="forminputblock">
<textarea name="article[]" class="js_editable_textarea deeptext" rows="1" cols="1"><?echo (isset($mailers['content'])) ? $mailers['content'] : $_POST['article'];?></textarea>
</fieldset>
<div id="result">
</div>
<fieldset class="toplined">
+ Add Another New Article
</fieldset>
<fieldset class="toplined">
<input type="submit" name="save_multiple" value="Save" />
</fieldset>
</form>
With the same key you use to access the articles sub array, you can access the different fields in the $_FILES array. Obviously you can merge the two arrays, but it isn't necessary for you to work with them.
Also, you should note that you have to copy the actual data from the temporary location to where ever you would like to permanently store it. Make sure to use the [is_uploaded_file()][1] and [move_uploaded_file()][2] methods to prevent potential attacks via file uploads.
[1]: http://www.php.net/manual/en/function.is-uploaded-file.php is_uploaded_file()
[2]: http://www.php.net/manual/en/function.move-uploaded-file.php move_uploaded_file()
I'm not sure that you would want to merge the two arrays, as you need to perform different actions on each array.
With the $_FILES array, the uploaded images will be stored in a temporary location, the images need to be moved to a more permanent location before being referenced in your database.
EDIT: I've just recoded you an entire example of how it could easily work. (uses jquery as an example)
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var position = 1;
$(".add").click(function(){
var parent = $(this).parent();
var newField = $(this).parent().clone(true).insertAfter(parent);
/* title */
var newName = 'articles['+ position + '][title]';
newField.children(".name").attr("name", newName);
/* content */
newName = 'articles['+ position + '][content]';
newField.children(".content").attr("name", newName);
/* content */
newName = 'articles['+ position + '][checkbox]';
newField.children(".checkbox").attr("name", newName);
newField.slideDown();
position++;
});
});
</script>
<h1>example</h1>
<form action="" method="post">
<fieldset class="article">
<label style="display:block">Article title</label>
<input type="text" name="articles[0][title]" value="" class="name" />
<label style="display:block">Article content</label>
<textarea name="articles[0][content]" cols="40" rows="10" class="content"></textarea>
<label style="display:block">Checkbox</label>
<input type="checkbox" name="articles[0][checkbox]" value="1" class="checkbox" />
<br />
add new after
</fieldset>
<br />
<input type="submit" value="submit" name="submit" />
</form>