本文主要是介绍JavaScriptCookiePHPCookie实现用户登录信息自动填入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
步骤:
1.登录表单的加载;
2.在加载登录表单后,引入的js会执行,给表单中加载值;
3.在没有cookie的情况下,登录跳转到主页过的服务器会存储cookie;
4.跳转到主页,主页在这里就不再展示啦!
一、登录页面login.html表单
<form action="ServerLogin.php" method="post" enctype="application/x-www-form-urlencoded"><input id="us" type="text" name="username" class="username" placeholder="Username"><input id="pw" type="password" name="password" class="password" placeholder="Password"><button type="submit">Sign me in</button><div class="error"><span>+</span></div> </form>
二、登录页引入js
<!--引入自动添加用户信息的cookie的js--> <script src="autoAddCookie.js"></script>
三、
文件autoAddCookie.js的cookie获取如下:
$(function () {initialValue();function initialValue() {//jQuery方式 $("#us").val(getCookieByKey("username"));$("#pw").val(getCookieByKey("password"));//javaScript方式 // document.getElementById("us").value = getCookieByKey("username"); // document.getElementById("pw").value = getCookieByKey("password"); }//javaScript Cookie获取 function getCookieByKey(key) {var cookie = document.cookie.split(";");for (i = 0; i < cookie.length; i++) {var value = cookie[i].trim();if (value.indexOf(key) == 0) {v = value.split("=");return v[1];}}} }); /** * Created by 洋 汪 on 2016/7/19. */
javaScript Cookies的设置获取详解在我的下边博文:http://blog.csdn.net/u013005050/article/details/51966626
四、服务器文件设置PHPcookie,ServerCookie.php
<?php /** * Created by PhpStorm. * User: 洋 汪 * Date: 2016/7/19 * Time: 11:53 */ header("Content-type:text/html;charset=utf-8"); include "data.php"; if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_POST["username"] == $info["username"] && $_POST["password"] == $info["password"]) { //设置cookie setCookieByKey($_POST["username"], $_POST["password"]); //设置session $mySession = $_POST; $mySession = array_merge($mySession, array("loginIp" => $_SERVER["REMOTE_ADDR"], "loginTime" => time())); setSession($mySession); echo "<script>window.location.href ='index.php';</script>"; } else { echo "<script>alert('用户名或密码错误!!!');</script>"; } } else { echo "<script> alert('请登录!!!'); window.location.href = 'login.html'; </script>"; } //设置session function setSession(array $mySession) { session_start(); // $_SESSION = $mySession; //Array ( [username] => wangyang [password] => 123456 [loginIp] => 127.0.0.1 [login_time] => 1468915628 ) // print_r($_SESSION); $_SESSION["username"] = $mySession["username"]; $_SESSION["password"] = $mySession["password"]; $_SESSION["loginIp"] = $mySession["loginIp"]; $_SESSION["loginTime"] = $mySession["loginTime"]; } //设置Cookie function setCookieByKey($username, $password) { setcookie("username", $username, time() + 120); setcookie("password", $password, time() + 120); } ?>PHP Cookie的详细讲解在我的博文当中,PHP Cookie的链接地址等我发表通过后,展示出来。
这篇关于JavaScriptCookiePHPCookie实现用户登录信息自动填入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!