php+js設置本地cookie文件的方法

博主是大三的在校大學生,學習計算機的路上,有些自己的感悟,寫下來互相討論下,歡迎吐槽。

Cookie文件常用於識別用戶。cookie 是一種服務器留在用戶計算機上的小文件。每當同一臺計算機通過瀏覽器請求頁面時,這臺計算機將會發送 cookie,讓網站服務器把少量數據儲存到客戶端的硬盤或內存,或是從客戶端的硬盤讀取數據的一種技術。從本質上講,它可以看作是你的身份證。保存的信息片斷以"名/值"對(name-value pairs)的形式儲存,一個"名/值"對僅僅是一條命名的數據。 Cookies中的內容大多數經過了加密處理,因此一般用戶看來只是一些毫無意義的字母數字組合,只有服務器的CGI處理程序才知道它們真正的含義。

如果我們設置index.html爲首頁。如果是本地cookie文件中能讀到這個用戶,說明這個用戶近期剛剛登錄過,不必再重複輸入賬號和密碼。如果用戶第一次登錄,或者cookie文件已經失效,需要從新setcookie,因此要強制返回login.html函數中去。

<!--logincheck.js-->
function getCookie(name) {
	var nameEQ = name + '=';               //處理字符串
	var ca = document.cookie.split(';');   //;分割數據
	for(var i=0;i < ca.length;i++) {
	     var c = ca[i];                     
	     while (c.charAt(0)==' ')          //讀到非空白爲止
	 	 c = c.substring(1,c.length);
	     if (c.indexOf(nameEQ) == 0)        //返回name 首次出現位置
		return c.substring(nameEQ.length,c.length);   //返回name= 後面的內容進行比較
	      }
	return null;
	}
function setCookie(name, value){
		var expdate = new Date();                    
		expdate.setTime(expdate.getTime() + (365*24*120));
		document.cookie=''+ name + '=' + value +';expires='+ expdate.toGMTString();  //設置cookie的內容失效時間
		}
function logOut(){
		setCookie('login', 'no');
		location.href='login.html';
	}
<!--index.html-->
<script src="logincheck.js" type="text/javascript"></script>  
	<script>
	if(getCookie('login') !='yes'){
	alert('你還沒有登錄,請先登錄');
	location.href='login.html';
	}
</script>
<html>
<title>index.html</title>
</html>

<!--login.html-->
<form action="check.php" method="post" >
        <tr>
        	<td><input type="text" name="userid" value="" placeholder="賬號"></td>
        	<td><input type="password" name="passwd" value="" placeholder="密碼"></td>
       </tr>
        <p class="remember_me">
          <label>
            <input type="checkbox" name="remember_me" id="remember_me">
            記住密碼
          </label>
        </p>
        <p class="submit"><input type="submit" name="commit" value="登錄"></p>
</form>

<script  src="logincheck.js"   type="text/javascript">
</script>
<?php
		error_reporting(E_ALL & ~E_NOTICE);          
		function _get($str){
			$val=!empty($_GET[$str])?$_GET[$str]:null;
			return $val;
			}
			 
		function find_user($name,$passwd){
			$conn=new Mongo("mongodb://localhost:27017");
			$collection=$conn->userxinxi->user;
			$result=false;
			$cursor=$collection->find(array("name"=>"$name"));
			foreach($cursor as $id=>$value){
					if($value["password"]!="$passwd"){
						break;
						}
					else{
						$result=true;
						return(setCookie('login','yes'));   //執行js函數
						}
				}
			return $result;
			}
	
		if(isset($_POST["commit"])){
	 		if(find_user($_POST["userid"],$_POST["passwd"])){
	 			header("Refresh: 1;url=./index.html");
	 			}
	 		else{
	 			header('Refresh: 1; url=./login.html');
	 			}
	 						
		} 
?>   			



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章