将变量保存到php文件中


Saving variables to php file

我被这个问题卡住了,代码工作正常,但不会将变量传递/保存到新创建的"sample.php"文件中。

<?php
$id = 3;
$name = "John Smith";
$myfile = fopen("sample.php", "w") or die("Unable to open file!");
$txt = "
  <?php
  // Start the session
  session_start();
  // Set session variables
  $_SESSION['"user'"] = $id;            // integer variable
  $_SESSION['"name'"] = '"$name'";  // string variable
  header('Location: home/start.php');
  ?>
";
fwrite($myfile, $txt);
fclose($myfile);
?>

您只需正确插入变量

$txt = '
  <?php
  // Start the session
  session_start();
  // Set session variables
  $_SESSION["user"] = '.$id.';     
  $_SESSION["name"] = "'.$name.'";  
  header("Location: home/start.php");
?>';

单引号确保您的会话变量不会在字符串中进行插值,并且只有$id$name进行

Fiddle

输出

 <?php
  // Start the session
  session_start();
  // Set session variables
  $_SESSION["user"] = 2;     
  $_SESSION["name"] = "John";  
  header("Location: home/start.php");
?>

您就快到了,只需在会话变量上转义$即可。

$str = "'$_SESSION['foo']";

否则Php将尝试在字符串中替换它们。

试试这个,使用单引号来舍入变量

 $id = 3;
$name = "John Smith";
$myfile = fopen("sample.php", "w") or die("Unable to open file!");
$txt = '
  <?php
  // Start the session
  session_start();
  // Set session variables
  $_SESSION["user"] = '. $id . ';  // integer variable   
  $_SESSION["name"] = "'. $name . '";  // string variable
  header(''Location: home/start.php'');
?>';
fwrite($myfile, $txt);
fclose($myfile);

Solved-我发现php中的开括号和闭括号必须被解析为变量才能真正包含在新文件中。感谢您的报价帮助!

<?php
$id = 3;
$name = "John Smith";
$open = "<?php";
$close = "?>";
$myfile = fopen("sample.php", "w") or die("Unable to open file!");
$txt = '
 '.$open.'
 // Start the session
 session_start();
 // Set session variables
 $_SESSION["user"] = '.$id.';
 $_SESSION["name"] = "'.$name.'";
 header("Location: home/start.php");
 '.$close.'
';
fwrite($myfile, $txt);
fclose($myfile);
?>

输出到sample.php:

<?php
// Start the session
session_start();
// Set session variables
$_SESSION["user"] = 3;
$_SESSION["name"] = "John Smith";
header("Location: home/start.php");
?>