4

I am currently in file1.php and I want a variable from file1.php to pass to file2.php

How do I pass a variable from one php file to another?

I too want to go from file1.php to file2.php

I did following in file1.php:

session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");

and did following in file2.php :

    <?php
    echo "abc";
    echo $_SESSION['akknum'];
    ?>

The file2.php is opening and abc is printing but no value of "jkl" is printing. What am I doing wrong?

3
  • is $_SESSION a must or could you use GET and POST? Commented Oct 11, 2015 at 19:03
  • No it's not,nothing must in $_SESSION Commented Oct 11, 2015 at 19:05
  • is that case, depending on the way your visitors surf from file1.php to file2.php, you could use $_GET parameters in a link for example: <a href="file2.php?akkum=jkl">Link to file2.php</a> Commented Oct 11, 2015 at 19:38

3 Answers 3

2

You need to add session_start(); in file2.php.

session_start();
echo "abc";
echo $_SESSION['akknum'];

Basic usage.

Sign up to request clarification or add additional context in comments.

2 Comments

Won't super global variables reset when starting a new session?
You don't start a new session. If you send the same SID, you continue to use the same session data. But if you don't start the session, $_SESSION will be always an empty array.
2

you need to session_start the second file too.

Comments

2

If you want to use $_SESSION on a different file, you'll need to call session_start();

file1.php

<?php
session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");
?>

file2.php

<?php
session_start();
echo $_SESSION['akknum'];
//jkl
?>

Read more about php sessions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.