-1

i have a txt file containing 20 lines i want to replace line # 4 with a new text from an input ...i have tried this and some others but not solving my problem. PHP Code

<?php 
if(isset($_POST['submit'])){

$selected_file = $_POST['files'];
$line = $_POST['to_line'];
$text = $_POST['text'];


//opn file 
$file_open = fopen($selected_file,"r+") or die('Fail to open a file');
//fwrite($file_open,$text);


$file_array = file($selected_file);
$file_array[$line] = $text;
$file_array = implode($file_array);
file_put_contents($selected_file,$file_array);

?>

HTML

<form name="write" method="post" action="">
<table>

<tr><td>Select File</td><td><select name="files" style="width:183px;">
<?php



 foreach ($a = scandir('.') as $file){
    $extension = pathinfo($file, PATHINFO_EXTENSION);
   if($extension == 'txt' || $extension == 'doc'){
 echo"<option>".$file."</option>";
 }}


?>

></select></td></tr>
<tr><td>Line</td><td><select name="to_line" style="width:183px">

<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
</td></tr>
<tr><td>Write Text</td><td><textarea name="text" style=" height:120px" ></textarea></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Save" /></td></tr>


</table>
</form>

what i want i want to select a value from drop-down list (line #) and that whole line will be replace with the new text.

Community
  • 1
  • 1
Khan
  • 43
  • 1
  • 8
  • Where exactly does it fail? Did you debug the source code? – RhinoDevel Mar 08 '16 at 11:43
  • it just add the text to the end of the line. i want to replace that whole line with new text. – Khan Mar 08 '16 at 11:45
  • Because you're imploding [0] with [5] and as it's only 2 items, it's adding to the end, you need to explode the file before assigning data to a certain element. Also be aware that [4] does not mean line 4, it's line 5. – James Lalor Mar 08 '16 at 11:49
  • this code is not works...give me another code example to solve it...if possible.!!! – Khan Mar 08 '16 at 11:54

1 Answers1

0

try below solution also make sure file have write permission:

if(isset($_POST['submit'])) {

    $selected_file = $_POST['files'];
    $line = $_POST['to_line'];
    $text = $_POST['text'];

    $file_array = file($selected_file);
    $file_array[$line - 1] = $text."\n";
    $file_content = implode("", $file_array);
    $f = fopen($selected_file, 'w+') or die('unable to open');
    fwrite($f, $file_content);
    fclose($f);
}
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44