简体   繁体   中英

Are there any domain specific global variables in PHP?

I have 2 websites running on my localhost

  1. localhost/sample_website1/index.php
  2. localhost/sample_website2/index.php

initial code in both the websites is:

if(isset($_SESSION['user'])){
    header("location:home.php")
}
// This code redirects index.php to home.php if the session already exists

.........next lines are login code..........
// 
// 
// 
            
............................................

I have successfully logged into sample_website1 using the login form in index.php and the session is activated. $_SESSION['user']=$username

Now I opened a new tab and visited sample_website2 in which it is using the session variable $_SESSION['user'] that is already set in sample_website1 and automatically logging into home.php from index.php

I need a session variable that will be active only in sample_website1 so that it will not directly authenticate user on some other website like sample_website2.

use session_name("sample_websiteN"); before session_start() (replace N with 1 or 2), see php.net/session_name

in localhost/sample_website1/index.php

<?php
session_name("sample_website1");
session_start();

if(isset($_SESSION['user'])){
    header("location:home.php")
}
// This code redirects index.php to home.php if the session already exists

.........next lines are login code..........
// 
// 
// 
            
............................................

in localhost/sample_website2/index.php

<?php
session_name("sample_website2");
session_start();

if(isset($_SESSION['user'])){
    header("location:home.php")
}
// This code redirects index.php to home.php if the session already exists

.........next lines are login code..........
// 
// 
// 
            
............................................

Explanation from php.net: The session name references the name of the session, which is used in cookies and URLs (eg PHPSESSID)

With this solution, you can deploy your code in same domain and in different domain with perfectly same behavior. You can host both directory in localhost/sample_website1/index.php and localhost/sample_website2/index.php OR in sample_website1.com/index.php and sample_website2.com/index.php with same code

If the session name seems ugly to be hardcoded, then save the session name string somewhere in a configuration file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM