【问题标题】:PHP curl to POST form data to REST API using basic authorizationPHP curl 使用基本授权将表单数据发布到 REST API
【发布时间】:2020-01-28 13:45:44
【问题描述】:

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

HTML 表格:

<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);

【问题讨论】:

  • $name = (isset($_POST['name'])); - isset 返回一个布尔值,因此您没有在此处捕获 POST 参数的实际
  • 嗯好吧,我开始明白了,但是如果我删除了 isset,php 会抛出这个错误“notice: undefined index: name”,我该怎么做才能解决这个问题?
  • $responsecurl_close($client); 之间添加此代码echo curl_errno($client); echo curl_error($client); 以查看错误。
  • 注意:未定义索引 -> stackoverflow.com/a/4261200/10955263
  • $url = "localhost:8080/myapi/actvities";这是错字吗?

标签: php html curl


【解决方案1】:

function isset() 检查是否设置了变量并返回布尔值 true 或 false。 您可以使用以下代码:

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

$name = $_POST['name'];
$description = $_POST['description'];

【讨论】:

  • 嗯,我用你的 sn-p 更新了我的代码,现在当我运行它时,它只出现“需要名称和描述”,它并没有让我看到介绍的表格数据
【解决方案2】:

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

向您的 api 发出请求很简单

use GuzzleHttp\Client;

$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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2013-12-02
    • 2016-09-23
    相关资源
    最近更新 更多