Table of Contents
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 –> Upload files using
6. $_SERVER –> 系统环境变量
7. $_SESSION –> 用于会话控制
8. $_COOKIE –> 用于会话控制
9. $_ENV –> 服务器端环境变量
Home Backend Development PHP Problem How many php super global variables are there?

How many php super global variables are there?

Jul 08, 2021 pm 05:04 PM
php superglobal variable

There are 9 php super global variables, namely: "$GLOBALS", "$_SERVER", "$_GET", "$_POST", "$_FILES", "$_COOKIE", "$_SESSION" ”, “$_REQUEST”, “$_ENV”.

How many php super global variables are there?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Many predefined variables in PHP are " "superglobal", which means they are available throughout the entire scope of a script. They can be accessed within a function or method without executing global $variable;.

These superglobal variables are:

  • $GLOBALS

  • $_SERVER

  • $_GET

  • $_POST

  • $_FILES

  • $_COOKIE

  • $_SESSION

  • $_REQUEST

  • $_ENV

1. $_GET –> get transmission method

PHP $_GET can also be used to collect form data after submitting an HTML form (method="get").
$_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 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.
  • 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 using

  • $_FILES is mainly used when a binary file needs to be uploaded. To upload an abc.mp3 file, the server needs to obtain relevant information about the file, which 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.
##$_FILES['userfile']['size']The size of the uploaded file, in bytes$_FILES['userfile']['tmp_name']After the file is uploaded, it will be served The name of the temporary file stored on the end $_FILES['userfile']['error'] and the 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

常用的字段:

Element/CodeDescription
$ _FILES['userfile']['name']The original name of the client machine file
$_FILES['userfile']['type']The MIME type of the file requires the browser to provide support for this information, such as "image/gif"
元素/代码描述
$_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 数据。

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 How many php super global variables are there?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles