拋開(kāi)Cookie使用SESSION-PHP中SESSION不能跨頁(yè)傳遞問(wèn)題的解決辦法
Jun 21, 2016 am 09:15 AMcookie|session|解決|問(wèn)題
拋開(kāi)cookie使用session
PHP中SESSION不能跨頁(yè)傳遞問(wèn)題的解決辦法
在PHP中使用過(guò)SESSION的朋友可能會(huì)碰到這么一個(gè)問(wèn)題,SESSION變量不能跨頁(yè)傳遞。這令我苦惱了好些日子,最終通過(guò)查資料思考并解決了這個(gè)問(wèn)題。我認(rèn)為,出現(xiàn)這個(gè)問(wèn)題的原因有以下幾點(diǎn):
1、客戶端禁用了cookie
2、瀏覽器出現(xiàn)問(wèn)題,暫時(shí)無(wú)法存取cookie
3、php.ini中的session.use_trans_sid = 0或者編譯時(shí)沒(méi)有打開(kāi)--enable-trans-sid選項(xiàng)
為什么會(huì)這樣呢?下面我解釋一下:
Session儲(chǔ)存于服務(wù)器端(默認(rèn)以文件方式存儲(chǔ)session),根據(jù)客戶端提供的session id來(lái)得到用戶的文件,取得變量的值,session id可以使用客戶端的Cookie或者Http1.1協(xié)議的Query_String(就是訪問(wèn)的URL的“?”后面的部分)來(lái)傳送給服務(wù)器,然后服務(wù)器讀取Session的目錄……。也就是說(shuō),session id是取得存儲(chǔ)在服務(wù)上的session變量的身份證。當(dāng)代碼session_start();運(yùn)行的時(shí)候,就在服務(wù)器上產(chǎn)生了一個(gè)session文件,隨之也產(chǎn)生了與之唯一對(duì)應(yīng)的一個(gè)session id,定義session變量以一定形式存儲(chǔ)在剛才產(chǎn)生的session文件中。通過(guò)session id,可以取出定義的變量??珥?yè)后,為了使用session,你必須又執(zhí)行session_start();將又會(huì)產(chǎn)生一個(gè)session文件,與之對(duì)應(yīng)產(chǎn)生相應(yīng)的session id,用這個(gè)session id是取不出前面提到的第一個(gè)session文件中的變量的,因?yàn)檫@個(gè)session id不是打開(kāi)它的“鑰匙”。如果在session_start();之前加代碼session_id($session id);將不產(chǎn)生新的session文件,直接讀取與這個(gè)id對(duì)應(yīng)的session文件。
PHP中的session在默認(rèn)情況下是使用客戶端的Cookie來(lái)保存session id的,所以當(dāng)客戶端的cookie出現(xiàn)問(wèn)題的時(shí)候就會(huì)影響session了。必須注意的是:session不一定必須依賴cookie,這也是session相比cookie的高明之處。當(dāng)客戶端的Cookie被禁用或出現(xiàn)問(wèn)題時(shí),PHP會(huì)自動(dòng)把session id附著在URL中,這樣再通過(guò)session id就能跨頁(yè)使用session變量了。但這種附著也是有一定條件的,即“php.ini中的session.use_trans_sid = 1或者編譯時(shí)打開(kāi)打開(kāi)了--enable-trans-sid選項(xiàng)”。
明白了以上的道理,現(xiàn)在我們來(lái)拋開(kāi)cookie使用session,主要途徑有三條:
1、設(shè)置php.ini中的session.use_trans_sid = 1或者編譯時(shí)打開(kāi)打開(kāi)了--enable-trans-sid選項(xiàng),讓PHP自動(dòng)跨頁(yè)傳遞session id。
2、手動(dòng)通過(guò)URL傳值、隱藏表單傳遞session id。
3、用文件、數(shù)據(jù)庫(kù)等形式保存session_id,在跨頁(yè)過(guò)程中手動(dòng)調(diào)用。
通過(guò)例子來(lái)說(shuō)明吧:
s1.php
session_start();
$_SESSION['var1']="中華人民共和國(guó)";
$url="下一頁(yè)";
echo $url;
?>
s2.php
session_start();
echo "傳遞的session變量var1的值為:".$_SESSION['var1'];
?>
運(yùn)行以上代碼,在客戶端cookie正常的情況下,應(yīng)該可以在得到結(jié)果“中華人民共和國(guó)”。
現(xiàn)在你手動(dòng)關(guān)閉客戶端的cookie,再運(yùn)行,可能得不到結(jié)果了吧。如果得不到結(jié)果,再“設(shè)置php.ini中的session.use_trans_sid = 1或者編譯時(shí)打開(kāi)打開(kāi)了--enable-trans-sid選項(xiàng)”,又得到結(jié)果“中華人民共和國(guó)”
這也就是上面所說(shuō)的途徑1。
下面再說(shuō)途徑2:
修改的代碼如下:
s1.php
session_start();
$_SESSION['var1']="中華人民共和國(guó)";
$sn = session_id();
$url="下一頁(yè)";
echo $url;
?>
s2.php
session_id($_GET['s']);
session_start();
echo "傳遞的session變量var1的值為:".$_SESSION['var1'];
?>
辦法3還是通過(guò)例子來(lái)說(shuō)明:
login.html
請(qǐng)登錄:
mylogin1.php
$name=$_POST['name'];
$pass=$_POST['pass'];
if(!$name || !$pass) {
echo "用戶名或密碼為空,請(qǐng)重新登錄";
die();
}
if (!($name=="laogong" && $pass=="123")) {
echo "用戶名或密碼不正確,請(qǐng)重新登錄";
die();
}
//注冊(cè)用戶
ob_start();
session_start();
$_SESSION['user']= $name;
$psid=session_id();
$fp=fopen("e:\\tmp\\phpsid.txt","w+");
fwrite($fp,$psid);
fclose($fp);
//身份驗(yàn)證成功,進(jìn)行相關(guān)操作
echo "已登錄
";
echo "下一頁(yè)";
?>
mylogin2.php
$fp=fopen("e:\\tmp\\phpsid.txt","r");
$sid=fread($fp,1024);
fclose($fp);
session_id($sid);
session_start();
if(isset($_SESSION['user']) && $_SESSION['user']="laogong" ) {
echo "已登錄!";
}
else {
//成功登錄進(jìn)行相關(guān)操作
echo "未登錄,無(wú)權(quán)訪問(wèn)";
echo "請(qǐng)登錄后瀏覽";
die();
}
?>
同樣請(qǐng)關(guān)閉cookie測(cè)試,用戶名:laogong 密碼:123 這是通過(guò)文件保存session id的,文件是:e:\tmp\phpsid.txt,請(qǐng)根據(jù)自己的系統(tǒng)決定文件名或路徑。
至于用數(shù)據(jù)庫(kù)的方法,我就不舉例子了,與文件的方法類似。
總結(jié)一下,上面的方法有一個(gè)共同點(diǎn),就是在前一頁(yè)取得session id,然后想辦法傳到下一頁(yè),在下一頁(yè)的session_start();代碼之前加代碼session_id(傳過(guò)來(lái)的session id);
注:本人測(cè)試環(huán)境:Win2K Sever Aapache 1.3.31 PHP 4.3.4
另外,lidm在類unix系統(tǒng)上也測(cè)試通過(guò)

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
