2013-03-31 42 views
2

我有一個cronjob,當前運行的是,當達到某個閾值時,它嘗試打開與Instagram的連接,並拉出與該標籤匹配的所有最近標記的照片。PHP +捲曲用csrfToken登錄到遠程頁面

問題是,當我嘗試啓動遠程登錄到「授權」從使用curl命令行我的應用程序,Instagram的一致與網頁說明

該頁面無法加載的響應。如果您在瀏覽器中禁用了Cookie,或者您在私密模式下瀏覽,請嘗試啓用Cookie或關閉私密模式,然後重試您的操作。

這是我的捲曲腳本。

$username = "<myusername>"; 
    $password = "<mypassword>"; 
    $useragent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31"; // Yes cause that's the way I roll 
    $cookie="InstagramCookie.txt"; 

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/'.$cookie); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/'.$cookie); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13'); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 

    $page = curl_exec($ch); 

    // try to find the actual login form 
    if (!preg_match('/<form method="POST" id="login-form" class="adjacent".*?<\/form>/is', $page, $form)) { 
     throw Instagram_Manager('Failed to find log in form!'); 
    } 

    $form = $form[0]; 

    // find the action of the login form 
    if (!preg_match('/action="([^"]+)"/i', $form, $action)) { 
     throw Instagram_Manager('Failed to find login form url'); 
    } 

    $URL2 = $action[1]; // this is our new post url 
    // find all hidden fields which we need to send with our login, this includes security tokens 
    $count = preg_match_all('/<input type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"/i', $form, $hiddenFields); 

    $postFields = array(); 

    // turn the hidden fields into an array 
    for ($i = 0; $i < $count; ++$i) { 
     $postFields[$hiddenFields[1][$i]] = $hiddenFields[2][$i]; 
    } 

    // add our login values 
    $postFields['username'] = $username; 
    $postFields['password'] = $password; 

    $post = ''; 

    // convert to string, this won't work as an array, form will not accept multipart/form-data, only application/x-www-form-urlencoded 
    foreach($postFields as $key => $value) { 
     $post .= $key . '=' . urlencode($value) . '&'; 
    } 

    $post = substr($post, 0, -1); 

    // set additional curl options using our previous options 
    curl_setopt($ch, CURLOPT_URL, "https://instagram.com/".$url2); 
    curl_setopt($ch, CURLOPT_REFERER, $url); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

    $page = curl_exec($ch); 

    file_put_contents("/tmp/page.txt", $page); 

任何想法,你有這將是有幫助的。

+0

馬克你能告訴我如何運行這個腳本。如何將圖像頁面的url傳遞給它並將其html源代碼保存到textarea? – user1788736

回答

1

嘗試了你的代碼,並修復了一些基本錯誤後正常工作。

首先檢查文件夾'/ tmp'是否存在,其中的文件是可寫和可讀的。

變化

$URL2 = $action[1]; 

$url2 = $action[1]; 

(變量爲小寫),用於

而且

"https://instagram.com/".$url2 
$url.$url2 

希望它有幫助

+0

$ url應該是什麼? – GoldenJoe