0

I am getting a warning inside the browser debugger, but the PHP still works. Why am I getting a warning? Thanks in advance.

Warning: Invalid argument supplied for foreach().

HTML:

<form action="" method="post" name="savefile">
    <input id="uniqueID" value="ZF4446A3GZ" name="filename" type="text">
    <input name="textdata[]" type="text">
    <input name="textdata[]" type="text">
    <input name="textdata[]" type="text">
    <input value="Done!" name="submitsave" type="submit">
</form>

PHP:

<?php
if (isset($_POST)){
    foreach($_POST["textdata"] as $text){
        if(!file_exists($_POST['filename'] . ".txt")){
            $file = tmpfile();
        }
        $file = fopen($_POST['filename'] . ".txt","a+");
        while(!feof($file)){
            $old = $old . fgets($file);
        }
        file_put_contents($_POST['filename'] . ".txt", trim($text).PHP_EOL, FILE_APPEND);
        fclose($file);
    }
}
?>
KaveElite
  • 94
  • 9
  • check this, hope this will help u... https://www.euperia.com/development/fix-php-warning-invalid-argument-supplied-foreach/1230 and http://stackoverflow.com/questions/19983912/warning-invalid-argument-supplied-for-foreach-in-php – Aru Feb 10 '15 at 04:33

1 Answers1

1

This error happens because you're trying to iterate on a non-iterable variable.

Either $_POST["textdata"] is not set or is not an array ($_POST usually only holds scalars and arrays)

To prevent this error, you should check if $_POST["textdata"] is set and is an array.

if ( isset($_POST["textdata"]) && is_array($_POST["textdata"]) ) {
  //DO stuff
}
Tivie
  • 18,864
  • 5
  • 58
  • 77