csha
csha

Reputation: 9604

File_get_contents receive and send cookies

I am trying to make an unofficial API for server Strava.cz using PHP's function file_get_contents(); but it doesn't work. What's wrong? :'(

function strava_czLogin($machine,$user,$pass){
//Sends the request
$src = file_get_contents(
            'http://m.strava.cz/Stravnik/formprihlaseni.aspx',
            false,
            stream_context_create(
             array('http'=>array('header' => "User-Agent:(none; StravaCekujNET; Linux x86_64; rv:1.0)\r\n"))
            )
           );
$src = mb_convert_encoding($src,'utf-8','auto'); //Encoding correction

//Works with the cookies (yummy!)
$cookies = array();
foreach ($http_response_header as $value) {
    if (preg_match('/^Set-Cookie:\s*([^;]+)/', $value, $matches)) {
        parse_str($matches[1], $tmp);
        $cookies += $tmp;
    }
}

$sessionId = "";
foreach ($cookies as $key => $value) {
    if ($key == "ASP_NET_SessionId"){$sessionId = $value;}
}

//Checks the result and returns the sessionId
if (preg_match('<form name="aspnetForm" method="post" action="stravnik.aspx" id="aspnetForm">',$src)){
     return array(true,$sessionId);
    }else{
     return array(false,null);
    }
}

function strava_czCheck($sessionId){
    //Sends request
    $src = file_get_contents('http://m.strava.cz/Stravnik/objednavky.aspx',false,stream_context_create(array('http'=>array('header' => "User-Agent:(none; StravaCekujNET; Linux x86_64; rv:1.0)\r\nCookie: ASP_NETSession=".$sessionId."\r\n"))));
    $src = mb_convert_encoding($src,'utf-8','auto'); //Zajistí správné kódování
    echo $src; //Prints the response - "Application Error"

    //Some irrelevant code here


    //Returns the result
    if ($arr==null) {return array(false,null);}
    else {return array(true,$arr);}
}

The server returns "Application Error" like when you're logged out.
And don't ask me why I'm doing this - I'm the man who asks :D

Upvotes: 0

Views: 2213

Answers (1)

Rupesh Patel
Rupesh Patel

Reputation: 3065

If you want to deal with cookies, use curl. Maybe this will help: https://rupeshpatel.wordpress.com/2012/05/12/general-purpose-function-for-curl/

Upvotes: 1

Related Questions