search
HomeBackend DevelopmentPHP TutorialSimple understanding of PHP super global variables

This article brings you relevant knowledge about PHP, which mainly introduces the relevant content about super global variables. Super global variables are a special type of variables, which are built-in and predefined. Accessed from any scope, there is no need to execute any special code segments. Let’s take a look at it. I hope it will be helpful to everyone.

Simple understanding of PHP super global variables

Understanding PHP Super Globals

Super global variables are a special type of variable because they can be accessed from any scope. Can be accessed from any file, class, or even function without executing any special code segment.

Superglobal variables are built-in and predefined. Programmers can use them through PHP libraries. Please note that not all built-in predefined variables in the class library are superglobal variables.

Prerequisites

To understand the content of this article, readers should have the following conditions.

  • Have a basic understanding of PHP variable declaration technology.
  • Have a preliminary understanding of PHP.

Introduction to PHP super global variables

Super global variables were introduced in PHP 4.1.0 and have been an important part of PHP ever since. There are about 9 superglobal variables in PHP, sometimes called automatic globals. They are described below.

  • $GLOBALS

  • $_SERVER

  • $_GET

  • $_POST

  • $_REQUEST

  • $_SESSION

  • $_COOKIE

  • $_FILE

  • $_ENV

Let us discuss these super global variables in the following sections .

$GLOBALS

##GLOBALS is a PH P variable, used to access other globals in PHP variable. All PHPglobal variables are stored in a file called ' GLOBALS is a PHP variable used to access other global variables in PHP scripts. All PHP global variables are stored in a file called `The following is an example of using the super global variable $GLOBAL :)<pre class="brush:php;toolbar:false">   nbsp;html&gt;            &lt;title&gt;GLOBAL example&lt;/title&gt;                  &lt;?php //php Script // Varriable declaration $a = 5; $b = 6; function multiplication(){ $GLOBALS[&amp;#39;c&amp;#39;] = $GLOBALS[&amp;#39;a&amp;#39;]* $GLOBALS[&amp;#39;b&amp;#39;]; } multiplication(); echo $c; ?&gt;         </pre>In the above example, the variable $c is inside the function and It is accessible from the outside because it is in the

$GLOBALS

array.

$_SERVER

$_SERVER is a super global variable used to save the information header, path and location of the PHP script. Variables have several elements that are saved. They include

$_SERVER

$_SERVER['PHP_SELF'] - which returns the filename of the currently executing script. $_SERVER['SERVER_NAME'] - This returns the name of the server hosting the website.

  • $_SERVER['HTTP_HOST'] - This will return the host header of the current request.

  • $_SERVER['SCRIPT_NAME'] - This returns the path to the current script.

  • Below is a sample code showing how to use the above elements.

       nbsp;html>
       
       
       <title> $_SERVER example</title>
       
           
           <?php        // PHP script
                  echo $_SERVER[&#39;PHP_SELF&#39;];
                  echo "<br>";
                  echo $_SERVER['SERVER_NAME'];
                  echo "<br>";
                  echo $_SERVER['HTTP_HOST'];
                  echo "<br>";
                  echo $_SERVER['SCRIPT_NAME'];
            ?>
           
       
  • The output of the above code will include.
    • 一个文件名。
    • 主机服务器的名称。
    • 主机当前请求的标题。
    • 当前脚本的路径。

    $_GET

    $_GET 变量是一个PHP超全局变量,用于收集HTML表单提交后的数据。HTML表单的结构是这样的:$_GET 作为一个方法。$_GET 也可以用来检索在uniform resource locator 中发送的数据。

    下面是一个例子,说明如何在HTML表单中实现$_GET 变量。

       nbsp;html>
       
       
       <title>$_GET example</title>
    
       
          
             <!-- html form -->
          
                                                                 
                  

    当用户点击Submit 按钮时,表单中的信息会用GET 方法发送,并显示在URL 。然而,每次最多只能发送2048 字符。

    $_POST

    就像$_GET 变量一样,$_POST 收集来自HTML表单的值。使用这种方法发送的信息不会显示在URL中。一次可以发送的字符数也没有限制。

    下面是一个例子。

        nbsp;html>
        
        
        <title>$_POST example</title>
    
        
          
              <!-- html form -->
          
                                                            
                

    为什么POST变量优于GET?

    尽管POSTGET 方法实现了相同的功能,但由于以下原因,POST 更受青睐。

    • POST方法对可以发送的数据大小没有限制。

    • POST方法可以同时发送ASCII和二进制数据。

    • POST方法不会在URL上显示正在发送的信息,因此可以防止建立书签。

    • POST方法使用一个HTTP header 来发送数据。这促进了数据安全。

    $_REQUEST

    $_REQUEST 变量是一个PHP超全局,用于在提交表单后收集数据。它包含了$_GET$_POST ,甚至默认的$_COOKIE 的内容。各个字段的数据可以由PHP使用$_REQUEST 变量来收集。

    下面的例子显示了如何使用$_REQUEST 这个变量。

    nbsp;html>
    
        
        <title>$_REQUEST example</title>
        
         
         
    " method="POST">                                  
               

    上述代码的输出将是表单中已提交的name 。如果没有提交名字,它将打印一个信息Empty name

    $_SESSION

    $_SESSION 变量是一个PHP的超级全局,它可以在用户每次打开网站时存储和利用有关网站用户的信息,直到网站关闭。

    每次用户访问网站时,都会启动一个会话。下面的函数被用来在PHP代码中启动一个会话。

       session_start()

    会话开始后,需要使用$_SESSION 变量进行设置。

    当用户离开一个网站时,会话被自动销毁。这是在用户不知情的情况下使用下面的PHP函数完成的。

    session_destroy()

    下面的例子演示了$_SESSION 的使用。

     php
        session_start();
    ?>
    
     nbsp;html>
     
       
          <title>$_SESSION demonstration code</title>
       
    
     
          <?php          //Set session varriables
    
             $_SESSION["name"]="Mackrine";
             $_SESSION["favcolor"]="Blue";
             echo "session varriables are set";
          ?>
     
    
    

    Cookie是一个小文件,由服务器存储在用户的计算机中。它可以识别用户。每当向服务器发出请求时。通常会在请求的同时发送一个cookie。PHP 使用setcookie() 函数创建 cookie。

       setcookie(cookie_name,cookie_value, expiry, path, domain,secure,httponly)

    该语法有许多参数。然而,只有name 参数是必需的。

    在创建之后,可以使用超全局$_COOKIE 变量来检索cookie。下面的代码显示了如何创建和检索一个cookie。

      <?php     $cookie_name = "uname";
        $cookie_value = "Mackrine";
    
       //setting cookie
    
        setcookie($cookie_name, $cookie_value, time()+(86400*30),"/");
    
         ?>
        nbsp;html>
        
        
        <?php        if(isset($_COOKIE[$cookie_name]))
            {
                echo "Cookie name:" .$cookie_name;
                echo "<br>";
                echo "Cookie value:" .$cookie_value;
    
            }
             else
             {
                echo $cookie_name. " is not set!";
    
             }
        ?>
        
        

    只有在过期的情况下,才可以使用setcookie() 函数删除cookie。

    $_FILES

    $_FILES 是一个变量,包含使用HTTPPOST方法上传的项目。 数组包含几个元素,如下所述。$_FILES

    • $_FILES['file']['name'] - 这通常是要上传的文件的原始名称。

    • $_FILES['file']['type'] - 这是指被上传文件的类型。

    • $_FILES['file']['size'] - 以字节为单位的文件大小。

    • $_FILES['file']['tmp_name'] - 它指的是在服务器上上传的存储文件的临时文件名。

    • $_FILE['file']['error']- 文件上传的相关错误代码。

    总结

    超全局变量是PHP语言的核心。在PHP编程中需要这些变量来制作高功能的程序。因此,你可以利用这些信息来制作高质量的应用程序。

    推荐学习:《PHP视频教程

The above is the detailed content of Simple understanding of PHP super global variables. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.