Use SESSIONS variables between different php files-ThrowExceptions

Exception or error:

I am new to $_SESSIONS but needs it to re-use variables between different php files. In the below code I want to use the variable $word in another php file, but I am unsure how to do this.

My php file looks like this:

<?php
  if (isset($_POST["search"])) {    

    //include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

Looking forward to your suggestions.


UPDATE Sessions still not working on page2.php?

I do not understand why $_SESSION do not work. One page1.php I can echo($_SESSION['word']) and get the correct value, but one page2.php I get ('$'."_SESSION['word'] isn't set because you had never been at file one");

I tested all the below solutions but none of them worked = same result on page2.php.

My page1.php file.

<?php
session_start();

//if we got something through $_POST
    if (isset($_POST["search"])) {  

    // include database connection
        $connect = mysql_connect('localhost', 'root', 'NomiS123') or die(mysql_error());
        mysql_select_db('workcard');

    // sanitize user input
        $word = mysql_real_escape_string($_POST["search"]);
        $word = htmlentities($word);

    // build search query to the database
        $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

        // get results
        $_SESSION['word'] = $word;
        $results = mysql_query($sql);
        if (mysql_num_rows($results)==0) {
            $_SESSION['word'] = $word;
            echo($_SESSION['word']. "<br>");
            var_dump($_SESSION);
            echo "<br>";
            echo "link link <br>";
            echo "<a href=\"../page2.php/\">new card</a> <br>";
            echo "<a href=\"//cykelc/\">New Search</a>";
        }   else {
                echo $word, " bla bla text <br> Create card <br>";
                echo "Edit info on: ", $word, "<br>";
                echo "<a href=\"//cykelc/\">New Search</a> <br>";

                while ($row = mysql_fetch_assoc($results)) {
                    echo '<pre>', print_r($row), '<pre>';
                    }
                    //$results->free();
            }   
        }
// mysql_close($connect);
?>

My PAGE2.php file.

<?php 
session_start();
if(isset($_SESSION['word'])) {
    $word = $_SESSION['word'];
    echo($word);
} else {
    die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
?>

I am going insane over this.


UPDATE – SOLVED

I tested all the below suggestions but none of them worked which was weird because I could set and echo out the sesson_id() on page1.php and page2.php, but on page2.php I got a different sesson_id(). I began to look into my MAMP sessions settings, but everything was correct set. The solution was “simply” to place the session_start(); on the very top on page2.php. And by the very top I mean before everything even the <!DOCTYPE html> etc.
Solved + lesson learned 🙂

How to solve:

First you must start the seesion via session_start(); directly after the opening PHP ‘tag’ (<?php session_start();... ?>)

Then you must save your variable to the session.
You can use $_SESSION['word'] = $word; for this purpose.

And in the other file you must also use session_start(); at the very first after the <?php ‘tag’.

Then you could access the old variable via $word = $_SESSION['word'];.

You now can also use $word in the second file. But you only can use it if it’s set (and you where at the first file before).

File one:

<?php
session_start();
    if (isset($_POST["search"])) {    

    //include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);
 $_SESSION['word'] = $word;

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

File two:

<?php
session_start();
if(isset($_SESSION['word'])) {
    $word = $_SESSION['word'];
} else {
    die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
echo $word;
?>

Hope this helps 😉

Answer:

To use PHP sessions you would do the below:

Initiate the session, session_start();

Note: session_start(); must be the first line of PHP in your file.

Create the session, $_SESSION['word'] = $word;

To access it on another page:

Initiate the session, session_start();

Access the session, $word = $_SESSION['word'];

Answer:

session_start() means that you are using session variables, make sure it’s at the top of the page. To make a session you do: $_SESSION['word'] = [some value]. This can be used between pages as long as you have session_start() at the top. Make sure to make sure it’s set first, if it’s not set initialize.

<?php session_start(); ?>

...

<?php 
    if ( isset($_SESSION['word']) ) {
      $_SESSION['word'] = /* change existing session value */;
    } else {
      $_SESSION['word'] = /* new session value */;
    }
?>

Answer:

You first of all should start the session using the function ‘session_start()’.
Place this in your index.php/bootstrap.php (a file that is always loaded when loading your website).

After that, you can use the ‘$_SESSION’ global to set data.

//In your index.php/boostrap.php
session_start();

In the file you want to save the $word:

$_SESSION['myword'] = $word;

And from that point you can use this variable on another page.

//On another page, after the variable is being set
echo $_SESSION['myword']; 

Be aware that when you are using shared webhosting, your session data is often stored in a global folder on the webserver and can be used by every website on that server. To prevent this, you should change you session save path using the ‘session_save_path()’ function or by creating you own session handler.

Answer:

Call session_start(); at the beginning of the PHP file, and if anything is set in the $_SESSION super global array, you can re-access it.

If it isn’t set you can set it with:
$_SESSION['a name']= 'some thing';

So for your example:
PHP FILE1

<?php
session_start();
$_SESSION['word'] = $_POST['word']
?>

PHP FILE2

<?php
session_start();
echo $_SESSION['word'];
?>

Answer:

There are many many ways to accomplish this it all depends on how you want to use it. You can include your file in that file, you can use require or require_once, or yes you can use the session super global.

The $_SESSION super global will be accessible to all files within your application. The only thing you need to make sure you do is use session_start() on the page as the first thing on that page. If you use session_start() after any output has gone to teh browser it will not work. Usually you will want to run session_start() as the first line on your index.php file. Then you can use …

<?php
if (isset($_POST["search"])) {    

//include database connection

 $word = mysql_real_escape_string($_POST["search"]);
 $word = htmlentities($word);
 $_SESSION['word'] = $word;

 $sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");

$results = mysql_query($sql);
 if (mysql_num_rows($results)==0) {
  echo $word, " text bla";
}else {
  echo $word, " text bla bla";
   while ($row = mysql_fetch_assoc($results)) {
    echo '<pre>', print_r($row), '<pre>';
   }
  } 
}?>

then in any page you want access to it just cal it up…

<?php
    echo $_SESSION['word'];

Hope that helps

Leave a Reply

Your email address will not be published. Required fields are marked *