Post multiple images in a form - Upload to server help

sikuneh

New Member
Messages
55
Reaction score
0
Points
0
I am updating a review site. I would like the posters to be able to add multiple images into their posts.

First, what would be the best way for the form to handle this,
and second, what would be the best way for the addPost script to upload all the images?

My thought was to have a button that brings a javascript prompt for fileName.fileType and includes an <img src=prompt> in the post but I'm not sure how to get each image from the user's computer.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
That's not nearly enough information. You're assuming we know more about your site internals than we do. Any recommendations we could give at this point wouldn't be specific to your site and may be off-base.

<img> elements can't transfer files to the server, they just cause the browser to load the image. All replaced elements are the same: the content is loaded client-side.
 

sikuneh

New Member
Messages
55
Reaction score
0
Points
0
Sorry, I thought there was some generic answer I just wasn't seeing.

Here is my post form:
HTML:
<?PHP

// Post_form.php

// the form to post a new review



if(!$userSession || $userPermission < 1)

{

	header("Location:index.php");

}

?>



</script>

<style type="text/css">

#post_form p label

{

	float:left;

	width:75px;

}



#post_form input:hover

{

	border:	2px solid yellow;

}

</style>

<h3 class="clean">Post Your Reivew:</h3>

<p class="clean" style="padding-bottom:30px;">Let the unwashed masses be struck in awe by your mindbending review.</p>

<p style="font-size:0.7em;">It is <span style="color:red;">HIGHLY</span> recomended that you write your review in a <span style="color:red;">TEXT EDITOR</span> such as (<span style="color:red;">NOTEPAD</span>) before submitting your post through this form. There may be something you missed and you probably don't want to rewrite your whole post from memory.</p>

<form action="index.php" method="post" id="post_form" name="post_form" onSubmit="return ValidateFields()" enctype="multipart/form-data">

	<p class="clean" style="float:left;width:250px;"><label>Title:</label> <input type="text" name="title" id="title" /></p>

    <p class="clean" style="float:left;width:390px;"><label>Genre:</label> <input type="text" name="genre" id="genre" /></p>

    <div style="clear:both; height:0;">&nbsp;</div>

    <p class="clean" style="float:left;width:250px;"><label>ESRB:</label> 

    	<select name="esrb" id="esrb">

            <option value="E">Everyone</option>

            <option value="E10">Everyone 10+</option>

            <option value="T">Teen</option>

            <option value="M">Mature</option>

            <option value="AO">Adult Only</option>

        </select>

     </p>

     <p class="clean" style="float:left;width:390px;"><label>Score:</label>



<select id="score" name="score"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option><option value="32">32</option><option value="33">33</option><option value="34">34</option><option value="35">35</option><option value="36">36</option><option value="37">37</option><option value="38">38</option><option value="39">39</option><option value="40">40</option><option value="41">41</option><option value="42">42</option><option value="43">43</option><option value="44">44</option><option value="45">45</option><option value="46">46</option><option value="47">47</option><option value="48">48</option><option value="49">49</option><option value="50">50</option><option value="51">51</option><option value="52">52</option><option value="53">53</option><option value="54">54</option><option value="55">55</option><option value="56">56</option><option value="57">57</option><option value="58">58</option><option value="59">59</option><option value="60">60</option><option value="61">61</option><option value="62">62</option><option value="63">63</option><option value="64">64</option><option value="65">65</option><option value="66">66</option><option value="67">67</option><option value="68">68</option><option value="69">69</option><option value="70">70</option><option value="71">71</option><option value="72">72</option><option value="73">73</option><option value="74">74</option><option value="75">75</option><option value="76">76</option><option value="77">77</option><option value="78">78</option><option value="79">79</option><option value="80">80</option><option value="81">81</option><option value="82">82</option><option value="83">83</option><option value="84">84</option><option value="85">85</option><option value="86">86</option><option value="87">87</option><option value="88">88</option><option value="89">89</option><option value="90">90</option><option value="91">91</option><option value="92">92</option><option value="93">93</option><option value="94">94</option><option value="95">95</option><option value="96">96</option><option value="97">97</option><option value="98">98</option><option value="99">99</option><option value="100">100</option></select> %</p>

         <div style="clear:both; height:0;">&nbsp;</div> 

    <p class="clean"><label>Platforms:</label> <input type="text" name="platforms" id="platforms" /></p>

    <p> 

        <div class="formatPostButtons">

            <a href="javascript:addStrong(document.getElementById('review'))" title="Add bold text"><strong>B</strong></a><a href="javascript:addEm(document.getElementById('review'))" title="Add emphasised italic text"><em>I</em></a><a href="javascript:addUnderline(document.getElementById('review'))" title="Add underlined text"><span style="text-decoration:underline">U</span></a><a href="javascript:addImage(document.getElementById('review'), document.getElementById('images'), 'left')">Image [L]</a><a href="javascript:addImage(document.getElementById('review'), document.getElementById('images'), 'right')">Image [R]</a>

        </div>

        <div style="clear:both; height:1px;">&nbsp;</div>

    <textarea cols="90" rows="7" name="review" id="review"></textarea></p>

    <p><textarea cols="50" rows="3" name="images" id="images" disabled></textarea></p>

    <p><input type="submit" value="Proceed" />

        <input type="hidden" name="q" value="Addpost" />

        <input type="hidden" name="p" value="Admin" /></p>

</form>

And here is my script that adds the review to the database
PHP:
<?PHP

// addpost.php

// Inserts a post into the database



// include the form_data class

include("Scripts/FormData.class.php");



$formData = new reviews_Scripts_FormData();						// Create a new instance of the form_data class

// Get all inputs as array

$vars = array('title'    => $_POST['title'],

			  'genre'    => $_POST['genre'],

			  'esrb'     => $_POST['esrb'],

			  'score'    => $_POST['score'],

			  'platforms'=>$_POST['platforms'],

			  'review'   => $_POST['review']);

// Create an array to hold user errors

$errors = array();



// Check for empty

$errors = $formData->checkEmpty($vars,$errors);



// Check for valid length

$errors = $formData->checkLength($vars['title'],1,400,$errors,"title");	// Check title length

$errors = $formData->checkLength($vars['genre'],1,400,$errors,"genre");	// Check genre length

$errors = $formData->checkLength($vars['esrb'],1,3,$errors,'esrb');		// Check esrb rating length

$errors = $formData->checkLength($vars['platforms'],1,500,$errors,'platforms');

// Replace enter presses with a \n so the database and showing thread formats it correctly

$pattern = "/  /";

$vars['review'] = preg_replace($pattern,"\n",$vars['review']);

$vars['review'] = nl2br($vars['review']);

$vars['review'] = stripslashes($vars['review']);



// If there were errors, format and display them

if ($errors) {

	$formData->userErrors($errors);

} else {

	try	{

		// insert into the database

		$insertPost = $dbh->prepare("INSERT INTO reviews(id,title,genre,esrb,score,review,platform,date,user_ID)

							  VALUES(0,:title,:genre,:esrb,:score,:review,:platforms,:date,:user_ID)");

			$insertPost->bindValue(":title",$vars['title']);

			$insertPost->bindValue(":genre",$vars['genre']);

			$insertPost->bindValue(":esrb",$vars['esrb']);

			$insertPost->bindValue(":score",$vars['score']);

			$insertPost->bindValue(":review",$vars['review']);

			$insertPost->bindValue(":platforms",$vars['platforms']);

			$insertPost->bindValue(":date",Date("Y-m-d"));

			$insertPost->bindValue(":user_ID",getID($dbh,$userSession));

		$insertPost->execute();

		

		echo '<p>Your post was added to the database.</p>';

		

		echo '<p><a href="Index.php">Go Home</a></p>';

	} catch(PDOException $error) {

		recordErrors("admin/addpost.php",$error->getMessage(),"Unable to add post to database",uniqid());

	}

}
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
There is sort of a generic answer for PHP (basically the information in "Handling file uploads", "How do I create arrays in a HTML <form>?" and "File input (or “upload”) in HTML forms", all of which you should read), but that PHP was being used wasn't established in the first post.

The short version is:
  • Use inputs of type "file". Use array syntax for their names.
  • I suggest putting the file inputs in an ordered list.
  • Use JS to create/delete file inputs and any other needed HTML elements. If you're using an ordered list, this includes the <li>. With jQuery, this is trivial.
  • Server side, access file information via the $_FILES superglobal. Some of this information (such as the name and type) comes from the request, which means it's user input and not to be trusted.
  • Use move_uploaded_file server-side to store the uploaded file more permanently.

Your form already has the correct enctype for file upload.

Example using jQuery provided by the Google Libraries API:
HTML:
<script type="text/javascript" src="https://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<!-- Use most recent version in 1.6 branch -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

<form method="post" enctype="multipart/form-data" ...>
  ...
  <ol id="images">
    <li><input class="add" value="+" type="button" /><input class="del" value="-" type="button" disabled /><input type="file" name="foo[]" /></li>
  </ol>
  ...
</form>

<script type="text/javascript">
  $('form .add').live('click', function (evt) {
      var $item = $(this).parent();
      $item.after($item.clone());
      $('#files .del').attr('disabled', false);
  });
  $('form .del').live('click', function (evt) {
      var $item = $(this).parent();
      var $sibs = $item.siblings();
      if ($sibs.length) {
          $item.remove();
          if ($sibs.length == 1) {
              $('#files .del').attr('disabled', true);
          }
      }
  });
</script>

An alternative is to allow posters to link to external images rather than storing them on your server by allowing the <img> tag in posts, though you'll need to prevent XSS attacks via img attributes. Also, this may result in your site hotlinking to sites that don't appreciate it. You may wish to limit image hosting to pre-approved image hosting sites, such as photobucket, flickr, imgur, imageshack and tinypic.

There are many other X10 threads on uploading multiple files; look over them.

By the way, kudos on using a prepared statement.
 
Last edited:
Top