AsTheWormTurns
AsTheWormTurns

Reputation: 1316

Writing to a PHP file using PHP code?

Is it possibile to write a regular PHP file using the PHP language itself?
Is it the same as writing a .txt file?
Or is there something else I should know?

Whenever I save a record into a database, I want to overwrite the same file myConfig.php and it should contain something like this:

<?php

     $myVar = "myValue";

?>

Upvotes: 3

Views: 3126

Answers (2)

Asaph
Asaph

Reputation: 162851

Writing php files is no different than writing other text files. One way to accomplish this is with file_put_contents(). Something approximate like this should work:

file_put_contents('myConfig.php', "<?php

    \$myVar = \"myValue\";

?>");

You'll have to make sure that the user that php is running as has permissions to write the file in the given directory. This is a common pitfall. Check your error logs for permissions errors if it's not working.

On a side-note, dynamically writing php code based on loading data from a database can lead to security vulnerabilities. Specifically, it may allow a malicious user to inject arbitrary php code into your system and execute it. This is especially true if the data in the database comes from web forms that users fill out. Be very careful. Validate, sanitize, and properly encode all your dynamic values. The best thing actually would be to step back and reconsider your design. Do you really need to dynamically write these config files as php files? Can you use ini files instead? (hint: parse_ini_file()). Or can you simply use the config values from the database directly without writing a file?

Upvotes: 13

biziclop
biziclop

Reputation: 14626

If your permissions are right, it should work nicely:

<?php
file_put_contents('selfwrite2.php',<<<END
<?php echo "Hello World!";
END
);
include 'selfwrite2.php';

Upvotes: 3

Related Questions