1. 程式人生 > >php解決session跨域,驗證碼無效問題。

php解決session跨域,驗證碼無效問題。

isset($_GET['getcode'])

最近在專案中遇到.net域名下通過iframe載入.cn域名網站。註冊的時候驗證碼失效了。其中也找到了辦法,不過不相容ie8及以下瀏覽器。一直反覆測試。今天終於成功了。

對於上面的一句話的前半句解釋下,估計有的同學搞不懂邏輯關係:訪問 www.abc.net (A站) 可以看到www.abc.cn(B站) 的網站內容,從而進行註冊。有的同學會問,幹嘛這麼費勁,域名解析到同一伺服器不就完了。可是兩個域名不是同一個人 買的,總之是不願解析。

好,閒話不扯了。

任務:通過A站ifarme載入B站然後註冊。

問題:儲存在session中驗證碼丟失,一直提示驗證碼錯誤。

解題思路:

1.session,cookie都不用。那就在頭部資訊傳遞引數。把驗證碼資訊寫入header中。

2.註冊頁面獲取驗證碼做特殊處理。img的src丟空,onclick也不要,加入id。寫一個函式獲取驗證碼然後把圖片賦值給img

解決步驟:

1.生成驗證碼頁:header('Code:abcdefg') ; 在圖片輸出前寫

.註冊頁:

2.驗證碼input 和img 標籤<input type="text" name="code"  ><img src="" id="img"> 

3.js程式碼:

autocode();//頁面載入完成 
$("#img").bind("click",function(){ autocode() }) ; //每次點選
function autocode()
{//獲取驗證碼
$.get('',{"action":"getcode"},function(data){
$("#img").attr('src',data)
});

}

4.當頁PHP程式碼:


if( isset($_GET['action']) && $_GET['action']=='getcode' )
{
$url = 'http://www.abc.cn/a.jpg';
$img = file_get_contents($url);
$info = $http_response_header;

}




1.獲取頭部資訊

$http_response_header — HTTP 響應頭

說明$http_response_header陣列與  函式類似。當使用HTTP 包裝器時,$http_response_header 將會被 HTTP 響應頭資訊填充。
$http_response_header 將被創建於區域性作用域中。

<?php
function get_contents() {
  file_get_contents("http://example.com");
  var_dump($http_response_header);
}
get_contents();
var_dump($http_response_header);
?>
/*
//列印資訊
array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}
NULL
*/
//頭部資訊解析函式
function parseHeaders( $headers )
{
    $head = array();
    foreach( $headers as $k=>$v )
    {
        $t = explode( ':', $v, 2 );
        if( isset( $t[1] ) )
            $head[ trim($t[0]) ] = trim( $t[1] );
        else
        {
            $head[] = $v;
            if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
                $head['reponse_code'] = intval($out[1]);
        }
    }
    return $head;
}

print_r(parseHeaders($http_response_header));

/*
Array
(
    [0] => HTTP/1.1 200 OK
    [reponse_code] => 200
    [Date] => Fri, 01 May 2015 12:56:09 GMT
    [Server] => Apache
    [X-Powered-By] => PHP/5.3.3-7+squeeze18
    [Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/
    [Expires] => Thu, 19 Nov 1981 08:52:00 GMT
    [Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    [Pragma] => no-cache
    [Vary] => Accept-Encoding
    [Content-Length] => 872
    [Connection] => close
    [Content-Type] => text/html
)
*/