Jump to content

Replace A String In File


dakke
 Share

Recommended Posts

Hi all,Probably very easy for you guys, for a newbie... not really.I try to replace a string in a file through ftp. Not sure how it should be done.I assume you have to open the file, than str_replace and than save the file again? The following is probably completely wrong, and as such to show how far I am from the solution. :)

<form method="post"><input name="db_name" type="text" /><input type="submit" class="submit" value="Check database >>" /></form><?php$db_login = "../includes/db_login.php";$fh1 = fopen($db_login, 'w');$str = str_replace("test", $db_name, $str);?>

Where I try to replace 'test', with $db_name in the file "db_login.php", using the $db_name coming from the form.

Link to comment
Share on other sites

You should be able to just use file_get_contents and file_put_contents, e.g.

<form action="" method="post"><input name="db_name" type="text" /><input type="submit" class="submit" value="Check database >>" /></form><?phpif (isset($_POST['db_name'])) {$db_login = "../includes/db_login.php";$fh1 = file_get_contents($db_login);$str = str_replace("test", $_POST['db_name'], $str);file_put_contents($db_login, $str);}?>

Note: this doesn't use FTP, and you shouldn't need FTP either.Note 2: you should perform some sort of sanitizing on the form field, or else someone could insert arbitrary PHP into your file.

Link to comment
Share on other sites

You should be able to just use file_get_contents and file_put_contents, e.g.
<form action="" method="post">Thanks for the quick reply.I always get a blank file using the above. When I submit, the entire file's content is deleted and not replaced. It does not replace, it deletes. What am I doing wrong?
Link to comment
Share on other sites

Eh, logical error, the return value of file_get_contents() should be assigned to $str.

<form action="" method="post"><input name="db_name" type="text" /><input type="submit" class="submit" value="Check database >>" /></form><?phpif (isset($_POST['db_name'])) {$db_login = "../includes/db_login.php";$str = file_get_contents($db_login);$str = str_replace("test", $_POST['db_name'], $str);file_put_contents($db_login, $str);}?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...