user3245689
user3245689

Reputation: 157

posting variable from php file to another php file

I show similar threads, but could not get clear through them.

page1.php

<?php
   $id = 1234;
   //Post $id to page2.php   
?>

page2.php

<?php
      $user_id=$_POST['id']; //should receive id posted from page1.php
?>

Upvotes: 1

Views: 102

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

You can use sessions for this also, to show you what your options are.

This works with a POST method (use all in one file for the form method)

Form method (page1.php)

<?php
session_start();
$id = $_SESSION["id"] = $_POST['id'];

if(isset($_POST["submit"])){
echo $id;
echo "<br>";
echo "<a href='page2.php'>Click to see session ID on next page</a>";
}
?>

<form action="" method="post">

Enter ID: 
<input type="text" name="id">

<br>
<input type="submit" name="submit" value="Submit">

</form>

page2.php

<?php
session_start();
$user_id=$_SESSION["id"];
echo $user_id; // will echo 1234 if you entered "1234" in the previous page.

Regular session method (page1.php)

<?php
session_start();
$id = $_SESSION["id"] = "1234";
echo $id; // will echo 1234

page2.php

<?php
session_start();
$user_id=$_SESSION["id"];
echo $user_id; // will echo 1234

Footnotes:
You could then use the same (session) variable for a member's login area, database for example.

It is important to keep session_start(); included inside all pages using sessions, and at the top.

Should you be using a header() in conjunction with this, then you will need to add ob_start(); before session_start();

Otherwise (as Eitan stated in a comment) "$_SESSION value will be unresolvable."

header() example:

<?php
ob_start();
session_start();
$user_id=$_SESSION["id"];

   if(isset($_SESSION["id"])){
header("Location: members_page.php");
   exit;
}

   else{
header("Location: login_page.php");
   exit;
}

You could also replace: if(isset($_SESSION["id"])) with if(!empty($_SESSION["id"]))

To implement a logout page, you would need to use session_destroy();

Upvotes: 0

Actually you are not sending the id parameter to your Page2.php

Page1.php

<?php
   $id = 1234;
   header("location:page2.php?id=$id");//Post $id to page2.php   
?>

Page2.php

<?php
      echo $user_id=$_GET['id']; //should receive id posted from page1.php
?>

Upvotes: 1

Related Questions