Validation 如何在PHP中解析/验证/处理http头

Validation 如何在PHP中解析/验证/处理http头,validation,http,header,psr-7,php-fig,Validation,Http,Header,Psr 7,Php Fig,目前我正在构建自己的php框架,现在我正在创建一个php-FIG PSR-7 MessageInterface的实现。具体来说,使用withHeader方法。它声明该方法可以为无效的头名称或值创建一个exeption:\InvalidArgumentException 所以我想知道,什么时候头是有效的还是无效的?值也一样。 或者我应该接受任何标题和任何标题值吗?那可能很危险,对吧 我现在可以说,如果一个头有多个值,它们是逗号分隔的。但这并不总是适用的。例如,如果我查看用户代理头,值本身有时包含逗

目前我正在构建自己的php框架,现在我正在创建一个php-FIG PSR-7 MessageInterface的实现。具体来说,使用withHeader方法。它声明该方法可以为无效的头名称或值创建一个exeption:\InvalidArgumentException

所以我想知道,什么时候头是有效的还是无效的?值也一样。 或者我应该接受任何标题和任何标题值吗?那可能很危险,对吧

我现在可以说,如果一个头有多个值,它们是逗号分隔的。但这并不总是适用的。例如,如果我查看用户代理头,值本身有时包含逗号。但是你应该把它当作一个单一的值。

你可以在中找到它。检查Zend Diactoro的实现。

事实上,将标题名作为
withHeader()的参数传递是“危险的”,因为

  • NULL
  • 不是字符串
  • 是一个空字符串
这同样适用于标题值参数。它必须是数组或字符串(仅表示一个值,而不是逗号分隔的值列表!)

至于
withHeader
方法的实现:

/**
 * Return an instance with the provided value replacing the specified header.
 *
 * ...
 *
 * @param string $name Case-insensitive header field name.
 * @param string|string[] $value Header value(s).
 * @return static
 * @throws \InvalidArgumentException for invalid header names or values.
 */
public function withHeader($name, $value) {
    $this
            ->validateHeaderName($name)
            ->validateHeaderValue($value)
    ;

    $clone = clone $this;

    $clone->replaceHeader($name, $value);

    return $clone;
}

/**
 * =================
 * Not part of PSR-7
 * =================
 * 
 * Validate header name.
 * 
 * @param string $name Case-insensitive header field name.
 * @return $this
 * @throws \InvalidArgumentException
 */
protected function validateHeaderName($name) {
    if (!isset($name)) {
        throw new \InvalidArgumentException('No header name provided!');
    }

    if (!is_string($name)) {
        throw new \InvalidArgumentException('The header name must be a string!');
    }

    if (empty($name)) {
        throw new \InvalidArgumentException('Empty header name provided!');
    }

    return $this;
}

/**
 * =================
 * Not part of PSR-7
 * =================
 * 
 * Validate header value.
 * 
 * @param string|string[] $value Header value(s).
 * @return $this
 * @throws \InvalidArgumentException
 */
protected function validateHeaderValue($value) {
    if (isset($value) && !is_array($value) && !is_string($value)) {
        throw new \InvalidArgumentException('The header value must be a string or an array!');
    }

    return $this;
}

/**
 * =================
 * Not part of PSR-7
 * =================
 * 
 * Replace a header item with a new one.
 * 
 * @param string $name Case-insensitive header field name.
 * @param string|string[] $value Header value(s).
 * @return $this
 * @done
 */
protected function replaceHeader($name, $value) {
    $this
            ->removeHeader($name)
            ->addHeader($name, $value)
    ;

    return $this;
}