-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 :)

Please Delete me
  • 807
  • 2
  • 10
  • 15

2 Answers2

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

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
1
file_put_contents('fileToCreate.php', '<?php' . "\n" . '$item = "' . $item . '";' . "\n" . '?>')

viz here: php.net/file_put_contents

Anagmate
  • 1,825
  • 3
  • 16
  • 15