tags:

views:

71

answers:

5

How to pass variables from a php file to another while it is not html inputs ,just i have a link refer to the other file and i want to pass variables or values to it

Example:

File1.php

<?php

$name='OdO';
echo "<a href='File2.php'>Go To File2</a>";

?>

File2.php

<?php

echo $name;

?>
+5  A: 

Use sessions to store any small value that needs to persist over several requests.

File1.php:

session_start();
$_SESSION['var'] = 'foo';

File2.php:

session_start();
$var = $_SESSION['var'];  // $var becomes 'foo'
kijin
any "small" value? Just take a look at the phpMyAdmin $_SESSION haha
joni
@joni haha, that's their definition of "small"! Personally I wouldn't put anything bigger than 50KB in the session. Those things belong in the database... But then again, I wouldn't want phpmyadmin to put arbitrary things in my database.
kijin
@kijin thanks alot,is there any additional ways?
OdO
@OdO additional ways? See other answers... You could also store the values in some sort of database (e.g. MySQL) or cache (e.g. Memcached) and retrieve it later. Or store it in a file.
kijin
what if i have more than one link to the page file2.php and by clicking each one the variables has a different value??
OdO
@OdO In that case you'll need to pass the variable as a query string: `file2.php?var=foo` and do `$_GET['var']` in file2.php. In other words, you need to make the URL different. It's the only way the server can tell which link the user clicked.
kijin
A: 

Try to use sessions. Or you can send a GET parameters.

Alexander.Plutov
How to send GET parameter while it is not Html inputs?,,may i better use POST?and how?
OdO
A: 

Hello use the include directive :

    <?php
          $name='OdO'; echo "Go To File2"; 
          include 'File2.php';
    ?>

or in the other order :

<?php
     include 'File1.php';
     echo $name;
?>

Be aware about the risk with include http://en.wikipedia.org/wiki/Remote_file_inclusion

Christophe Debove
But i'm having HTML tags and style tags in both the two files,wouldn'the include make those tags appears in each page and interfere??
OdO
why to avoid global variables??
OdO
forget what I just said you can use global var $GLOBALS.
Christophe Debove
A: 

You can use URLs to pass the value too.

like

index.php?id=1&value=certain

and access it later like

$id = $_GET['id'];
$value = $_GET['value'];

However, POST might be much reliable. Sessions/Cookies and database might be used to make the values globally available.

Starx
A: 

Here's one (bad) solution, using output buffering:

File 1:

<?php
    $name = 'OdO';
    echo '<a href="File2.php">Go To File2</a>';
?>

File 2:

<?php
    ob_start();
    include 'File1.php';
    ob_end_clean();

    echo $name;
?>
Eric