-2

I'm new in File handling. So I was wondering how would I go about to write a php file with php?

Let's say I want to make a php script which creates a file which contains the following code:

PHP File TO be Created

<?php
$item = "takes a variable from current file and put it here";
?>

Let's say I have a php which took the following from my form:

Code which takes a variable and writes it to another php file, exactly as it is

<?php
$item = $_GET['shirts'];

//Code which writes to Php File above
?>

I have no idea how to do this. Please be very explicit when you explain. Thanks :)

10
  • 1
    us2.php.net/manual/en/book.filesystem.php Commented Nov 20, 2013 at 19:46
  • you want to use functions like fwrite etc so write contents to files. see that link above ^^ Commented Nov 20, 2013 at 19:46
  • generally a bad idea to write a php file with php. Commented Nov 20, 2013 at 19:46
  • 3
    Generating executable php code based on user input - is very bad idea. Just saying. Commented Nov 20, 2013 at 19:46
  • 1
    Ok, and do read these two articles owasp.org/index.php/Top_10_2013-Top_10 and stackoverflow.com/q/60174/1415724 they will surely help. Commented Nov 20, 2013 at 19:51

2 Answers 2

2

Like this:

$var='that';
file_put_contents('newfile.php','<?php echo "thisthat' . $var . '"; ?>');

Note that if $var is coming from user input in any way you will need to be extremely careful to sanitize it so a hacker can't just do anything he wants on your server.

Documentation for file_put_contents here: php.net/file_put_contents

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

Comments

1
file_put_contents('fileToCreate.php', '<?php' . "\n" . '$item = "' . $item . '";' . "\n" . '?>')

viz here: php.net/file_put_contents

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.