Passing Variables through different pages in PHP


You often need to pass/keep variables from pages to pages when you design the website. For example, when you display records in a table, you want the users be able to specify the number of items shown per page, e.g. $per variable. To do this, we can have three methods. Although the following semantics is about PHP, but the same principle can be easily applied to other dynamic server scripting languages such as ASP.NET, JSP.

Naive Approach (GET)

You can hard-code the URL link everytime you want to redirect to a new URL. Of course, you will manually pass the $per variable each time. If you forget, and the value of the variable will be lost.

1
2
3
4
5
6
7
define('C_PERDEF', 5);
$per = C_PERDEF; // default 5 items per page
if (isset($_GET['per'])) {
    $per = (integer)$_GET['per']; 
}
 
echo "<a href='next.php?page=2&per=$per'>";
define('C_PERDEF', 5);
$per = C_PERDEF; // default 5 items per page
if (isset($_GET['per'])) {
    $per = (integer)$_GET['per']; 
}

echo "<a href='next.php?page=2&per=$per'>";

Session Approach

You can save the variable in the session, which will be $_SESSION[‘per’]. To use the variable, you will need to put session_start() at the beginning of every page that you want to use.

1
2
3
4
5
6
7
8
9
10
    define('C_PERDEF', 5);
    $per = C_PERDEF;
    if (isset($_GET['per'])) { // allows update via GET parameter first
        $per = (integer)$_GET['per'];
    } else {
        if (isset($_SESSION['per'])) {
            $per = $_SESSION['per'];
        }
    }
    $_SESSION['per'] = $per;
    define('C_PERDEF', 5);
    $per = C_PERDEF;
    if (isset($_GET['per'])) { // allows update via GET parameter first
        $per = (integer)$_GET['per'];
    } else {
        if (isset($_SESSION['per'])) {
            $per = $_SESSION['per'];
        }
    }
    $_SESSION['per'] = $per;

The logics here is to allow updating with priority the variable via URL and then value will be updated in the session. To use the variable in the page, you will need something like this:

1
2
3
4
$per = C_PERDEF;
if (isset($_SESSION['per'])) {
    $per = (integer)$_SESSION['per'];
}
$per = C_PERDEF;
if (isset($_SESSION['per'])) {
    $per = (integer)$_SESSION['per'];
}

The session variables will be available through the entire session (several pages), unlike static HTML redirections.

You can even have a form somewhere in the page that allows user to easily update their preferences.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    echo "<select class='form-control' name='per' id='per'>";
    $step = 5;
    $j = 0;
    for ($i = 5; $i <= 2000; $i += $step) {
        if ($per == $i) {
           echo "<option selected value='$i'>$i Items Per Page</option>";
        } else {
          echo "<option value='$i'>$i Items Per Page</option>";
        }
        $j ++;
        if ($j % 20 == 0) {
           $step += 5;
        }
    }
    echo "</select>";
    echo "<select class='form-control' name='per' id='per'>";
    $step = 5;
    $j = 0;
    for ($i = 5; $i <= 2000; $i += $step) {
        if ($per == $i) {
           echo "<option selected value='$i'>$i Items Per Page</option>";
        } else {
          echo "<option value='$i'>$i Items Per Page</option>";
        }
        $j ++;
        if ($j % 20 == 0) {
           $step += 5;
        }
    }
    echo "</select>";

Put a form submit button and then change the method attribute of the form tag to GET.

Redirect class

The following Storage class stores the key-value pair.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
  class Storage
  {
    private $_pairs = array();
    
    public function Storage($pairs = array())
    {
      foreach ($pairs as $keys => $v)
      {
          $this->setVar($keys, $v);
      }
    }
    
    public function sort()
    {
      ksort($this->_pairs);
    }
    
    public function getSize()
    {
      return (count($this->_pairs));
    }
    
    public function keys()
    {
      return (array_keys($this->_pairs));
    }
    
    public function values()
    {
      return (array_values($this->_pairs));
    }
    
    public function isVar($name)
    {
      return (array_key_exists($name, $this->_pairs));
    }
    
    public function getVar($name)
    {
      return (isset($this->_pairs[$name])) ? ($this->_pairs[$name]) : (NULL);
    }
    
    public function delVar($name)
    {
      if (isset($this->_pairs[$name]))
      {
        unset($this->_pairs[$name]);
      }
    }
    
    public function setVar($name, $value)
    {
      $this->delVar($name);
      if ((strlen($value) > 0) && (strlen($name) > 0))
      {
        $this->_pairs[$name] = $value;
      }
    }
    
    public function getAll()
    {
      return ($this->_pairs);   
    }
    
    public function toQs()
    {
      $_q = '';
      foreach ($this->_pairs as $key=>$pair)
      {
        $key = trim($key);
        $pair = trim($pair);
        if (($key) && ($pair))
        {
          $key = urlencode($key);
          $pair= urlencode($pair);
          $_q .= "($key=$pair)";
        }
      }
      $_q = str_replace(')(', '&', $_q);
      $_q = str_replace('(', '', $_q);
      $_q = str_replace(')', '', $_q);
      return '?'.$_q;
    }     
  };
  class Storage
  {
    private $_pairs = array();
    
    public function Storage($pairs = array())
    {
      foreach ($pairs as $keys => $v)
      {
          $this->setVar($keys, $v);
      }
    }
    
    public function sort()
    {
      ksort($this->_pairs);
    }
    
    public function getSize()
    {
      return (count($this->_pairs));
    }
    
    public function keys()
    {
      return (array_keys($this->_pairs));
    }
    
    public function values()
    {
      return (array_values($this->_pairs));
    }
    
    public function isVar($name)
    {
      return (array_key_exists($name, $this->_pairs));
    }
    
    public function getVar($name)
    {
      return (isset($this->_pairs[$name])) ? ($this->_pairs[$name]) : (NULL);
    }
    
    public function delVar($name)
    {
      if (isset($this->_pairs[$name]))
      {
        unset($this->_pairs[$name]);
      }
    }
    
    public function setVar($name, $value)
    {
      $this->delVar($name);
      if ((strlen($value) > 0) && (strlen($name) > 0))
      {
        $this->_pairs[$name] = $value;
      }
    }
    
    public function getAll()
    {
      return ($this->_pairs);	
    }
    
    public function toQs()
    {
      $_q = '';
      foreach ($this->_pairs as $key=>$pair)
      {
        $key = trim($key);
        $pair = trim($pair);
        if (($key) && ($pair))
        {
          $key = urlencode($key);
          $pair= urlencode($pair);
          $_q .= "($key=$pair)";
      	}
      }
      $_q = str_replace(')(', '&', $_q);
      $_q = str_replace('(', '', $_q);
      $_q = str_replace(')', '', $_q);
      return '?'.$_q;
    }     
  };

Then we can parse each page the $_SERVER[‘QUERY_STRING’].

1
2
3
4
5
6
7
8
9
10
11
12
13
  $query = $_SERVER['QUERY_STRING'];
  $pairs = explode('&', $query);
  $QS = new Storage();
  foreach ($pairs as $pair)
  {
    if (false !== strpos($pair, '='))
    {
      list($name, $value) = explode('=', $pair, 2);
      $name = urldecode($name);
      $value = urldecode($value);
      $QS->setVar($name, $value);
    }
  }
  $query = $_SERVER['QUERY_STRING'];
  $pairs = explode('&', $query);
  $QS = new Storage();
  foreach ($pairs as $pair)
  {
    if (false !== strpos($pair, '='))
    {
      list($name, $value) = explode('=', $pair, 2);
      $name = urldecode($name);
      $value = urldecode($value);
      $QS->setVar($name, $value);
    }
  }

And, suppose you can come up with a redirect() function that takes a key-value pair.

1
2
3
4
5
6
7
8
9
function redirect($values = array()) {
  global $QS; // if you don't like global variable, then move the above code here.
  if (!empty($values)) {
     foreach ($values as $key => $val) {
        $QS->setVar($key, $val); // if would be better to check of null values here.
     }
  }
  return $QS->toQs();
}
function redirect($values = array()) {
  global $QS; // if you don't like global variable, then move the above code here.
  if (!empty($values)) {
     foreach ($values as $key => $val) {
        $QS->setVar($key, $val); // if would be better to check of null values here.
     }
  }
  return $QS->toQs();
}

Then, to use it,

1
echo redirect(array("do" => "Hello", "per" => 5));
echo redirect(array("do" => "Hello", "per" => 5));

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
809 words
Last Post: How to Cache Heavy Operations (such as Database Queries) in PHP?
Next Post: How to Create a Picture By Changing Cell Colors in Excel, using PHP and VBScript?

The Permanent URL is: Passing Variables through different pages in PHP

Leave a Reply