As stated in comment by deceze, its better to save your data in JSON format or var_export format rather than as php file. Maybe the OP thought that if it's saved in such format then it will be accessible from webserver root (e.g.: point your browser's address bar to https://example.com/htpassw_array.json will download the whole password, while point your browser's address bar to https://example.com/htpassw_array.php will only give you an empty page).
The solution is to save the JSON file outside webserver root path (e.g.: in /home/youruser or C:/Users/youruser).
Example:
<?php
$password = array(
'login1' => 'password1',
'login2' => 'password2',
'login3' => 'password3',
);
$myfile = fopen("/home/myuser/htpassw_array.php", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($password));
fclose($myfile);
Of course, the best option is to use a database (e.g.: mysql, postgres).
Then again, there is some use for php code to generate other php code (e.g.: writing CRUD generator). To prevent special commands/expressions to be interpreted, you can try:
- escaping them (e.g.: backslash):
$txt = "<?php \$passwords = array(
- separating them into more piece of string:
$txt = "<?php "."$"."passwords = array(
- switch double quote and single quote to prevent php from interpreting
$passwords
- or create a template then using string replace on them (this is an overkill in your use case)
Also, as deceze stated in comment, PHP doesn't double-interpret itself, so number 2 is not needed in this case
Example solution no 1 (escaping)
<?php
$txt = "<?php \$passwords = array(
'login1' => 'password1',
'login2' => 'password2',
'login3' => 'password3',
); ?>";
$myfile = fopen("htpassw_array.php", "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fclose($myfile);
Example solution no 2 (concatenating)
<?php
$txt = "<?php "."$"."passwords = array(
'login1' => 'password1',
'login2' => 'password2',
'login3' => 'password3',
); ?>";
$myfile = fopen("htpassw_array.php", "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fclose($myfile);
Example solution no 3 (double/single quote)
<?php
$txt = '<?php $passwords = array(
"login1" => "password1",
"login2" => "password2",
"login3" => "password3",
); ?>';
$myfile = fopen("htpassw_array.php", "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fclose($myfile);
Output file:
<?php $passwords = array(
'login1' => 'password1',
'login2' => 'password2',
'login3' => 'password3',
); ?>
When I run:
<?php
require_once("htpassw_array.php");
var_dump($passwords);
The output is:
array(3) {
["login1"]=>
string(9) "password1"
["login2"]=>
string(9) "password2"
["login3"]=>
string(9) "password3"
}