-4

How can I write data to a file with PHP?

Here is an example of what needs to be written:

    $filename = 'test.txt';
    $keysize = '2048';
    $dname = 'www.domain.com';

The end result of the test.txt file should look like this

[ req ]
bits = 2048
domain_name = www.domain.com
user3436467
  • 1,763
  • 1
  • 22
  • 35
  • Use `file_put_contents`. – Barmar Apr 25 '15 at 11:47
  • possible duplicate of [PHP write file from input to txt](http://stackoverflow.com/questions/14998961/php-write-file-from-input-to-txt) – FanaticD Apr 25 '15 at 11:48
  • Since my last comment was removed I have to say it this way: `We can only give you links, but at the end you have to read/learn it! We can't learn for you!` – Rizier123 Apr 25 '15 at 11:57
  • possible duplicate of [How to write into a file in PHP?](http://stackoverflow.com/questions/1768894/how-to-write-into-a-file-in-php) – Cristik Apr 25 '15 at 12:06

2 Answers2

1

Use file_put_contents

$output = "[ req ] \nbits = $keysize\ndomain_name = $dname";
file_put_contents($filename, $output);

\n makes a new line. I can put $keysize etc in the string itself because I'm using " to make the string - it would not work with '. See this relevant SO question: What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
enigma
  • 3,476
  • 2
  • 17
  • 30
-1

PHP Script is:

<?php
$output = "[ req ]"."<br>";
$output .= "bits = ".$keysize."<br>";
$output .= "domain_name = ".$dname."<br>";
$handle = fopen($filename , 'w');
$write =  fwrite($handle, $output);
fclose($handle);
?>
Sagar
  • 642
  • 3
  • 14