How to pass variables between php scripts?

前端 未结 7 1952
梦如初夏
梦如初夏 2020-12-03 15:15

Is there any way to pass values and variables between php scripts?

Formally, I tried to code a login page and when user enter wrong input first another script will

相关标签:
7条回答
  • 2020-12-03 15:21

    You can use:

    • temporary file (e.g. tempnam()),
    • cache (NoSQL: memcached, redis),
    • session variable ($_SESSION), but you need to start the session first.
    0 讨论(0)
  • 2020-12-03 15:26

    You should look into session variables. This involves storing data on the server linked to a particular reference number (the "session id") which is then sent by the browser on each request (generally as a cookie). The server can see that the same user is accessing the page, and it sets the $_SESSION superglobal to reflect this.

    For instance:

    a.php

    session_start(); // must be called before data is sent
    
    $_SESSION['error_msg'] = 'Invalid input';
    
    // redirect to b.php
    

    b.php

    <?php
    
    session_start();
    
    echo $_SESSION['error_msg']; // outputs "Invalid input"
    
    0 讨论(0)
  • 2020-12-03 15:27

    Can't you include (or include_once or require) the other script?

    0 讨论(0)
  • 2020-12-03 15:28

    I would say that you could also store a variable in cache if you really need.

    0 讨论(0)
  • 2020-12-03 15:38

    The quick way would be to use either global or session variables.

    global $variable = 'something';
    

    The 'better' way of doing it would be to include the script and pass the variable by parameter like

    // script1.php contains function 'add3'
    function add3( $value ) {
      return $value + 3;
    }
    
    // script2.php
    include "script1.php";
    echo 'Value is '.add3(2); // Value is 5
    
    0 讨论(0)
  • 2020-12-03 15:38

    I use extract() method to pass variable among PHP Scripts. It look like below example:

    1. File index.php

    <?php
    $data = [
        'title'=>'hello',
        'content'=>'hello world'
    ];
    extract($data);
    require 'content.php';
    

    2. File content.php :

    <?php 
    echo $title;
    echo $content;
    
    0 讨论(0)
提交回复
热议问题