0

i need to find a line and change it to whatever user will type in input i didnt write this code pls help

<?php
$myfile = 'test.txt';
$lines = file($myFile, FILE_IGNORE_NEW_LINES);
$lines[4] = $_POST['title'];
file_put_contents($myFile , implode("\n", $lines));
?>

i tryed lot of ways but non of them works and i only have this code . i am working on project idea is simple user will give type url of website i need to find a line and change it to <form action="process.php" method="post"> i need help its will be on same line so i dont need to change line i searched lot of ways but does not works for me. i am starter at php so...

R.A
  • 61
  • 1
  • 5

1 Answers1

3

There is an error in your code.

$lines = file($myFile, FILE_IGNORE_NEW_LINES);

should be

$lines = file($myfile, FILE_IGNORE_NEW_LINES);

because you're declaring $myfile = 'test.txt';

Note the usage of smaller case f in file name.

Now, coming to your question.

You want to replace some lines in the file with user input.

Let's assume that you want to replace the text THIS SHOULD BE REPLACED. For that, you could use the code something line below:

<?PHP
$myfile = './test.txt';
$lines = file($myfile, FILE_IGNORE_NEW_LINES);

$textToBeReplaced = "THIS SHOULD BE REPLACED";

$index = array_search($textToBeReplaced, $lines);
if (false !== $index) {
    $lines[$index] = $_POST['title'] ?? '';
}
file_put_contents($myFile , implode("\n", $lines));
?>
 
ash__939
  • 1,614
  • 2
  • 12
  • 21