복붙노트

PHP cURL을 사용하여 원격 사이트에 로그인하십시오.

PHP

PHP cURL을 사용하여 원격 사이트에 로그인하십시오.

나는 cURL을 사용하는 것에 익숙하지 않으며 그것을 위해 좋은 자원을 찾기가 어렵다. 내가하려는 것은 원격 사이트에 로그인하는 것입니다. 컬을 로그인 양식으로 만든 다음 성공했다고 돌려 보내야합니다.

내가 가지고있는 코드는 작동하지 않는 것처럼 보이고 사이트의 메인 페이지 만 보여줍니다.

    $username="mylogin@gmail.com"; 
$password="mypassword"; 
$url="http://www.myremotesite.com/index.php?page=login"; 
$cookie="cookie.txt"; 

$postdata = "email=".$username."&password=".$password; 

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); 
curl_setopt ($ch, CURLOPT_REFERER, $url); 

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); 
curl_setopt ($ch, CURLOPT_POST, 1); 
$result = curl_exec ($ch); 

echo $result;  
curl_close($ch);

내가 도대체 ​​뭘 잘못하고있는 겁니까. 이 작업이 끝나면 다른 페이지로 리디렉션하고 내 사이트의 콘텐츠를 가져오고 싶습니다.

해결법

  1. ==============================

    1.나는 이것을 좋았지 만 나중에 다시 방문하도록했다. 이 질문은 정기적으로 보게됩니다. 결국 결국 나를 위해 일한 것을 사용하게되었습니다.

    나는 이것을 좋았지 만 나중에 다시 방문하도록했다. 이 질문은 정기적으로 보게됩니다. 결국 결국 나를 위해 일한 것을 사용하게되었습니다.

    //username and password of account
    $username = trim($values["email"]);
    $password = trim($values["password"]);
    
    //set the directory for the cookie using defined document root var
    $dir = DOC_ROOT."/ctemp";
    //build a unique path with every request to store 
    //the info per user with custom func. 
    $path = build_unique_path($dir);
    
    //login form action url
    $url="https://www.site.com/login/action"; 
    $postinfo = "email=".$username."&password=".$password;
    
    $cookie_file_path = $path."/cookie.txt";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
    //set the cookie the site has for certain features, this is optional
    curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
    curl_setopt($ch, CURLOPT_USERAGENT,
        "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
    curl_exec($ch);
    
    //page with the content I want to grab
    curl_setopt($ch, CURLOPT_URL, "http://www.site.com/page/");
    //do stuff with the info with DomDocument() etc
    $html = curl_exec($ch);
    curl_close($ch);
    
  2. ==============================

    2.나는 같은 질문을했고 나는이 웹 사이트에서이 대답을 발견했다.

    나는 같은 질문을했고 나는이 웹 사이트에서이 대답을 발견했다.

    그리고 저는 그것을 조금 변경했습니다 (마지막 줄의 curl_close).

    $username = 'myuser';
    $password = 'mypass';
    $loginUrl = 'http://www.example.com/login/';
    
    //init curl
    $ch = curl_init();
    
    //Set the URL to work with
    curl_setopt($ch, CURLOPT_URL, $loginUrl);
    
    // ENABLE HTTP POST
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Set the post parameters
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);
    
    //Handle cookies for the login
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
    
    //Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
    //not to print out the results of its query.
    //Instead, it will return the results as a string return value
    //from curl_exec() instead of the usual true/false.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    //execute the request (the login)
    $store = curl_exec($ch);
    
    //the login is now done and you can continue to get the
    //protected content.
    
    //set the URL to the protected file
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip');
    
    //execute the request
    $content = curl_exec($ch);
    
    curl_close($ch);
    
    //save the data to disk
    file_put_contents('~/download.zip', $content);
    

    이게 네가 찾고있는 것 같아. 맞지?

    그리고 하나의 유용한 관련 질문. 세션에서 cUrl을 유지하는 방법 : https://stackoverflow.com/a/13020494/2226796

  3. ==============================

    3.로그인 페이지의 소스를 봅니다. HTML 태그 양식을 찾습니다. 그 태그 안에는 action과 같은 형태가있을 것입니다. = 폼 자체의 URL이 아닌 $ url로 그 값을 사용하십시오.

    로그인 페이지의 소스를 봅니다. HTML 태그 양식을 찾습니다. 그 태그 안에는 action과 같은 형태가있을 것입니다. = 폼 자체의 URL이 아닌 $ url로 그 값을 사용하십시오.

    또한 거기에있는 동안 입력 상자의 이름이 나열된 이름으로 지정되어 있는지 확인하십시오.

    예를 들어 기본 로그인 양식은 다음과 유사합니다.

    <form method='post' action='postlogin.php'>
        Email Address: <input type='text' name='email'>
        Password: <input type='password' name='password'>
    </form>
    

    위의 폼을 예제로 사용하여 $ url 값을 다음과 같이 변경하십시오.

    $url="http://www.myremotesite.com/postlogin.php";
    

    $ postdata에 나열한 값을 확인하십시오.

    $postdata = "email=".$username."&password=".$password;
    

    잘 작동합니다.

  4. ==============================

    4.ImpressPages에서이 문제를 해결 한 방법은 다음과 같습니다.

    ImpressPages에서이 문제를 해결 한 방법은 다음과 같습니다.

    //initial request with login data
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
    curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
    $answer = curl_exec($ch);
    if (curl_error($ch)) {
        echo curl_error($ch);
    }
    
    //another request preserving the session
    
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "");
    $answer = curl_exec($ch);
    if (curl_error($ch)) {
        echo curl_error($ch);
    }
    
  5. ==============================

    5.파나마 잭 예제 날 위해 작동하지 않습니다 - 치명적인 오류 : 정의되지 않은 함수를 호출 build_unique_path (). 나는이 코드를 사용했다 - (더 간단한 - 나의 의견) :

    파나마 잭 예제 날 위해 작동하지 않습니다 - 치명적인 오류 : 정의되지 않은 함수를 호출 build_unique_path (). 나는이 코드를 사용했다 - (더 간단한 - 나의 의견) :


    // options
    $login_email = 'alabala@gmail.com';
    $login_pass = 'alabala4807';
    $cookie_file_path = "/tmp/cookies.txt";
    $LOGINURL = "http://alabala.com/index.php?route=account/login";
    $agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

    // begin script
    $ch = curl_init();

    // extra headers
    $headers[] = "Accept: */*";
    $headers[] = "Connection: Keep-Alive";

    // basic curl options for all requests
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

    // set first URL
    curl_setopt($ch, CURLOPT_URL, $LOGINURL);

    // execute session to get cookies and required form inputs
    $content = curl_exec($ch);

    // grab the hidden inputs from the form required to login
    $fields = getFormFields($content);
    $fields['email'] = $login_email;
    $fields['password'] = $login_pass;

    // set postfields using what we extracted from the form
    $POSTFIELDS = http_build_query($fields);
    // change URL to login URL
    curl_setopt($ch, CURLOPT_URL, $LOGINURL);

    // set post options
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

    // perform login
    $result = curl_exec($ch);

    print $result;

    function getFormFields($data)
    {
    if (preg_match('/()/is', $data, $matches)) {
    $inputs = getInputs($matches[1]);

    return $inputs;
    } else {
    die('didnt find login form');
    }
    }

    function getInputs($form)
    {
    $inputs = array();
    $elements = preg_match_all("/(]+>)/is", $form, $matches);
    if ($elements > 0) {
    for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
    if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
    $name = $name[1];

    $value = '';
    if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
    $value = $value[1];
    }

    $inputs[$name] = $value;
    }
    }
    }

    return $inputs;
    }

    $grab_url='http://grab.url/alabala';

    //page with the content I want to grab
    curl_setopt($ch, CURLOPT_URL, $grab_url);
    //do stuff with the info with DomDocument() etc
    $html = curl_exec($ch);
    curl_close($ch);

    var_dump($html);
    die;

  6. from https://stackoverflow.com/questions/3008817/login-to-remote-site-with-php-curl by cc-by-sa and MIT license