PHP中使session可以跨視窗啟動並執行方法

來源:互聯網
上載者:User

這本來是session的基本用法,但在php中就不靈了。不過我們可以把session變數註冊成"跨視窗的全域變數"。但這有一個條件,就是要向需要使用該session變數的視窗發送變數名為session_name(),值為session_id()的變數,用表單或者在url後面用?帶上都可以.並且在使用session變數的頁面的一開始處調用session_start()。

例子如下:

login.php檔案:



<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登陸畫面</title>
</head>
<body>
<form action="result.php" method="post">
  
<table width="100%" border="0">
  
<tr>
    
<td align="center" valign="middle"><p>測試系統-----登陸畫面</p>
        
<table width="250" style="border-collapse:collapse; border-color:#000000"
            border
="1" cellpadding="2" cellspacing="2">
            
<tr>
                
<td width="30%">使用者:</td>
                
<td><input name="username" type="text" style="width:150px"/></td>
            
</tr>
            
<tr>
                
<td>密碼:</td>
                
<td><input name="password" type="password" style="width:150px"/></td>
            
</tr>
            
<tr>
                
<td colspan="2" align="center"><input type="submit" value="登陸"/></td>
            
</tr>
        
</table>
    
</td>
  
</tr>
</table>
</form>
</body>
</html>

result.php檔案:



<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>結果畫面</title>
</head>
<body>
<form method="post">
    歡迎你, 
    
<?php
        @
session_start();
        
if(isset($_POST["username"])){
            
$username = htmlspecialchars($_POST["username"]);
            
$_SESSION[''username''= $username;
        } 
else {
            
$username = $_SESSION[''username''];
        }
        
echo $username
    
?>
    
<br/>
    
<br/>
    
<a href="login.php">返回</a>
    
<a href="database.php?".session_name()."=".session_id()."">資料庫測試</a>
    
</form>
</body>
</html>

database.php檔案:



<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>結果畫面</title>
</head>
<body>
<form method="post">
    Email:
    
<?php
        @
session_start();
    
        
$conn = mssql_pconnect(''localhost'', ''sa'', ''sa'');
        mssql_select_db(
''netstore'');
        
$query =  mssql_query(''select * from CUSTOMER'', $conn);
        
$name =  mssql_result($query, 0, ''email'');
        
echo $name;
    
?>
    
<br/>
    
<br/>
    
<a href="result.php?".session_name()."=".session_id()."">返回</a>
</form>
</body>
</html>


 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.