Allow End Users to Add Images to Your Gallery

A common question I’ve seen on the WP forums – as well as other places – is the idea of allowing people to post images to your WordPress site. I’ve actually had two different clients of mine also request this feature: one wanted the images to be posted to a “showcase gallery,” while the other wanted commenters to leave images in the comments section when they contributed to discussions.

Although I don’t really recommend this, you can do it, and it’s really not that difficult.

First, I’m going to start with a disclaimer. The reason I don’t feel either of these options are a very good idea is because of – you guessed it – spammers. I you’re running, say, a “mom blog,” and you wanted moms to post pictures in the comments – how would you feel if one day you discovered a post form last year, covered in porn pics? Links to porn sites are one thing, but seeing actual graphic images brings on a whole lot of liability that should concern you. Having such images on your site most likely would violate your TOS with your hosting company – and out you’d go. Not to mention the bad publicity you’d get within your circle.

And let’s not forget the way you can embed JPG graphics with actual scripts – at one time (many moons ago) even Outlook was preventing JPGs from being viewed in your emails because people were exploiting this fact, and embedding malware in JPG images. (Honestly, I don’t know if this is an issue anymore – but I do recall at one time it was – and it was, in deed, several years ago, si it might be remedied by now.)

The point is, IF you want to do this, you MUST take some responsibility for your site, and be diligent about moderation. Dont’ think you can add this code and simply walk away and have it take care of itself. If you apply this, you MUST check often, and set stringent rules for your site to avoid situations like those mentioned above.

That being said, I will now share.

First, I’ll tell you how I did the “Allow Subscribers to Add Images to a Gallery.”

You’ll ant to start by getting a nice plugin for your images Gallery. My personal fave is NextGen (and the one I chose to use for the client that requested this ability). The reason I like NextGen is because it has a lot of options for how you display your galleries, and is highly customizable. (SimpleViewer is another good one, as well, if you’d like an alternative.) However, the reason I chose these gallery plugins for THIS is because it makes it really easy: you can upload images to a certain folder on your server, and have these galleries just connect to those folders and display what’s inside with the click of a button. No oneed to constantly go back and forth, trying to make your script recognize were new images are – it’s pretty much point and click, and you’re set.

So you want to install and configure your plugin to get the Gallery going, and set the page where you want the Gallery to appear. Don’t worry about choosing a folder right now – we’ll deal with that in just a moment.

After you’ve got the gallery installed and configured, you’ll also want to create folder that’s for the images to be uploaded to. You’ll want to FTP into your server, and in your WordPress installation you want to create your gallery folder for these submissions (in the same level as wp-content and wp-includes). This orm, by the way, uses the name “gallery_uploads” for the folder name – but you can use whatever you want. Just be sure to change it in the form if you use something different. You will also want to create a page so people can use the form (just go into your admin, and write a new Page. Title it whatever – but for purposes of example, we’ll call it “Gallery Submission,” which will have a page slug of “gallery-submission.”)

Now that we’re all set up, we need to create our form. This is actually the hard part, because I haven’t actually found a form plugin that’s ready to implement this, so you’re gonna have to hand-create one. Luckily for you, I have a secure PHP form that I’ve used for many clients for a while now, that I wrote myself. So I’ve already create the form for you. The code below basically creates a form that has the following fields:

1) End user’s Name
2) End user’s Email
3) Input field for the image on your computer (with a “browse” button)
4) Field to supply an image description

This form checks to be sure that no typical spammy activity takes place: it’ll check for XSS injection, as well as trying to use it as a zombie form to send out mass emails as you (it prevents that from happening). however it will *not* check for that annoying stuff where people insert a whole bunch of URLs – but it *does* check for the presence of “http:” or “[url]” – which is typical of spammy behavior. If either of those is inserted into the description field, it’ll reject the submission.

It also checks for “auto-submission” with the help of a little surprise. Basically, spammers “auto-submit” forms by filling out ALL input fields available. This form has a “surprise” field. I am a HATER of “CAPTCHA” – I detest those things. (I cannot express how much I hate CAPTCHA fields on forms.) personally, I feel that the spammer should be the one who has to work to fill out a form, not the legit end user. So what this field does is present an extra input field that the auto-submit will see and fill in. You, as a legitimate end-user, do not see it. (if you want to see it – then you can either disable your stylesheet, or view the source code. it’s right before the “submit” button.) If *any* input is placed in that field, then it’ll reject the submission as spam. (Said field also has accessibility in mind – if you’re using a screen reader, it’ll tell you to leave it empty.)

It also limits the image uploaded to 500KB, and restricts the file to GIF or JPG images only (so you don’t have to worry about people uploading documents or scripts).

So open up your functions.php file (if you don’t have one, make one) in a plain text editor, and paste the following code:

function bb_gallery_upload() {

// form fields
$form .= '<form method="post" action="' . $PHP_SELF . '" id="bb_contact" enctype="multipart/form-data">' . "\n";
$form .= "Please upload an image to submit to our gallery.<br /><small>Limits: filesize no larger than 500KB, JPG or GIF images only.</small><br /><br />" . "\n";
$form .= '<div class="form_field">' . "\n";
$form .= '<label for="name">Your Name:</label>' . "\n";
$form .= '<input class="form" type="text" id="name" name="fromname" value="' . stripslashes($_POST['fromname']) .'" />' . "\n";
$form .= '<hr class="clear" />' . "\n";
$form .= '</div>' . "\n\n";
$form .= '<div class="form_field">' . "\n";
$form .= '<label for="email">Your eMail:</label>' . "\n";
$form .= '<input class="form" type="text" id="email" name="fromemail" value="' . stripslashes($_POST['fromemail']) .'" />' . "\n";
$form .= '<hr class="clear" />' . "\n";
$form .= '</div>' . "\n\n";
$form .= '<div class="form_field">' . "\n";
$form .= '<label for="file">Your image:</label>' . "\n";
$form .= '<input class="form" type="file" id="file" name="file" />' . "\n";
$form .= '<hr class="clear" />' . "\n";
$form .= '</div>' . "\n\n";
$form .= '<div class="form_field">' . "\n";
$form .= '<label id="description" for="message">Please enter a description for your image.</label>' . "\n";
$form .= '<textarea rows="4" cols="10" id="message" name="comments">' . stripslashes($_POST['comments']) . '</textarea>' . "\n";
$form .= '</div>' . "\n\n";
$form .= '<div align="center">' . "\n";
$form .= '<label for="surprise" title="This field is to help prevent spam. Please do not place any input in this field. Doing so will cause the form stop functioning.">' . "\n";
$form .= '<input id="surprise" class="surprise" type="text" name="surprise" value="' . stripSlashes($surprise) . '" />' . "\n";
$form .= '<input type="hidden" name="action" value="sendmail" />' . "\n";
$form .= '<input class="button" type="submit" value="Submit" />' . "\n";
$form .= '</div>' . "\n";
$form .= '</form>' . "\n\n";

// get the Page URL
$pageURL = "http://" . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

// thank you message
$thanks .= "<h3 class=\"thankyou\">Thanks! Your submission has been received.</h3>";
$thanks .= "<p class=\"thankyou\">";
$thanks .= "We really appreciate the time you took out of your day to share your success with us. We'll review your submission, and if it meets our guidelines, we'll have it posted in our gallery for all to see.<br /><br />Have a great day!";
$thanks .= "</p>";

Now all of that contains your form field displays. It also contains some other information that’s needed later (like the $thanks variable is the thank-you message that’s seen when the transaction is successful.)

Next, you want to put in the good stuff for error messages:

// start the script
foreach($_POST as $k => $v);
$_POST[$k] = htmlentities($v);


isset($_POST['action']) ? $action = $_POST['action'] : $action = '';
isset($_POST['fromname']) ? $fromname = $_POST['fromname'] : $fromname = '';
isset($_POST['fromname_error']) ? $fromname_error = $_POST['fromname_error'] : $fromname_error = '';
isset($_POST['fromemail']) ? $fromemail = $_POST['fromemail'] : $fromemail = '';
isset($_POST['fromemail_error']) ? $fromemail_error = $_POST['fromemail_error'] : $fromemail_error = '';
isset($_POST['file']) ? $file = $_POST['file'] : $file = '';
isset($_POST['file_error']) ? $file_error = $_POST['file_error'] : $file_error = '';
isset($_POST['comments']) ? $comments = $_POST['comments'] : $comments = '';
isset($_POST['comments_error']) ? $comments_error = $_POST['comments_error'] : $comments_error = '';
isset($_POST['surprise']) ? $surprise = $_POST['surprise'] : $surprise = '';
isset($_POST['surprise_error']) ? $surprise_error = $_POST['surprise_error'] : $surprise_error = '';
isset($_POST['error']) ? $error = $_POST['error'] : $error = '';
isset($_POST['injection_error']) ? $injection_error = $_POST['injection_error'] : $injection_error = '';
isset($_POST['send']) ? $send = $_POST['send'] : $send = '';

This basically checks the fields for input and sets things up for you all nice and neat. IF you ever add any fields to your form, you’ll need to be sure you add in a corresponding line for that new field.

Now, let’s start the script:

if ($action != "sendmail") {
echo $form;
}

This basically tells the page that if the page is initially loaded, then just output the form, ready to accept input.

if ($action == "sendmail") {

Now we get into the goodies. If the submit button is pressed, we start checking. First, we start with the “Name” field. If it’s left empty, the following bit of code is what sets up the error message for the blank entry.

if ($fromname == "") {
echo "<span class=\"message\">You didn't enter your name.</span>" . "\n";
$send == "no";
}

Now we’ll heck the email field. If it’ left empty, or if the email format is incorrect, then it’ll return an error. (By the way, I know some of you have issues with email address checks that tell you a legit email is formatted incorrectly – so annoying. I know, I run into the same issue because I have several emaill addresses that are formatted like “firstname.lastname@domain.com” and the “.” throws it off. THAT kind of email will pass this check.)

if (!ereg('^[-!#$%&\'*+\./0-9=?A-Z^_`a-z{|}~]+'.'@'.'[-!#$%&\'*+\/0-9=?A-Z^_`a-z{|}~]+\.'.'[-!#$%&\'*+\./0-9=?A-Z^_`a-z{|}~]+$', $fromemail) || ereg("'", $fromemail)) {
echo "<span class=\"message\">You didn't enter your email address, or it was in the wrong format.</span>" . "\n";
$send = "no";
}

Now, let’s get the image input:

if ((($_FILES["file"]["type"] == "image/gif") ||
($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/pjpeg")) &&
($_FILES["file"]["size"] < 500000)) {
if ($_FILES["file"]["error"] > 0) {
echo "<span class=\"message\">I'm sorry - there was an error with your upload. " . $_FILES["file"]["error"] . "</span>" . "\n";
$send = "no";
}
} else {
echo "<span class=\"message\">I'm sorry - this is an ivalid file format, or the filesize was too large.</span>" . "\n";
$send = "no";
}

As you can see, it calls for the image uploads path (if you change the name of the folder you created, then you’ll have to reflect that change here), and sets the filesize and type of image accepted.

And now the description field – this part simply checks to see if it’s left blank:

if ($comments == "") {
echo "<span class=\"message\">You didn't leave a message (that's kind of the point, isn't it?)</span>" . "\n";
$send = "no";
}

And now our “surprise” field for spammers:

if ($surprise != "") {
echo "<span class=\"message\">Spammy activity was detected. If you feel this is in error, please leave a comment on one of the posts - I'll see it and attend to the issue.</span>" . "\n";
$send = "no";
}

And now we tell the script what to do if the form is rejected (defines the $send = “no” part) – which is basically return the form again, but with error messages displayed.

if ($send == "no") {
echo $form;
return;
}

Now we get into the second round of checks – we want to be sure there’s certain characters and activity that is *really* checked for spaminators. The above code does checks based on the assumption that input is legitimately messed up, and provides nice error messages for those boo-boos. This part isn’t so nice. It checks for outright spammy activity -something you can pretty much guarantee that your average end user will input in a field unless they are actually trying to hijack your form. Feel free to change this error message to be as nasty as you please (personally, I try to keep it a little on the nice side, just in case a cat walked across someone’s keyboard or something!)

$find = array("/\r/", "/\n/", "/bcc\:/i", "/Content\-Type\:/i", "/cc\:/i", "/to\:/i", "/http\:/i", "/\[url/");
$test_fromname = preg_replace($find, "", $fromname);
$test_toname = preg_replace($find, "", $toname);

$find2 = array("/bcc\:/i", "/Content\-Type\:/i", "/cc\:/i", "/to\:/i", "/http\:/i", "/\[url/");
$test_comments = preg_replace($find2, "", $comments);

if ( ($fromname != $test_fromname) || ($toname != $test_toname) || ($comments != $test_comments) ) {
echo "<span class=\"message\">Sorry, but one - or more - of your entries is using spam-related content. This form detects such activity - including injection attempts of several forms. Sad to say, \"normal\" people wouldn't use such characters in normal message-sending formats, so I'm going to have to assume you're an evil, bad person.<br /><br />Go away.<br /><br />Of course, if I'm incorrect, then please leave a comment on one of my posts, and I'll try and fix the issue, and you have my apologies.</span>" . "\n";
echo $form;
return;

Now if the submitted form actually passes all of these checks, then we proceed to successful submission:

} else {
if (file_exists("./gallery_uploads/" . $_FILES["file"]["name"])) {
echo "\"" . $_FILES["file"]["name"] . "\" already exists. Please try a different file, or renaming this one before uploading. Click the \"Back\" button in your browser window to try again.";
return;
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "./gallery_uploads/" . $_FILES["file"]["name"]);

Of course, there’s a single extra check here (because the server can’t check for filesize unless an attempt at uploading is actually tried, and it won’t try if any of the other fields have an issue). But if it’s okay then…

$message = nl2br("
From: $fromname ($fromemail)

You've had a submission to the image gallery on your site.

Image Description: $comments

");
$message = stripSlashes($message);

$mailheader = "From: $fromname <$fromemail>\nContent-Type: text/html";
mail("NAME <EMAIL>", "$subject", "$message", "$mailheader");
}
}

This section actually submits the image to the folder you’ve created AND emails you a notification that someone has submitted an image to your gallery. Right there, in the “mail()” section, where it says “NAME” and “EMAIL”, you need to put in your name and email address. Any time someone submits an image to your uploads folder, you will be notified immediately.

Now we thank them for the successful submission and close out the script.

{
echo $thanks;
return;
}

} // end "action = sendmail" section

} // end contact form

Once you’ve done all that, you can add it to your site by opening up the theme file for the page display and adding in the call to the form. Now, if you’re using a specific Page template file, then you can just add the code into it. But most people don’t do that – instead they use a plain “page.php” or even “index.php” file for the display of the content. So you need to open up that file and put in:

<?php if(is_page('gallery-submission') {
bb_gallery_upload();
} ?>

in place of (or beneath, if you want to put in your own text content above the form) <?php the_content(); ?>.

Now, when you navigate to your gallery submission page, there’s your form.

To get the images to display in your Gallery, you’ll need to set up your Gallery to pull images from the uploads folder. NextGen (my first choice) is awesome, because you can set it up to look in that folder (in the settings) and if new images are put in, they’ll already be listed without extra effort. I’m pretty sure you can also set NextGen to not display images unless you’ve approved them first – so you will see them, but they have to be approved before they will be shown on your site. (SimpleViewer will have to have the XML file re-created before it’ll display anything, and I believe it’ll show them on your site when they become visible to you – so if something’s not approved, you’ll have to delete it quickly and rewrite the XML file again.)

Well, that was longer than I expected it to be! I’ll get the “comments” one later on, and sometime soon I’ll play with this a bit and give it an extra step of allowing only subscribed users to add to your gallery (instead of just anyone). It’s actually pretty simple to allow that – but I have a child in need ot a diaper change at the moment!

In the meantime, you can just snag the whole script here.

Comments

  • Adam S

    Shelly, how come you redeclare the PHP variable on each line and then concatenate? You could just have one “$form =” and then each line is appended with a dot. For example:

    $form = “\n”
    . “Line line here”
    . “Third line here.”;

    It’s good form and will be faster (by milliseconds, but still).

    Also, your mail function has “NAME” as an argument and no email, however, in this case, all you need is an email address as the first argument, not a name.

    March 30, 2009 at 7:24 am Reply
    Show/Hide Replies
    • Shelly

      Hi Adam :)

      Why do I do that? I don’t know, in all honesty! Maybe because I’m a little OCD and I like to make things “pretty” and have them line up perfectly? Honestly, I never really even thought about it. But that’s an excellent suggestion!

      As for the “name/email” thing…I’m not clear on what you’re saying – I apologize. OH wait! I see – yes, I missed a tag when showing the code on the site (the browser is parsing it fo’ real instead of displaying the code.) If you look at the linked file, it’s definitely there, but thanks for the tip…it’s fixed now :)

      March 30, 2009 at 7:37 am Reply
  • Have your say:

    * Copy this password:

    * Type or paste password here:

    1,815 Spam Comments Blocked so far by Spam Free Wordpress