Link to home
Create AccountLog in
Avatar of AndreiPociu
AndreiPociu

asked on

Maintain session using fsockopen()

My objective is to remotely submit a form using PHP. Using the function shown below, I managed to do just that.
But now I have a problem: there is another form I need to submit, but for submitting that form I first need to log in on the website using another form. It was very easy to do that, but the problem is my session is not kept, so when I move to the second form after logging in, it appears as if I'm logged out (session is null), and of course, it doesn't get submitted successfuly.

Thanks in advance for your help.
Below you can see the function which currently works without problems, but doesn't keep the session. Also, will your solution (if there is one) also work for cookies?

function auto_post($url, $data, $read_response = false)
{
   $url = parse_url($url);
   $request = "POST ".$url['path']." HTTP/1.1\r\n".
              "Host: ".$url['host']."\r\n".
              "Content-type: application/x-www-form-urlencoded\r\n".
              "User-Agent: Mozilla 4.0\r\n".
              "Content-length: ".strlen($data)."\r\n".
              "Connection: close\r\n\r\n".
              $data;

   $fp = @fsockopen($url['host'], 80, $error_no, $error_msg);
   if(!$fp){
     die("Couldn't Connect To {$url['host']} <br />\r\n Error Number: $error_no <br />\r\n Error Message: $error_msg.");
   }
   @fwrite($fp,$request);

   if($read_response){
        $headers = '';
        while (!feof($fp)) {
            $line_cur = fgets($fp, 4096);
            $headers .= $line_cur;
            if (($line_cur == "\r\n") || ($line_cur == "\n")) {
                break;
            }
        }
        $body = '';
        while (!feof($fp)) {
            $line_cur = fgets($fp, 4096);
            $body .= $line_cur;
        }
   }
   @fclose($fp);
   return ($read_response ? array('headers'=>$headers, 'body'=>$body) : true);
}
auto_post('http://www.website.com/login.php', 'User=something&Pass=1234');
// Right here the log in is successful, but the session is not set / not kept
auto_post('http://www.website.com/submitarticle.php', 'title=something&author=1');
ASKER CERTIFIED SOLUTION
Avatar of sjohnstone1234
sjohnstone1234
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
(you're probably aware, but generally sessions are maintained using cookies - so any approach that supports cookies should maintain your sessions as well)
Avatar of AndreiPociu
AndreiPociu

ASKER

Thanks Simon. I was looking into cURL even before using fsockopen(), since I used cURL when working with Authorize.Net and other merchant accounts. However, since I then saw fsockopen() examples, I decided it to use instead. Now I see that cURL does exactly what I want.