tags:

views:

55

answers:

2

Sorry if this has been answered somewhere; I'm not quite sure how to phrase the problem to even look for help.

Anyway, I have a form with three text input boxes, where the user will input three song titles. I have simple PHP set up to treat those input boxes as an array (because I may want, say, 100 song titles in the future) and write the song titles to another document.

<form method="post">
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<button type="submit" name="submit" value="submit">Submit</button>
</form>

<?php
if (isset($_POST['submit'])) {
   $open = fopen("test.html", "w");

   if(empty($_POST['songs'])) { }
   else {
      $songs = $_POST['songs'];
      foreach($songs as $song) {
         fwrite($open, $song."<br />");
      };
   };
};
?>

This correctly writes the song titles to an external file. However, even when the input boxes are empty, the external file will still be written to (just with the <br />'s). I'd assumed that the if statement would ensure nothing would happen if the boxes were blank, but that's obviously not the case.

I guess the array's not really empty like I thought it was, but I'm not really sure what implications that comes with. Any idea what I'm doing wrong?

(And again, I am clueless when it comes to PHP, so forgive me if this has been answered a million times before, if I described it horribly, etc.)

A: 

you should check each entry:

<?php
if (isset($_POST['submit'])) {
   $open = fopen("test.html", "w");

   foreach($_POST['songs'] as $song) {
       if(!empty($song)) {
           fwrite($open, $song."<br />");
      };
   };
};
?>
Flexx
Oh, so simple, haha. Thanks!
I personally wouldn't use empty() as it is so forgiving when it comes to values it decrees as being empty: for instance, a string of "0" will be evaluated as true by empty() - it is unlikely that a song title would be "0" on its own, but because it COULD happen, I'd be minded to use a simpler if(trim($song) !== '') conditional.
Adam Hepton
Good point, thank you!
+1  A: 

Indeed $_POST['songs'] is not an empty array, it's an array of 3 empty strings. You can use the following to clear out all the empty values:

$song_titles = array_filter($_POST['songs'], function($title) {return (bool) trim($title);});

You could also put some other checks into that callback function (whitelist only alphanumerics and some other characters (spaces, dashes etc)).

If you have a version of PHP older than 5.3 you'll have to define the callback function separately, see http://us2.php.net/manual/en/function.array-filter.php

Sid