0

I have form:

<form method="post">
<textarea name="add" cols="50" rows="20"></textarea>
<br>
<input type="submit" formaction="make.php" value="MAKE"><br><br><br>
</form>

I post few rows using this form such as:

lala
lalal12
blabla

Also I have big txt file words.txt. I need to take random 1000 rows from this file and put them into lala.txt, lalal12.txt, blabla.txt-1000 different random rows to each file. I tried to do:

<?php
$words = file_get_contents('words.txt');

$add = $_POST[add];

if (isset($add)) {
$arr = explode( "\n", $add); 
foreach($arr as $row)   {
    shuffle($words);
    $out = array_slice($words, 0, 1000);
    $out = implode("\n", $out);
    file_put_contents($row.'.txt', $out);
}
}

but it doesn't work. Please help me with it.

  • "It doesn't work good." Does it run? Does it crash/error out? – Nightfirecat Nov 07 '13 at 02:33
  • 1
    Also, I'd advise looking at similar questions: http://stackoverflow.com/questions/12406300/split-a-big-txt-file-with-php, http://stackoverflow.com/questions/10270162/read-through-huge-text-files-and-store-each-line-in-database, http://stackoverflow.com/questions/5391304/split-big-files-using-php – Nightfirecat Nov 07 '13 at 02:37
  • If it failed when writing then you might have an issue with write permissions. However, we cannot advise unless you can tell us if you're getting some sort of error. If you're getting a white screen of death add the following to the top of your file: ` – Darragh Enright Nov 07 '13 at 02:44
  • It is syntactically correct so I doubt there are any errors, however `$_POST[add]` should be `$_POST['add']` so that `isset($add)` returns `true`. – doublesharp Nov 07 '13 at 02:52

1 Answers1

1

Your code is not running because isset($add) is returning false. In the line $add = $_POST[add]; you are assigning $add to the value of a $_POST element with the value of the constant add, which does not exist. You need to wrap quotes around it to properly access the key value:

$add = $_POST['add']; // access the POST value for key "add"

This would also work, but isn't really the right way to do it, putting it here to highlight the your use of add as a constant:

define('add', 'add'); // set the constant add to the string value "add"
$add = $_POST[add];   // access the POST value
doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • iirc, using an undefined constant `add` as a key here just triggers a PHP notice. PHP will then assume that the user intended the string `'add'` - so `isset($add)` should actually return `true` here. assuming of course the key exists in `$_POST` in the first place. that said I completely agree that the OP should quote their keys. – Darragh Enright Nov 07 '13 at 03:24