How to Pass Data in PHP

In PHP, data can be passed using various methods depending on the need and scope. The most common ways include GET and POST methods for form data, SESSION and COOKIE for storing and sharing data across pages, and function parameters for internal data handling. You can also use includes and associative arrays for modular code and data grouping. Choosing the right method depends on whether the data is temporary, secure, or needs to persist across pages.

1. Function Parameters (within same file)


<?php
function showMessage($text) {
    echo $text;
}

showMessage("Welcome!");
?>

2. Associative Arrays (internal use or function calls)


<?php
$user = ['name' => 'John', 'age' => 23];

function displayUser($user) {
    echo "Name: " . $user['name'];
}

displayUser($user);
?>

3. Include with Variables (like layout components)

header.php


<h1><?php echo $pageTitle; ?></h1>

home.php


<?php
$pageTitle = "Home Page";
include 'header.php';
?>

4. Session – Passing data from home.php to about.php

home.php


<?php
session_start();
$_SESSION['username'] = "John";
header("Location: about.php");
exit;
?>

about.php


<?php
session_start();
echo "Welcome, " . $_SESSION['username'];
?>

Summary – What to Use Instead of React Props in PHP

Use Case PHP Method
Reusable logic in same file Function parameters
Reusable data group (like object) Associative arrays
Include and reuse layout/UI blocks include + variables
Pass data between pages (like props) $_SESSION ✅ Best
Temporary one-page data POST or GET