Location>code7788 >text

8 common ways to pass parameters (cross files) in PHP

Popularity:830 ℃/2025-04-10 08:43:50

The following are the parameters passed across files in PHP8 common methods, sorted by scenario and security, with detailed instructions and sample code:


1. Hyperglobal variables (suitable for data sharing between requests)

1. $_GET / $_POST

  • use: Pass parameters through URL or form submission (client → server)
  • Example
    //
     <a href="?id=123&name=John">Jump</a>
    
     //
     $id = $_GET['id']; // Get 123
     $name = $_GET['name']; // Get John
  • Notice: The input data needs to be filtered (such asfilter_input()) to prevent XSS attacks.

2. $_SESSION

  • use: Keep data across pages during sessions (dependencesession_start()
  • Example
    //
     session_start();
     $_SESSION['user'] = 'Alice';
    
     //
     session_start();
     echo $_SESSION['user']; // Output Alice
  • Safety: Session security needs to be configured (such assession.cookie_httponly)。

3. $_COOKIE

  • use: The client stores small data and automatically sends it with requests
  • Example
    //
     setcookie("theme", "dark", time() + 86400);
    
     //
     echo $_COOKIE['theme']; // Output dark
  • limit: The data size is limited (approximately 4KB), and it needs to be prevented from tampering.

2. File contains (suitable for sharing data within the same request)

4. include / require+ Variable

  • use: Directly share the current scope variables (requires attention to variable pollution)
  • Example
    //
     $db_host = 'localhost';
    
     //
     include '';
     echo $db_host; // Output localhost
  • shortcoming: The scope of the variable is uncontrollable, which may lead to naming conflicts.

3. File storage (suitable for persistent data)

5. Read and write files

  • use: Storing intermediate data through files
  • Example
    //
     file_put_contents('', 'Hello World');
    
     //
     $data = file_get_contents(''); // Read Hello World
  • Notice: File lock needs to be processed (LOCK_EX) and concurrent conflicts.

6. database

  • use: Share data through a database (such as MySQL)
  • Example
    // 
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
    $pdo->exec("INSERT INTO messages (content) VALUES ('Hello')");
    
    // 
    $stmt = $pdo->query("SELECT content FROM messages");
    $data = $stmt->fetchAll();
    
  • Safety: Preprocessing statements must be used to prevent SQL injection.

4. Serialization and deserialization

7. serialize()andunserialize()

  • use: Store complex data structures (such as arrays, objects)
  • Example
    //
     $data = ['name' => 'Bob', 'age' => 30];
     file_put_contents('', serialize($data));
    
     //
     $data = unserialize(file_get_contents(''));
     echo $data['name']; // Output Bob
  • risk: Deserialization may execute malicious code and the data source needs to be verified.

5. Object-oriented method

8. Static class attributes/singleton mode

  • use: Share global state through classes
  • Example
    //
     class Config {
         public static $value = 'default';
     }
    
     //
     Config::$value = 'new value';
    
     //
     echo Config::$value; // Output new value

Method comparison and selection suggestions

method Applicable scenarios Security Persistence Data volume limit
$_GET/$_POST Form/URL parameter transfer Low none Small
$_SESSION User session data high Session level medium
$_COOKIE Client storage configuration middle long Small
File contains Share configuration with request middle none big
File storage Persistence of non-sensitive data Low long big
database Structured data sharing high long big
Serialization Complex data structures Low long big
Static class attributes Global configuration/state management middle Request level big

Summarize

  • Temporary data delivery:Preferred$_SESSIONorinclude(Note the scope)
  • Client data:use$_GET/$_POST/$_COOKIE(Input must be filtered)
  • Persistent storage: Select a file or database
  • Global state management: Use static class attributes or singleton mode