PHP curl to POST 表单数据到使用 REST API 使用基本授权



我是PHP的新手,我正在为我的大学科目开发一个简单的客户端。此客户端的主要目标是将 CRUD 执行到 JAVA API 中。经过一番研究,我发现对于像这样的简单客户端,人们使用 CURL。我从来没有用过卷曲,我不知道我是否做错了什么。当我提交表单时,它不会出现任何错误,但是当我打开邮递员时,我看到我的数据没有成功发布。 如果有人能帮助我,我将不胜感激!

表格:

<form class="form" action="createActivity.php">
<label for="name" class="labelActivityName"><b>Name</b></label>
<input type="text" id="name" placeholder="Name" name="name">
<label for="description" class="labelActivityDescription"><b>Description</b></label>
<textarea id="description" placeholder="Description..." name="description"></textarea>
<button type="submit"><b>Submit</b></button>
</form>
PHP CURL:
$url = "http://localhost:8080/myapi/actvities";
$username = 'user';
$password = 'user123';
$name = (isset($_POST['name']));
$description = (isset($_POST['description']));
$fields = array(
'name' => $name,
'description' => $description
);
$client = curl_init();
curl_setopt($client, CURLOPT_URL, $url);
curl_setopt($client, CURLOPT_RETURNTRANSFER,1);
curl_setopt($client, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($client, CURLOPT_USERPWD, "$username:$password");
curl_setopt($client, CURLOPT_POST, 1);
curl_setopt($client, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($client);
curl_close($client);

函数isset((检查变量是否被设置并返回布尔值真或假。 您可以使用以下代码:

if (! (isset($_POST['name']) && isset($_POST['description']))) {
http_response_code(422);
echo 'name and description are required.';
exit;
}
$name = $_POST['name'];
$description = $_POST['description'];

我建议你尝试安装guzzle。 http://docs.guzzlephp.org/en/stable/quickstart.html

对您的 api 发出请求很简单,就像

use GuzzleHttpClient;
$client = new Client();
$response = $client->post('adsf', [
'auth' => ['username', 'password'], // basic auth
// sending data via form request
'form_params' => [
'name' => 'Some name',
'description' => 'Some description'
]
]);
var_dump($response->getBody());
var_dump($response->getStatusCode());

最新更新