I'm working at a project right now, which is a very simple database-application. There are some php files which the user should upload. Then he calls a specific file - let it be install.html, where he should enter his root and password for accessing the server. Then a database and some tables will be created. Now, there are other files, for which this information is also needed. I thought about including a connect.php. But here's the question: Is it possible to edit the root and password in this connect.php through another php file? If not, do you know any other user-friendly way of avoiding this problem?
-
2Depends on what is in the file. Can you post any code?afuzzyllama– afuzzyllama2012-11-03 14:58:52 +00:00Commented Nov 3, 2012 at 14:58
-
You mean allowing users to upload and/or change PHP scripts? Your server will be in great danger.Alvin Wong– Alvin Wong2012-11-03 15:24:08 +00:00Commented Nov 3, 2012 at 15:24
-
But how should i handle this probleme? Either i allow the user to change it this way, or he should change the data in the .php file on itself, which isn't really user-friendly, isn't it?Eddi– Eddi2012-11-03 15:42:28 +00:00Commented Nov 3, 2012 at 15:42
2 Answers
Sure you can do that. The general idea is that you 've got a string with placeholders (e.g. like "{{username}}" and "{{password}}") that you replace with the correct values with str_replace and then write the contents to the file with file_put_contents.
The string with the placeholders can either be declared in your script as a string or you can read it from a file with file_get_contents. So you could have:
$replacements = array(
'{{username}}' => 'root',
'{{password}}' => '123456',
);
$config = file_get_contents('config.php');
$config = str_replace(array_keys($replacements),
array_values($replacements),
$config);
file_put_contents('config.php', $config);
1 Comment
connect.php has the right permissions (to be written to).A PHP file is just a text file. Like you can change a text-file with PHP you can also change a PHP file with PHP. Which is just standard file-io, see FilesystemDocs.
Ensure you have got access to the file and it is readable. Also consider to educate users after they used your install script how they can harden their setup. PHP files should be read-only in a hosting environment because of security reasons.