我在这里尝试使用 php 和 restfull web 服务登录一个表单,每当我尝试执行它时都会弹出基本的身份验证用户名和密码。它必须自动通信,在我的情况下它没有发生不知道我哪里出错了?
<?php
if(isset($_POST['submit'])){
$postData = array('userId'=>$_POST['userId'],'password'=> $_POST['password']);
$authToken = base64_encode( "rest:rest" );
// Setup cURL
$ch = curl_init('http://xxxxxxxxxxx:8080/LIMS_Mobile/rest/loginpage/authenticate');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic'.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
print_r($responseData);
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form method="post" name="myForm" class="form-horizontal">
<div class="row">
<div class= "form-group">
<label class= "col-md-2"> UserId </label>
<div class="col-md-4">
<input name="userId" type= "text" class= "form-control" placeholder="Your name" required/>
</div>
</div>
<div class= "form-group">
<label class= "col-md-2"> Passeord </label>
<div class="col-md-4">
<input name="password" type= "text" class= "form-control" placeholder="Your name" required/>
</div>
</div>
<div class= "form-group">
<label class= "col-md-2"></label>
<div class="col-md-4">
<input type="submit" name="submit"/>
</div>
</div>
</div>
</form>
</body>
</html>
最佳答案
为了在 curl 请求中使用基本身份验证,您应该在请求中同时使用 CURLOPT_HTTPAUTH
和 CURLOPT_USERPWD
选项:
$curl = curl_init();
....
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
如果您使用的是 curl_setopt_array
函数,您可以这样做:
$curl = curl_init();
curl_setopt_array($curl, [
...
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => "username:password",
]);
请注意,特别是在您的代码中,Basic
和 token 之间缺少一个空格。
关于php表单通过基本认证restful api提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746424/