将字符串从一个PHP脚本传递到另一个PHP脚本而不带链接


Passing a string from one PHP script to the other without the link

我有一个字符串,我在script1.php中评估。我需要将这个字符串传递给script2.php。我不想嵌入字符串到URL,然后传递。还有别的办法吗?

解决这个问题有不同的可能性。第一个是GET。(例如链接,甚至通过curl或AJAX隐藏。使用curl, PHP执行调用。使用AJAX,调用在服务器上完成,以便用户可以在源代码中看到字符串)


文章

第二种方法是通过POST。

用script1.php创建一个HTML表单,并让它将响应发送到script2.php

<form method="post" action="script2.php">
   <input type="hidden" name="myString" value="myValue" />
   <input type="submit" style="/*you can stile me like a link*/" value="Click me" />
</form> 

现在您可以在script2.php中使用这个字符串,如下所示

<?php
  $myString = null;
  if(isset($_POST['myString')) $myString = $_POST['myString'];
?>

文件

如果这两个脚本在同一台服务器上,您可以使用一个文件。在这种情况下,每个请求都将看到创建的字符串script1.php。

<?php
  $myString = "myValue";
  file_put_contents("myString.txt", $myString);
?>

现在script2.php可以读取文件的内容并使用它。

<?php
  $myString = file_get_contents("myString.txt");
?>

数据库/其他应用程序或后台worker

另一种可能性(与文件非常相似)是在数据库中存储字符串的方式。然后,您可以再次读取该值并在script2.php中使用它。如果您可以访问全局数据库,您甚至可以像GET或POST一样将字符串从一台服务器分发到另一台服务器。

您甚至可以启动一个本地应用程序(使用exec函数)来为您存储信息。然后可以再次执行Script2.php以获取新应用程序

的值
<

饼干/strong>

当然你可以将字符串保存在Cookie中。如果浏览器允许,可以使用script2.php

读取

script1.php

<?php
  $myString = "myValue";
  setcookie('MyString', $myString);
?>

script2.php

<?php
  $myString = null;
  if(isset($_COOKIE['MyString'])) $myString = $_COOKIE['MyString'];
?>

使用此解决方案,您的数据存储在客户端。如果用户愿意,他可以查看、更改和操作数据。另一方面,您可以节省服务器上的存储空间。


本地存储

与cookie类似,您可以使用JavaScript代码将数据存储在本地存储中。本地存储仅位于客户端。如果要获取script2.php上的数据,则必须通过AJAX调用它。现在可以处理数据了。

script1.php

<?php $myString = "myValue"; /*Be careful. your string must not contain ' otherwise you have to escape it!*/ ?>
<script type="text/javascript">
  localStorage.setItem('myString', '<?php echo $myString; ?>');
</script>

script2.php

<?php
  if(!isset($_GET['myString'])){
?>
<div id="content"></div>
<script type="text/javascript">
  var xhReq = new XMLHttpRequest();
  xhReq.open("GET", "script2.php?myString="+localStorage.getItem("myString"), false); //Be careful! You have to urlescape the value if necessary
  xhReq.send(null);
  var serverResponse = xhReq.responseText;
  document.getElementById("content").innerHtml = serverResponse; //Be careful. Escape HTML Tags if necessary here
</script>
<?php
  }
  else{
    $myString = $_GET['myString'];
  }
?>

<

会话/strong>

通常的方法是会话。这将机器上的本地存储(如文件)与参数方法(COOKIE、GET或POST)结合在一起。信息以某个ID存储在服务器上。此ID通过参数方法从一侧传递到另一侧。

script1.php

<?php
  session_start();
  $myString = 'myValue';
  $_SESSION['myString'] = $myString;
?>

script2.php

<?php
  session_start();
  $myString = null;
  if(isset($_SESSION['myString'])) $myString = $_SESSION['myString'];
?>

如果你使用外部程序,肯定会有更多。如果可以通过外部库获得Websockets,则可以使用它们。

但是:你不能在无限循环中使用GET, POST, SESSION。我建议使用外部应用程序或文件代替。因为PHP在一个脚本中立即处理每个请求。如果你能给我更多关于你的"频繁循环"的信息,我可以试着帮你找到一个解决这个特殊问题的方法。