通过 HTML 表单传递 PHP 变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18431638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:33:31  来源:igfitidea点击:

Pass a PHP variable value through an HTML form

phphtmlforms

提问by user2642907

In a html form I have a variable $var = "some value";.

在 html 表单中,我有一个变量$var = "some value";

I want to call this variable after the form posted. The form is posted on the same page.

我想在表单发布后调用这个变量。该表格张贴在同一页面上。

I want to call here

我想在这里打电话

if (isset($_POST['save_exit']))
{

    echo $var; 

}

But the variable is not printing. Where I have to use the code GLOBAL ??

但是变量没有打印。我必须在哪里使用代码 GLOBAL ??

回答by Charaf JRA

EDIT:After your comments, I understand that you want to pass variable through your form.

编辑:在您发表评论后,我知道您想通过表单传递变量。

You can do this using hidden field:

您可以使用隐藏字段执行此操作:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

在 PHP 操作文件中:

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

Or using sessions: In your first page:

或使用会话:在您的第一页中:

 $_SESSION['var']=$var;

start_session();should be placed at the beginning of your php page.

start_session();应该放在你的php页面的开头。

In PHP action File:

在 PHP 操作文件中:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

第一个答案:

You can also use $GLOBALS:

您还可以使用$GLOBALS

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentationfor more informations.

查看此文档以获取更多信息。

回答by Alex Rashkov

Try that

试试看

First place

第一名

global $var;
$var = 'value';

Second place

第二个地方

global $var;
if (isset($_POST['save_exit']))
{
    echo $var; 
}

Or if you want to be more explicit you can use the globals array:

或者,如果您想更明确,您可以使用 globals 数组:

$GLOBALS['var'] = 'test';

// after that
echo $GLOBALS['var'];

And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:

这是第三个选项,与 PHP global 无关,这是由于问题中缺乏清晰度和信息。因此,如果您有 HTML 格式的表单,并且想将“变量”/值传递给另一个 PHP 脚本,则必须执行以下操作:

HTML form

HTML 表单

<form action="script.php" method="post">
    <input type="text" value="<?php echo $var?>" name="var" />
    <input type="submit" value="Send" />
</form>

PHP script ("script.php")

PHP 脚本(“script.php”)

<?php

$var = $_POST['var'];
echo $var;

?>