Prevent empty form input array from being posted?
Posted
by user355295
on Stack Overflow
See other posts from Stack Overflow
or by user355295
Published on 2010-06-01T11:08:06Z
Indexed on
2010/06/01
11:23 UTC
Read the original article
Hit count: 180
php
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.)
© Stack Overflow or respective owner