Session control for single sign-on in PHP
This article mainly introduces the session control of single sign-on in PHP. It has certain reference value. Now I share it with you. Friends in need can refer to it
1. Simply use session
Before using session, you need to open session with session_start()
Write a Demo to implement it
Create a new session.php
<?php session_start(); //使用时必须开启,如果你在php.ini里头修改了配置那么就无需在开启session了 $_SESSION['username'] = 'admin'; //存储session信息为键为username值为admin的一对数据 ?>
Create a new getsession.php and let’s do it Get the value
<?php session_start(); //使用时必须开启,如果你在php.ini里头修改了配置那么就无需在开启session了 echo $_SESSION['username']; //取出在session里存的username的值 ?>
The values obtained by different browsers are different because their sessionids are different. For example:
I use Google browser to access session.php and then generate If a session is created, then I can get the value when I access getsession.php using the same browser. When I access session.php again using the Firefox browser, a session is regenerated, and I can get the value when I access getsession.php again. to the value, but you will find that the value is not the same, because the two browsers have different sessionIDs. If you take the sessionID of Firefox and modify the sessionID of Google, then you will find that they are two The values are the same, because the session value only recognizes sessionID.
Children's shoes can try to operate it to see if it looks like this.
2. Cross-domain
If we configure our own virtual host on our own Apache/nginx server.
Mine is an Apache server, and nginx also modifies the configuration file----vhost.conf.
<VirtualHost *:80> DocumentRoot "H:\myphp_www\PHPTutorial\WWW\sessoin" ServerName www.test.com ServerAlias <Directory "H:\myphp_www\PHPTutorial\WWW\sessoin"> Options FollowSymLinks ExecCGI AllowOverride All Order allow,deny Allow from all Require all granted </Directory> </VirtualHost>
A virtual host with a virtual domain name of www.test.com has been set up. Remember to restart Apache/nginx, otherwise the configuration will not take effect.
What we have to do now is to keep the session IDs under the two domain names consistent, for example: www.test.com and localhost, provided that they are under one server.
Let’s write a Demo to implement it (not considering security and performance first)
To create a user.php, we need to pass the sessionID under the current localhost to www.test.com
<?php session_start(); //一定要先开启session $sid = session_id(); //获取到当前的sessionID ?> <a href="http://www.test.com/getsession.php?sid= <?php echo $sid;?> ">跳转</a>
If you jump directly on the page, there will be an error, because we only transmitted it and gotsession.php did not receive it, so we need to modify the getsession.php file
<?php if (isset($_GET['sid'])){ //setcookie('名字','值','有效期','域名'); $sid = $_GET['sid']; //setcookie('PHPSESSID' , $sid); //设置sessionID //或者我们还可以用另一种方式 session_id($sid); //开启session之前 指定一个sessionid } session_start(); echo $_SESSION['username']; ?>
so that we can change it according to the sessionID The consistency solves the cross-domain problem between the two domain names
3. Implement single sign-on----meaning that after logging in under localhost, you can log in simultaneously under www.test.com---- -Cross-domain request
Cross-domain requests cannot be implemented using ajax. Jsonp needs to be used for cross-domain
Create a local file in the same directory of the session folder to better distinguish the two domains
What we want to achieve now is to allow localhost and www.test.com to communicate with each other -----The premise is that it is on a server
Create an api.php under the session
<?php ?>
Create an index.html under local
<script src="www.test.com/api.php"></script> <!-- JS代码在浏览器端执行 -->
When accessing index.html under local, it will initiate two requests because the js code inside requests www.test.com/api .php
Modify the getsession.php file under session to the following content:
<?php session_start(); if(isset($_SESSION['uid'])){ echo "用户已登录,id是".$_SESSION['uid']; } else { echo "没有登录"; } ?>
Copy a copy of getsession.php under session to local
In local Create a login.php file
<?php session_start(); $_SESSION['uid'] = 18; //存储session数据键为uid值为18的一对数据 ?>
When we access login.php and then access the getsession.php file in the current directory, the result is: the user is logged in and the id is 18.
Then What we have to do now is to quietly let www.test.com log in when accessing login.php under localhost to log in.
Modify the login.php file under localhost to the following code:
<?php session_start(); $_SESSION['uid'] = 18; //存储session数据键为uid值为18的一对数据 $uid = $_SESSION['uid']; ?> <script src="www.test.com/api.php?uid=<?php echo $uid;?>" ></script>
Visit localhost/local/login.php for synchronous login, and then access localhost/local/getsession.php to already be logged in
Now visit www.test.com/getsession directly The .php file will not change in any way because we have not received the session, so we need to modify the api.php file under the session to the following code:
<?php session_start(); $uid = $_GET['uid']; $_SESSION['uid'] = $uid; ?>
In this case, visit www.test.com/getsession. When using php, it will also prompt that you have logged in
In this way, we use Jsonp to implement cross-domain requests. When logging into one website, another website can log in simultaneously
The above is the entire article Content, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Introduction to information encryption technology in PHP
How to solve the problem of PHP leaving behind after the foreach loop Array reference problem
How to solve the problem that the mui-silder plug-in in vue mui is invalid and cannot be dragged
The above is the detailed content of Session control for single sign-on in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The problem was found in the springboot project production session-out timeout. The problem is described below: In the test environment, the session-out was configured by changing the application.yaml. After setting different times to verify that the session-out configuration took effect, the expiration time was directly set to 8 hours for release. Arrived in production environment. However, I received feedback from customers at noon that the project expiration time was set to be short. If no operation is performed for half an hour, the session will expire and require repeated logins. Solve the problem of handling the development environment: the springboot project has built-in Tomcat, so the session-out configured in application.yaml in the project is effective. Production environment: Production environment release is

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Solution to the problem that the php session disappears after refreshing: 1. Open the session through "session_start();"; 2. Write all public configurations in a php file; 3. The variable name cannot be the same as the array subscript; 4. In Just check the storage path of the session data in phpinfo and check whether the sessio in the file directory is saved successfully.

The default expiration time of session PHP is 1440 seconds, which is 24 minutes, which means that if the client does not refresh for more than 24 minutes, the current session will expire; if the user closes the browser, the session will end and the Session will no longer exist.

Problem: Today, we encountered a setting timeout problem in our project, and changes to SpringBoot2’s application.properties never took effect. Solution: The server.* properties are used to control the embedded container used by SpringBoot. SpringBoot will create an instance of the servlet container using one of the ServletWebServerFactory instances. These classes use server.* properties to configure the controlled servlet container (tomcat, jetty, etc.). When the application is deployed as a war file to a Tomcat instance, the server.* properties do not apply. They do not apply,

1. Implementing SMS login based on session 1.1 SMS login flow chart 1.2 Implementing sending SMS verification code Front-end request description: Description of request method POST request path /user/code request parameter phone (phone number) return value No back-end interface implementation: @Slf4j@ ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1. Verify mobile phone number if

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site
