我在Python中有以下代码正常工作(有访问权限):
import requests
username = 'user'
password = 'pass'
r = requests.get('https://internalwebsite/list', auth=(username, password))
j = r.json()
如何在PHP中编写?
我尝试过这样的类似但到目前为止没有成功:
$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);
常规cURL命令也很好(有响应):
curl -u 'user:pass' https://internalwebsite/list
感谢。
答案 0 :(得分:1)
我相信您应该使用CURLOPT_USERPWD,而不是为此特定用例提交postvars(根据您对我以前的解决方案的评论)
$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);
答案 1 :(得分:0)
如果您使用POST,则需要HTTP POST
而不是curl_setopt($ch, CURLOPT_POST, 1);
启用curl_setopt($ch, CURLOPT_POST, 0);
。试试这个
$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);
答案 2 :(得分:0)
$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";