Reputation: 13111
I have following code in Python that is working good (have access):
import requests
username = 'user'
password = 'pass'
r = requests.get('https://internalwebsite/list', auth=(username, password))
j = r.json()
How do I write that in PHP?
I tried similiar like this but no success so far:
$postvars = "username=user&password=pass";
$url = "https://internalwebsite/list";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
Regular cURL command works good as well (has response):
curl -u 'user:pass' https://internalwebsite/list
Thanks.
Upvotes: 2
Views: 1294
Reputation: 665
I believe you should be using the CURLOPT_USERPWD, instead of submitting the postvars for this particular use case(based on your comment to my previous solution)
$url = "https://internalwebsite/list";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERPWD, "myusername:mypassword");
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
Upvotes: 1
Reputation: 1750
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, ( $url . '?' . $postvars ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec($ch);
curl_close($ch);
echo "response is $response";
Upvotes: 0
Reputation: 959
You need to enable HTTP POST
by curl_setopt($ch, CURLOPT_POST, 1);
instead of curl_setopt($ch, CURLOPT_POST, 0);
if you are using POST. Try this
$username = 'user';
$password = 'pass';
$url = 'https://internalwebsite/list';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $url);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user=' . $username . '&pass=' . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close($ch);
Upvotes: 0