将变量保存到php文件中

4
我卡在这里了,代码正常工作但无法将变量保存到新创建的'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);

?>

你在那个字符串内部使用了双引号,所以它不能工作。 - Felipe Alarcon
你在这里尝试做什么?请告诉我你的目标。 - nitin jain
现在实际上什么都没有发生,是括号的问题吗? - Chris011001
4个回答

3
您只需要正确地插值变量即可。
$txt = '
  <?php
  // Start the session
  session_start();
  // Set session variables
  $_SESSION["user"] = '.$id.';     
  $_SESSION["name"] = "'.$name.'";  
  header("Location: home/start.php");
?>';

使用单引号可以确保您的会话变量不会在字符串中插值,只有$id$name会。

演示

输出

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

......而且我在今年圣诞节有了新的最好朋友....干杯,伙计!! :D - NoobEditor

2

你已经接近成功了,只需要在会话变量上加上反斜杠(\)即可。

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

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

0

尝试这个,使用单引号来包围变量

 $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);

无法让它正常工作。 - Chris011001
如果我删除 <?php 和 ?>,它会输出正确的结果,但另一方面,文件将没有 PHP 的开头和结尾括号。 - Chris011001

-1
解决了 - 我发现在 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");
?>

这是一种非常复杂的方式来完成一个简单的事情。你不必创建所有那些额外的行和变量。 - Hanky Panky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接