IncomingRequest 클래스”

IncomingRequest 클래스는 브라우저 같은 클라이언트로부터의 HTTP 요청을 객체 지향적으로 표현한 것입니다. 이 클래스는 RequestMessage 클래스의 모든 메서드에 접근할 수 있으며, 아래에 나열된 추가 메서드도 제공합니다.

요청 접근하기”

현재 클래스가 CodeIgniter\Controller의 자손인 경우 요청 클래스의 인스턴스가 이미 채워져 있으며 클래스 속성으로 접근할 수 있습니다:”

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class UserController extends Controller
{
    public function index()
    {
        if ($this->request->isAJAX()) {
            // ...
        }
    }
}

컨트롤러 내부가 아니더라도 애플리케이션의 Request 객체에 접근해야 하면 Services class를 통해 그 복사본을 가져올 수 있습니다:”

<?php

$request = service('request');

다만, 컨트롤러가 아닌 클래스에서는 요청을 의존성으로 주입해 클래스 속성으로 저장하는 것이 바람직합니다:”

<?php

namespace App\Libraries;

use CodeIgniter\HTTP\RequestInterface;

class SomeClass
{
    protected $request;

    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
    }
}

$someClass = new SomeClass(service('request'));

요청 유형 확인”

요청은 AJAX 요청이나 커맨드 라인에서의 요청 등 여러 유형일 수 있습니다. 이는 isAJAX()isCLI() 메서드로 확인할 수 있습니다:”

<?php

// Check for AJAX request.
if ($request->isAJAX()) {
    // ...
}

// Check for CLI Request
if ($request->isCLI()) {
    // ...
}

참고

isAJAX() 메서드는 X-Requested-With 헤더에 의존하는데, 경우에 따라 JavaScript의 XHR 요청(예: fetch)에서는 기본적으로 전송되지 않습니다. 이 문제를 피하는 방법은 AJAX Requests 섹션을 참조하세요.”

is() 메서드

Added in version 4.3.0.

v4.3.0부터는 is() 메서드를 사용할 수 있습니다. 이 메서드는 HTTP 메서드, 'ajax' 또는 'json'을 인자로 받아 불리언을 반환합니다.”

참고

HTTP 메서드는 대소문자를 구분해야 하지만, 파라미터는 대소문자를 구분하지 않습니다.”

<?php

// Checks HTTP methods. Returns boolean.
$request->is('get');
$request->is('post');
$request->is('put');
$request->is('delete');
$request->is('head');
$request->is('patch');
$request->is('options');

// Checks if it is an AJAX request. The same as `$request->isAJAX()`.
$request->is('ajax');

// Checks if it is a JSON request.
$request->is('json');

getMethod()”

이 요청이 나타내는 HTTP 메서드는 getMethod() 메서드로 확인할 수 있습니다:”

<?php

// Returns 'POST'
$method = $request->getMethod();

HTTP 메서드는 대소문자를 구분하며, 관례상 표준화된 메서드는 모두 대문자 US-ASCII 문자로 정의됩니다.”

참고

v4.5.0 이전에는 기본적으로 메서드가 소문자 문자열(예: 'get', 'post' 등)로 반환되었으나, 이는 버그였습니다.”

strtolower()로 감싸면 소문자 버전을 얻을 수 있습니다::”

// Returns 'get'
$method = strtolower($request->getMethod());

요청이 HTTPS 연결을 통해 이루어졌는지 여부는 isSecure() 메서드로 확인할 수 있습니다:”

<?php

if (! $request->isSecure()) {
    force_https();
}

입력 데이터 가져오기”

Request 객체를 통해 $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV에서 입력을 가져올 수 있습니다. 이 데이터는 자동으로 필터링되지 않으며 요청으로 전달된 원시 입력 데이터가 반환됩니다.”

참고

IncomingRequest Class

The main advantages to using these methods instead of accessing them “directly ($_POST['something']), is that they will return null if the “item doesn’t exist, and you can have the data filtered. This lets you “conveniently use data without having to test whether an item exists “first. In other words, normally you might do something like this:

<?php

$something = $_POST['foo'] ?? null;

With CodeIgniter’s built-in methods you can simply do this:

<?php

$something = $request->getPost('foo');

데이터 가져오기

getGet()

The getGet() method will pull from $_GET.

  • $request->getGet()

getPost()

The getPost() method will pull from $_POST.

  • $request->getPost()

getCookie()

The getCookie() method will pull from $_COOKIE.

  • $request->getCookie()

getServer()

The getServer() method will pull from $_SERVER.

  • $request->getServer()

getPostGet()

In addition, there are a few utility methods for retrieving information “from either $_GET or $_POST, while maintaining the ability to “control the order you look for it:

  • $request->getPostGet() - checks $_POST first, then $_GET

getGetPost()

  • $request->getGetPost() - checks $_GET first, then $_POST

getVar()

중요

This method exists only for backward compatibility. Do not use it in new “projects. Even if you are already using it, we recommend that you use “another, more appropriate method.

The getVar() method will pull from $_REQUEST, so will return any “data from $_GET, $_POST, or $_COOKIE (depending on php.ini “request-order).

경고

If you want to validate POST data only, don’t use getVar(). Newer “values override older values. POST values may be overridden by the “cookies if they have the same name, and you set "C" after "P" in “request-order.

참고

If the incoming request has a Content-Type header set to “application/json, the getVar() method returns the JSON data “instead of $_REQUEST data.

JSON 데이터 가져오기

You can grab the contents of php://input as a JSON stream with “getJSON().

참고

This has no way of checking if the incoming data is valid JSON or not, “you should only use this method if you know that you’re expecting JSON.

<?php

$json = $request->getJSON();

By default, this will return any objects in the JSON data as objects. If “you want that converted to associative arrays, pass in true as the “first parameter.

The second and third parameters match up to the $depth and $flags” arguments of the json_decode() PHP function.

Getting Specific Data from JSON

You can get a specific piece of data from a JSON stream by passing a “variable name into getJsonVar() for the data that you want or you can” use "dot" notation to dig into the JSON to get data that is not on the” root level.

<?php

/*
 * With a request body of:
 * {
 *     "foo": "bar",
 *     "fizz": {
 *         "buzz": "baz"
 *     }
 * }
 */

$data = $request->getJsonVar('foo');
// $data = "bar"

$data = $request->getJsonVar('fizz.buzz');
// $data = "baz"

If you want the result to be an associative array instead of an object, “you can pass true in the second parameter:

<?php

// With the same request as above
$data = $request->getJsonVar('fizz');
// $data->buzz = "baz"

$data = $request->getJsonVar('fizz', true);
// $data = ["buzz" => "baz"]

참고

See the documentation for dot_array_search() in the Array” helper for more information on "dot" notation.

Retrieving Raw Data (PUT, PATCH, DELETE)

Finally, you can grab the contents of php://input as a raw stream “with getRawInput():

<?php

$data = $request->getRawInput();

This will retrieve data and convert it to an array. Like this:

<?php

var_dump($request->getRawInput());

/*
 * Outputs:
 * [
 *     'Param1' => 'Value1',
 *     'Param2' => 'Value2',
 * ]
 */

You can also use getRawInputVar(), to get the specified variable from” raw stream and filter it.

<?php

// When the request body is 'foo=one&bar=two&baz[]=10&baz[]=20'
var_dump($request->getRawInputVar('bar'));
// Outputs: two

// foo=one&bar=two&baz[]=10&baz[]=20
var_dump($request->getRawInputVar(['foo', 'bar']));
/*
 * Outputs:
 * [
 *      'foo' => 'one',
 *      'bar' => 'two'
 * ]
 */

// foo=one&bar=two&baz[]=10&baz[]=20
var_dump($request->getRawInputVar('baz'));
/*
 * Outputs:
 * [
 *      '10',
 *      '20'
 * ]
 */

// foo=one&bar=two&baz[]=10&baz[]=20
var_dump($request->getRawInputVar('baz.0'));
// Outputs: 10

입력 데이터 필터링

애플리케이션의 보안을 유지하려면 입력값에 접근할 때 필터링하는 것이 좋습니다. 이러한 메서드의 두 번째 인수로 사용할 필터 유형을 전달할 수 있습니다. 필터링에는 기본 제공 filter_var() 함수가 사용됩니다. 유효한 필터 유형 목록은 PHP 매뉴얼의 valid filter types을 참고하세요.

POST 변수 필터링 예시:

<?php

$email = $request->getPost('email', FILTER_SANITIZE_EMAIL);

위에서 언급한 모든 메서드는 두 번째 인수로 필터 유형을 지원하지만, getJSON()getRawInput() 은 예외입니다.

헤더 가져오기

You can get access to any header that was sent with the request with the “headers() method, which returns an array of all headers, with the key” as the name of the header, and the value is an instance of “CodeIgniter\HTTP\Header:

<?php

var_dump($request->headers());

/*
 * Outputs:
 * [
 *     'Host'          => CodeIgniter\HTTP\Header,
 *     'Cache-Control' => CodeIgniter\HTTP\Header,
 *     'Accept'        => CodeIgniter\HTTP\Header,
 * ]
 */

If you only need a single header, you can pass the name into the “header() method. This will grab the specified header object in a “case-insensitive manner if it exists. If not, then it will return “null:

<?php

// these are all equivalent
$host = $request->header('host');
$host = $request->header('Host');
$host = $request->header('HOST');

You can always use hasHeader() to see if the header existed in this “request:

<?php

if ($request->hasHeader('DNT')) {
    // Don't track something...
}

If you need the value of header as a string with all values on one line, “you can use the getHeaderLine() method:

<?php

// Accept-Encoding: gzip, deflate, sdch
echo 'Accept-Encoding: ' . $request->getHeaderLine('accept-encoding');

If you need the entire header, with the name and values in a single “string, simply cast the header as a string:

<?php

echo (string) $header;

요청 URL

You can retrieve a URI object that represents the” current URI for this request through the $request->getUri() method. “You can cast this object as a string to get a full URL for the current “request:

<?php

$uri = (string) $request->getUri();

The object gives you full abilities to grab any part of the request on “it’s own:

<?php

$uri = $request->getUri();

echo $uri->getScheme();         // http
echo $uri->getAuthority();      // snoopy:password@example.com:88
echo $uri->getUserInfo();       // snoopy:password
echo $uri->getHost();           // example.com
echo $uri->getPort();           // 88
echo $uri->getPath();           // /path/to/page
echo $uri->getRoutePath();      // path/to/page
echo $uri->getQuery();          // foo=bar&bar=baz
print_r($uri->getSegments());   // Array ( [0] => path [1] => to [2] => page )
echo $uri->getSegment(1);       // path
echo $uri->getTotalSegments();  // 3

You can work with the current URI string (the path relative to your “baseURL) using the getRoutePath().

참고

The getRoutePath() method can be used since v4.4.0. Prior to v4.4.0, “the getPath() method returned the path relative to your baseURL.

업로드된 파일

Information about all uploaded files can be retrieved through “$request->getFiles(), which returns an array of “CodeIgniter\HTTP\Files\UploadedFile instance. This helps to ease “the pain of working with uploaded files, and uses best practices to “minimize any security risks.

<?php

$files = $request->getFiles();

See Working with Uploaded Files “for the details.

You can retrieve a single file uploaded on its own, based on the filename” given in the HTML file input:

<?php

$file = $request->getFile('userfile');

You can retrieve an array of same-named files uploaded as part of a “multi-file upload, based on the filename given in the HTML file input:

<?php

$files = $request->getFileMultiple('userfile');

참고

The files here correspond to $_FILES. Even if a user just clicks “submit button of a form and does not upload any file, the file will still” exist. You can check that the file was actually uploaded by the “isValid() method in UploadedFile. See 파일 검증 for more “details.

콘텐츠 협상

You can easily negotiate content types with the request through the “negotiate() method:

<?php

$language    = $request->negotiate('language', ['en-US', 'en-GB', 'fr', 'es-mx']);
$imageType   = $request->negotiate('media', ['image/png', 'image/jpg']);
$charset     = $request->negotiate('charset', ['UTF-8', 'UTF-16']);
$contentType = $request->negotiate('media', ['text/html', 'text/xml']);
$encoding    = $request->negotiate('encoding', ['gzip', 'compress']);

See the Content Negotiation page “for more details.

클래스 참조

참고

In addition to the methods listed here, this class inherits the methods “from the Request Class and the Message “Class.

The methods provided by the parent classes that are available are:

  • CodeIgniter\HTTP\Request::getIPAddress()

  • CodeIgniter\HTTP\Request::isValidIP()

  • CodeIgniter\HTTP\Request::getMethod()

  • CodeIgniter\HTTP\Request::setMethod()

  • CodeIgniter\HTTP\Request::getServer()

  • CodeIgniter\HTTP\Request::setGlobal()

  • CodeIgniter\HTTP\Request::fetchGlobal()

  • CodeIgniter\HTTP\Message::getBody()

  • CodeIgniter\HTTP\Message::setBody()

  • CodeIgniter\HTTP\Message::appendBody()

  • CodeIgniter\HTTP\Message::populateHeaders()

  • CodeIgniter\HTTP\Message::headers()

  • CodeIgniter\HTTP\Message::header()

  • CodeIgniter\HTTP\Message::hasHeader()

  • CodeIgniter\HTTP\Message::getHeaderLine()

  • CodeIgniter\HTTP\Message::setHeader()

  • CodeIgniter\HTTP\Message::removeHeader()

  • CodeIgniter\HTTP\Message::appendHeader()

  • CodeIgniter\HTTP\Message::prependHeader()

  • CodeIgniter\HTTP\Message::getProtocolVersion()

  • CodeIgniter\HTTP\Message::setProtocolVersion()

class CodeIgniter\HTTP\IncomingRequest
isCLI()
반환:

True if the request was initiated from the command line, otherwise false.

반환 형식:

bool

isAJAX()
반환:

True if the request is an AJAX request, otherwise false.

반환 형식:

bool

isSecure()
반환:

True if the request is an HTTPS request, otherwise false.

반환 형식:

bool

getVar([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (string) – 찾을 변수/키의 이름입니다.

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_REQUEST if no parameters supplied, otherwise the REQUEST value if “found, or null if not

반환 형식:

array|bool|float|int|object|string|null

중요

This method exists only for backward compatibility. Do not use it in new “projects. Even if you are already using it, we recommend that you use “another, more appropriate method.

This method is identical to getGet(), only it fetches REQUEST data.

getGet([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (string) – 찾을 변수/키의 이름입니다.

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_GET if no parameters supplied, otherwise the GET value if found, or” null if not

반환 형식:

array|bool|float|int|object|string|null

The first parameter will contain the name of the GET item you are looking” for:

<?php

$request->getGet('some_data');

The method returns null if the item you are attempting to retrieve does “not exist.

The second optional parameter lets you run the data through the PHP’s “filters. Pass in the desired filter type as the second parameter:

<?php

$request->getGet('some_data', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

To return an array of all GET items call without any parameters.

To return all GET items and pass them through the filter, set the first “parameter to null while setting the second parameter to the filter you “want to use:

<?php

$request->getGet(null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
// returns all GET items with string sanitation

To return an array of multiple GET parameters, pass all the required keys” as an array:

<?php

$request->getGet(['field1', 'field2']);

Same rule applied here, to retrieve the parameters with filtering, set “the second parameter to the filter type to apply:

<?php

$request->getGet(['field1', 'field2'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
getPost([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (string) – 찾을 변수/키의 이름입니다.

  • $filter (int) – The type of filter to apply. A list of filters can be found here.

  • $flags (int) – Flags to apply. A list of flags can be found here.

반환:

$_POST if no parameters supplied, otherwise the POST value if found, “or null if not

반환 형식:

array|bool|float|int|object|string|null

This method is identical to getGet(), only it fetches POST data.

getPostGet([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (string) – 찾을 변수/키의 이름입니다.

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_POST and $_GET combined if no parameters specified (prefer POST” value on conflict), otherwise looks for POST value, if nothing found “looks for GET value, if no value found returns null

반환 형식:

array|bool|float|int|object|string|null

This method works pretty much the same way as getPost() and “getGet(), only combined. It will search through both POST and GET “streams for data, looking first in POST, and then in GET:

<?php

$request->getPostGet('field1');

If no index is specified, it will return both POST and GET streams “combined. Although POST data will be preferred in case of name conflict.

getGetPost([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (string) – 찾을 변수/키의 이름입니다.

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_GET and $_POST combined if no parameters specified (prefer GET “value on conflict), otherwise looks for GET value, if nothing found looks” for POST value, if no value found returns null

반환 형식:

array|bool|float|int|object|string|null

This method works pretty much the same way as getPost() and “getGet(), only combined. It will search through both GET and POST “streams for data, looking first in GET, and then in POST:

<?php

$request->getGetPost('field1');

If no index is specified, it will return both GET and POST streams “combined. Although GET data will be preferred in case of name conflict.

getCookie([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (array|string|null) – 쿠키 이름

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_COOKIE if no parameters supplied, otherwise the COOKIE value if “found or null if not

반환 형식:

array|bool|float|int|object|string|null

This method is identical to getPost() and getGet(), only it “fetches cookie data:

<?php

$request->getCookie('some_cookie');
$request->getCookie('some_cookie', FILTER_SANITIZE_FULL_SPECIAL_CHARS); // with filter

To return an array of multiple cookie values, pass all the required keys “as an array:

<?php

$request->getCookie(['some_cookie', 'some_cookie2']);

참고

Unlike the Cookie Helper function “get_cookie(), this method does NOT prepend your configured “Config\Cookie::$prefix value.

getServer([$index = null[, $filter = null[, $flags = null]]])
매개변수:
  • $index (array|string|null) – 값 이름

  • $filter (int) – The type of filter to apply. A list of filters can be found in Types of “filters.

  • $flags (int) – Flags to apply. A list of flags can be found in Filter flags.

반환:

$_SERVER item value if found, null if not

반환 형식:

array|bool|float|int|object|string|null

This method is identical to the getPost(), getGet() and “getCookie() methods, only it fetches Server data ($_SERVER):

<?php

$request->getServer('some_data');

To return an array of multiple $_SERVER values, pass all the required” keys as an array.

<?php

$request->getServer(['SERVER_PROTOCOL', 'REQUEST_URI']);
getUserAgent()
반환:

The User Agent string, as found in the SERVER data, or null if not found.

반환 형식:

CodeIgniter\HTTP\UserAgent

This method returns the User Agent instance from the SERVER data:

<?php

$request->getUserAgent();
getPath()
반환:

The current URI path relative to baseURL

반환 형식:

string

This method returns the current URI path relative to baseURL.

참고

Prior to v4.4.0, this was the safest method to determine the "current “URI", since IncomingRequest::$uri might not be aware of the complete” App configuration for base URLs.