Login to remote site with PHP cURL

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
Fargo
New php-forum User
New php-forum User
Posts: 2
Joined: Sun Aug 29, 2021 10:21 pm

Sun Aug 29, 2021 10:42 pm

Hi,

What I'm trying to do is login to a remote site, by having curl do the login form.Its hard to find good resources for it.
The code I have doesn't seem to work and only tries to show the main login page of the site.

url: https://bit.ly/2WBtwD3

Code: Select all

<?php
$username = 'user';
$password = 'pass';
$loginUrl = 'https://moj.antik.sk/';

//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, 'login='.$username.'&password='.$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, 'https://moj.antik.sk/statistics');

//execute the request
$content = curl_exec($ch);

curl_close($ch);

//save the data to disk
file_put_contents('~/file.txt', $content);
?>
Last edited by Fargo on Wed Sep 01, 2021 4:09 am, edited 1 time in total.
Fargo
New php-forum User
New php-forum User
Posts: 2
Joined: Sun Aug 29, 2021 10:21 pm

Tue Aug 31, 2021 1:29 am

Does someone have a suggestion about what is happening? I'm still trying...
codebro
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Aug 21, 2021 9:34 am

Tue Aug 31, 2021 9:23 am

Hi,

I see that the URL you are trying to hit is a shortened version from bit.ly. Curl does not follow redirections so you might be posting your content into a wrong page.

Lemme know if you manage to fix it, I will try to help.
Post Reply