Detailed explanation of 9 superglobal variables in PHP (usage examples)

青灯夜游
Release: 2023-03-03 07:42:01
forward
3896 people have browsed it

Detailed explanation of 9 superglobal variables in PHP (usage examples)

Superglobal variables, introduced in PHP 4.1.0, are built-in variables that are always available in all scopes. Many predefined variables in PHP are "superglobal," meaning they are available throughout the entire scope of a script. They can be accessed within a function or method without executing global $variable;.

There are 9 commonly used super global variables:

1. $_GET –> get transmission method

2. $_POST –> post transmission method

3. $_REQUEST –> can receive values ​​in both get and post methods

4. $GLOBALS –> references all variables available in the global scope

5. $_FILES –> Use to upload files

6. $_SERVER –> System environment variables

7. $_SESSION –> Used for session control

8. $_COOKIE –> Used for session control

9. $_ENV –> Server-side environment variable

The following will give you a detailed introduction

1. $_GET –> get transmission method

PHP $_GET can also be used to collect the data after submitting the HTML form (method="get") Form data.
$_GET can also collect data sent in the URL.

For example, access the URL link:

http://localhost/test_get.php?subject=PHP&web=W3school.com.cn
Copy after login

The usage method is as follows:

<html>
<body>
    <?php 
        echo "Study " . $_GET[&#39;subject&#39;] . " at " . $_GET[&#39;web&#39;];
    ?>
</body>
</html>
Copy after login

2. $_POST –> post transmission method

PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also commonly used to pass variables.

The following example shows a form containing input fields and a submit button. When the user clicks the submit button to submit the data, the form data is sent to the file specified in the action attribute of the

tag. In this example, we specify the file itself to handle the form data. If you wish to use another PHP page to handle the form data, change the file name to a file name of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:

<html>
<body>
    <form method="post" action="<?php echo $_SERVER[&#39;PHP_SELF&#39;];?>">
        Name: <input type="text" name="fname">
        <input type="submit">
    </form>

    <?php 
        $name = $_POST[&#39;fname&#39;]; 
        echo $name; 
    ?>
</body>
</html>
Copy after login

3. $_REQUEST –> can receive values ​​in both get and post methods

PHP $_REQUEST is used to collect data submitted by HTML forms.

The following example shows a form containing input fields and a submit button. When a user submits form data by clicking the submit button, the form data is sent to the script file specified in the action attribute of the tag. In this example, we specify the file itself to handle the form data. If you need to use other PHP files to process form data, please change the file name to the file name of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:

<html>
<body>
    <form method="post" action="<?php echo $_SERVER[&#39;PHP_SELF&#39;];?>">
        Name: <input type="text" name="fname">
        <input type="submit">
    </form>

    <?php 
        $name = $_REQUEST[&#39;fname&#39;]; 
        echo $name; 
    ?>
</body>
</html>
Copy after login

4. $GLOBALS –> References all variables available in the global scope

  • $GLOBALS This type of global variable is used to access global variables from anywhere in a PHP script (either from a function or method).

  • PHP stores all global variables in an array named $GLOBALS[index]. The name of the variable is the key of the array.

  • is mainly used when global variables cannot be used in the local scope, but the global variables need to be used, use $GLOBALS.

The following example shows how to use the super global variable $GLOBALS:

<?php 
    $x = 75; 
    $y = 25;

    function addition() { 
      $GLOBALS[&#39;z&#39;] = $GLOBALS[&#39;x&#39;] + $GLOBALS[&#39;y&#39;]; 
    }

    addition(); 
    echo $z; 
?>
Copy after login

5. $_FILES –> Upload files Use

  • $_FILES is mainly used where binary files need to be uploaded. To enter and upload an abc.mp3 file, the server needs to obtain the file. The relevant information is obtained through the variable $_FILES.

  • $_FILES The super global variable contains information about the data uploaded to the server through the POST method. This super global variable is different from other variables. It is a two-dimensional array containing 5 elements.

Element/Code

Description

##Element/CodeDescription ##$_FILES['userfile']['tmp_name']The temporary file name stored on the server after the file is uploaded##$_FILES['userfile']['error']
$_FILES['userfile']['name']

Client machine file Original name

$_FILES['userfile']['type']

MIME type of the file, required The browser provides support for this information, such as "image/gif"

$_FILES['userfile']['size']

The size of the uploaded file, in bytes

Error code related to the file upload. [‘error’] was added in PHP version 4.2.0. Although this variable is named error , this variable is actually filled in on success. It has five possible values: see note ③

# below the table

注:
① 在 PHP 4.1.0 版本以前该数组的名称为 $HTTP_POST_FILES,它并不像 $_FILES 一样是自动全局变量。PHP 3 不支持 $HTTP_POST_FILES 数组。
② 如果表单中没有选择上传的文件,则 PHP 变量 $_FILES[‘userfile’][‘size’] 的值将为 0,$_FILES[‘userfile’][‘tmp_name’] 将为 none。
③ error字段5个错误码:

  • UPLOAD_ERR_OK 文件成功上传

  • UPLOAD_ERR_INI_SIZE 文件大小超出了

  • MAX_FILE_SIZE 指令所指定的最大值。

  • UPLOAD_ERR_FORM_SIZE 文件大小超出了MAX_FILE_SIZE 隐藏表单域参数(可选)指定的最大值。

  • UPLOAD_ERR_PARTIAL 文件只上传了一部分UPLOAD_ERR_NO_FILE 上传表单中没有指定文件

前端上传文件示例代码:

/**创建一个文件上传表单
允许用户从表单上传文件是非常有用的。
请看下面这个供上传文件的 HTML 表单:**/
<html>
<body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file" /> 
        <input type="submit" name="submit" value="Submit" />
    </form>
</body>
</html>
Copy after login

后端处理文件示例代码:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
Copy after login

6. $_SERVER –> 系统环境变量

$_SERVER 这种超全局变量保存关于报头、路径和脚本位置的信息。

下面的例子展示了如何使用 $_SERVER 中的某些元素:

<?php 
    echo $_SERVER[&#39;PHP_SELF&#39;];
    echo "<br>";
    echo $_SERVER[&#39;SERVER_NAME&#39;];
    echo "<br>";
    echo $_SERVER[&#39;HTTP_HOST&#39;];
    echo "<br>";
    echo $_SERVER[&#39;HTTP_REFERER&#39;];
    echo "<br>";
    echo $_SERVER[&#39;HTTP_USER_AGENT&#39;];
    echo "<br>";
    echo $_SERVER[&#39;SCRIPT_NAME&#39;];
?>
Copy after login

常用的字段:

元素/代码

描述

元素/代码描述

$_SERVER[‘PHP_SELF’]

返回当前执行脚本的文件名。

$_SERVER[‘GATEWAY_INTERFACE’]

返回服务器使用的 CGI 规范的版本。

$_SERVER[‘SERVER_ADDR’]

返回当前运行脚本所在的服务器的 IP 地址。

$_SERVER[‘SERVER_NAME’]

返回当前运行脚本所在的服务器的主机名(比如 www.w3school.com.cn)。

$_SERVER[‘SERVER_SOFTWARE’]

返回服务器标识字符串(比如 Apache/2.2.24)。

$_SERVER[‘SERVER_PROTOCOL’]

返回请求页面时通信协议的名称和版本(例如,“HTTP/1.0”)。

$_SERVER[‘REQUEST_METHOD’]

返回访问页面使用的请求方法(例如 POST)。

$_SERVER[‘REQUEST_TIME’]

返回请求开始时的时间戳(例如 1577687494)。

$_SERVER[‘QUERY_STRING’]

返回查询字符串,如果是通过查询字符串访问此页面。

$_SERVER[‘HTTP_ACCEPT’]

返回来自当前请求的请求头。

$_SERVER[‘HTTP_ACCEPT_CHARSET’]

返回来自当前请求的 Accept_Charset 头( 例如 utf-8,ISO-8859-1)

$_SERVER[‘HTTP_HOST’]

返回来自当前请求的 Host 头。

$_SERVER[‘HTTP_REFERER’]

返回当前页面的完整 URL(不可靠,因为不是所有用户代理都支持)。

$_SERVER[‘HTTPS’]

是否通过安全 HTTP 协议查询脚本。

$_SERVER[‘REMOTE_ADDR’]

返回浏览当前页面的用户的 IP 地址。

$_SERVER[‘REMOTE_HOST’]

返回浏览当前页面的用户的主机名。

$_SERVER[‘REMOTE_PORT’]

返回用户机器上连接到 Web 服务器所使用的端口号。

$_SERVER[‘SCRIPT_FILENAME’]

返回当前执行脚本的绝对路径。

$_SERVER[‘SERVER_ADMIN’]

该值指明了 Apache 服务器配置文件中的 SERVER_ADMIN 参数。

$_SERVER[‘SERVER_PORT’]

Web 服务器使用的端口。默认值为 “80”。

$_SERVER[‘SERVER_SIGNATURE’]

返回服务器版本和虚拟主机名。

$_SERVER[‘PATH_TRANSLATED’]

当前脚本所在文件系统(非文档根目录)的基本路径。

$_SERVER[‘SCRIPT_NAME’]

返回当前脚本的路径。

$_SERVER[‘SCRIPT_URI’]

返回当前页面的 URI。

7. $_SESSION –> 用于会话控制

PHP session 变量用于存储有关用户会话的信息,或更改用户会话的设置。Session 变量保存的信息是单一用户的,并且可供应用程序中的所有页面使用。

  • 当您运行一个应用程序时,您会打开它,做些更改,然后关闭它。这很像一次会话。计算机清楚你是谁。它知道你何时启动应用程序,并在何时终止。但是在因特网上,存在一个问题:服务器不知道你是谁以及你做什么,这是由于 HTTP 地址不能维持状态。

  • 通过在服务器上存储用户信息以便随后使用,PHP session 解决了这个问题(比如用户名称、购买商品等)。不过,会话信息是临时的,在用户离开网站后将被删除。如果您需要永久储存信息,可以把数据存储在数据库中。

  • Session 的工作机制是:为每个访问者创建一个唯一的 id (UID),并基于这个 UID 来存储变量。UID 存储在 cookie 中,亦或通过 URL 进行传导。

①开始 PHP Session :
在您把用户信息存储到 PHP session 中之前,首先必须启动会话。
注释:session_start() 函数必须位于 标签之前

<?php session_start(); ?>

<html>
<body>

</body>
</html>
Copy after login

②存储 和使用Session 变量:

<?php
session_start();
// store session data
$_SESSION[&#39;views&#39;]=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION[&#39;views&#39;];
?>

</body>
</html>
Copy after login

③终结 Session
如果您希望删除某些 session 数据,可以使用 unset() 或 session_destroy() 函数。

//通过 unset() 函数用于释放指定的 session 变量:
<?php
unset($_SESSION[&#39;views&#39;]);
?>

//通过 session_destroy() 函数彻底终结 session:
<?php
session_destroy();
?>
Copy after login

注释:session_destroy() 将重置 session,您将失去所有已存储的 session 数据。

8. $_COOKIE –> 用于会话控制

cookie 常用于识别用户。cookie 是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie。通过 PHP,您能够创建并取回 cookie 的值。

①创建 Cookie

//语法
setcookie(name, value, expire, path, domain);

//示例
<?php 
setcookie("user", "Alex Porter", time()+3600);
//创建名为 "user" 的 cookie,把为它赋值 "Alex Porter"。我们也规定了此 cookie 在一小时后过期
?>

<html>
<body>

</body>
</html>
Copy after login

②取回 Cookie 值

//示例a:取回了名为 "user" 的 cookie 的值,并把它显示在了页面上
<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);
?>

//示例b:使用 isset() 函数来确认是否已设置了 cookie
<html>
<body>

<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>

</body>
</html>
Copy after login

9. $_ENV –> 服务器端环境变量

PHP中的$_ENV是一个包含服务器端环境变量的数组,不同系统不完全一样。
部分变量示例:
$_ENV[ ‘HOSTNAME’ ] 服务器的主机名
$_ENV[ ‘SHELL’ ] 系统 shell

$_ENV只是被动的接受服务器端的环境变量并把它们转换为数组元素,你可以尝试直接输出它:

//输出内容格式清晰,ThinkPHP可以直接用dump()
var_dump($_ENV);

//输出到屏幕
print_r($_ENV);

//输出key-value键值对
foreach($_ENV as $key=>$val){echo $key.&#39;--------&#39;.$val.&#39;<br>&#39;;}
Copy after login

【相关教程推荐:《PHP教程》】

The above is the detailed content of Detailed explanation of 9 superglobal variables in PHP (usage examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template