3

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";

?>
4
  • 4
    What happened when you tried? Commented Dec 5, 2011 at 18:32
  • I must admit I have not tried: basicly because I thought it was different from writing a regular txt file. It was a good idea asking because I was creating my files with fopen etc., while file_put_contents is more compact. Commented Dec 5, 2011 at 18:34
  • @AsTheWormTurns: Try first, ask later. Thanks Commented Dec 5, 2011 at 18:43
  • @Tomalak Geret'kal: you're right, and generally is what I do. If you want to crucify me... :-) Commented Dec 5, 2011 at 18:51

2 Answers 2

13

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?

Sign up to request clarification or add additional context in comments.

2 Comments

I suppose thats a better answer than just saying "yes".
@Asaph: do we need a slash before $myVar too?
3

If your permissions are right, it should work nicely:

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

1 Comment

Sick but I love it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.