Php check request content type

Как получить содержимое POST на php?

Я отправляю POST на страницу php следующее:

Это тело запроса (запрос POST).

Что мне нужно сделать в php, чтобы извлечь это значение?

var_dump($_POST);

Этот код не работает.

Ответ 1

Чтобы получить доступ к содержимому объекта запроса POST или PUT (или любого другого метода HTTP):

$entityBody = file_get_contents(‘php://input’);

Кроме того, STDIN константа — это уже открытый поток php://input , поэтому вы можете в качестве альтернативы сделать:

$entityBody = stream_get_contents(STDIN);

Из документации PHP по потокам ввода-вывода :

php: // input — это поток только для чтения, который позволяет вам читать необработанные данные из содержимого запроса. В случае запросов POST предпочтительнее использовать запрос php: // вместо того, чтобы использовать $HTTP_RAW_POST_DATA, который зависит от специальных директив php.ini. Более того, для тех случаев, когда $HTTP_RAW_POST_DATA не устанавливается по умолчанию, это потенциально менее ресурсоемкая альтернатива установки .

always_populate_raw_post_data. php: // ввод недоступен с enctype = «multipart/form-data».

В этом случае, если поток php://input , к которому вы обращаетесь как веб-SAPI, будет недоступен для поиска . Это означает, что его можно прочитать только один раз. Если вы работаете в среде, где регулярно загружается содержимое HTTP, вы можете сохранить ввод в его потоковой форме (а не буферизовать его).

Для реализации потокового ресурса можно выполнить что-то вроде этого:

function detectRequestBody()

$rawInput = fopen(‘php://input’, ‘r’);

$tempStream = fopen(‘php://temp’, ‘r+’);

stream_copy_to_stream($rawInput, $tempStream);

rewind($tempStream);

return $tempStream;

>

php://temp позволяет вам управлять потреблением памяти, потому что это прозрачно переключается на хранилище файловой системы после сохранения определенного количества данных (по умолчанию 2M). Этим размером можно управлять в файле php.ini или добавляя /maxmemory:NN , где NN — это максимальный объем данных в байтах, которые необходимо сохранить в памяти перед использованием временного файла.

Конечно, если у вас нет действительно веской причины для поиска во входном потоке, вам не понадобится эта функция в веб-приложении. Обычно достаточно одного чтения содержимого объекта HTTP-запроса – нет необходимости заставлять клиентов ждать долгое время для выяснения, что делает в а ше приложение.

Обратите внимание, что ввод php: // недоступен для запросов с указанием заголовка « Content-Type: multipart/form-data ( enctype=»multipart/form-data» в HTML-формах)». Это происходит из-за того, что интер прет атор PHP уже проанализировал данные формы в $_POST .

Ответ 2

Возможное решение:

function getPost()

if(!empty($_POST))

// когда в качестве HTTP Content-Type в запросе используется application/x-www-form-urlencoded или multipart/form-data

// ПРИМЕЧАНИЕ: если это так и $_POST пуст, можно проверить порядок переменных (variables_order) в php.ini! — они должны содержать букву P

Читайте также:  Website template design in html

return $_POST;

>

// при использовании application/json в качестве HTTP Content-Type в запросе

$post = json_decode(file_get_contents(‘php://input’), true);

if(json_last_error() == JSON_ERROR_NONE)

return $post;

>

return [];

>

print_r(getPost());

Ответ 3

Этот пример о том, как создать PHP API с file_get_contents(«php://input») , и об использовании с javascript в связке с ajax XMLHttpRequest .

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function ()

if (this.readyState == 4 && this.status == 200)

console.log(«done»);

>

>

>;

xhttp.open(«POST», «http://127.0.0.1:8000/api.php», true);

xhttp.send(JSON.stringify(

username: $(this).val(),

email:email,

password:password

>));

$data = json_decode(file_get_contents(«php://input»));

$username = $data->username;

$email = $data->email;

$password = $data->password;

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

Check Content-type POST request PHP

For example, Question: I’m trying to use an online service that requires to read the body of post requests at a callback url (webhook). Question: I have a time tracking application where every time that a new Time Entry is about to be added, I must first verify that all the previous time entries have been closed (meaning that an ending date has been set) and throw and error message using the validate() method.

Check Content-type POST request PHP

How can I check if the Content-type of a POST request in PHP is either application/json or application/x-www-form-urlencoded?

I’ve tried using $_SERVER[«CONTENT_TYPE»] and echo get_headers(‘url’, 1)[«Content-Type»] but neither of those work for me.

echo '
'; print_r(getallheaders()); 
$allHeaders = getallheaders(); $contentType = $allHeaders['Content-Type']; 

Check whether a request is GET or POST [duplicate], Better use $_SERVER['REQUEST_METHOD'] : if ($_SERVER['REQUEST_METHOD'] === 'POST') < // … >According to NetBeans IDE, it's not good to access $_SERVER

How to Get Data from a Request | PHP get and post form methods

This PHP tutorial will show you how to get data from a request. We will look at examples of Duration: 19:22

Easiest way to check if multiple POST parameters are set?

Hi so I want to know the easiest way to check if multiple POST parameters are set. Instead of doing a long if check with multiple "isset($_POST ['example'])" linked together by "&&", I wanted to know if there was a cleaner way of doing it.

What I ended up doing was making an array and looping over it:

 $params_needed = ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]; 

I would then call the function below, passing in $params_needed to check if the parameter names above are set:

 function all_params_valid($params_needed) < foreach ($params_needed as $param) < if (!isset($_POST[$param])) < error("Missing the " . $param . " variable in POST request."); return false; >> return true; > if (all_params_valid($params_needed))

However when I do this, it gets stuck on the first index and says "Missing the song_name variable. " despite actually including it in the post request , and I'm not sure why this is happening. The expected behavior would be for it to move on and tell me the next parameter "artist_name" is not set, but this doesn't happen.

I personally like using array_diff for this issue.

What you care about is your expected input is the same as the given input .

So you can use array_diff like this:

 $params_needed = ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]; $given_params = array_keys($_POST); $missing_params = array_diff($params_needed, $given_params); if(!empty($missing_params)) < // uh oh, someone didn't complete the form completely. >

How I approach this is by using array_map () so I can return all the values in the array whilst checking if it isset()

$args = array_map(function($key) < return isset($_POST[$key]) ? array($key =>$_POST[$key]) : someErrorMethod($key); >, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]); 
$args = array_map(function($key) < return array($key =>$_POST[$key] ?? someErrorMethod($key)); >, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]); 

Your error method could look something like this:

function someErrorMethod($key)

Inside of your $args variable, you will have an array of key => value. For example,

How to detect if $_POST is set?, to check if your script was POSTed. If additional data was passed, $_POST will not be empty, otherwise it will. You can use empty method to check if it contains

Cannot read body of post request with php

I'm trying to use an online service that requires to read the body of post requests at a callback url (webhook).

However I'm not familiar with http requests and unable to read the received data .

I'm using file_get_contents('php://input ') to retrieve the body and store the result in a text file :

file_put_contents("log/test.txt", file_get_contents('php://input')); 

image

I received data look like this in notepad++ (weird characters) :

Any idea on what's happening here ?

You are posting binary data.
You are posting an image/wavfile/document.
You can convert it back to what it was and save it to a directory.

$target_dir = "files/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); // file = your input name $target_file = preg_replace('/\s+/', '_', $target_file); $uploadOk = 1; $FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if file already exists if (file_exists($target_file)) < $uploadOk = 0; >// Check file size if ($_FILES["file"]["size"] > 5000000) < $uploadOk = 0; >// Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) < echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file >else < if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) < echo "Your file ". preg_replace('/\s+/', '_', basename( $_FILES["file"]["name"])). " is uploaded."; >else < echo "Sorry, an error occured"; >> 

It appears that data were gzipped .

So the simple solution is to use GZDECODE :

file_put_contents("log/test.txt", gzdecode(file_get_contents('php://input'))); 

Cannot read body of post request with php, You are posting binary data. You are posting an image/wavfile/document. You can convert it back to what it was and save it to a directory.

How to validate a post request without a specific attribute to validate

I have a time tracking application where every time that a new Time Entry is about to be added, I must first verify that all the previous time entries have been closed (meaning that an ending date has been set) and throw and error message using the validate() method.

I don't know how feasable this is or how to do it, reading the documentation it seems that most custome rules require that an attribute be given, but in this case it's more about validating the logical requirements rather than the form of the post request.

When I receive a post request I fetch all previous time entries which come before the post request starting time and have not yet been given an ending time.

Ideally, if I get any time entries returned I would throw an error saying 'You need to close the previous time entry before opening a new one'.

For more clarity, here is what I want to do in code :

$timeEntry= new TimeEntry; $openTimeEntries = $timeEntry->Where('start_time', 'startTime)->Where('end_time', 0)->get(); $count = $openTimeEntries->count(); $request->validate([ 'comment' => 'string', 'candidateId' => 'required', 'startTime' => 'required|date', 'endTime' => 'date|nullable|after:startTime', 'CustomeTimeEntryRule' => $openTimeEntries->count() > 0, // If false I want this rule to add the message to the validate error array ]); 

You are on the right track.

However, If you really customize validation you should create a request for here you can read more about it.

Simply call php artisan make:request TimeEntryStoreRequest

public function rules() < return [ 'CustomeTimeEntryRule' =>$openTimeEntries->count() > 0, ]; > /** * @return array|string[] */ public function messages(): array < return [ 'CustomeTimeEntryRule.*' =>'Custom message', ]; > 

However, if it is not a form input from a user I think you should check it inside your controller not in the form.

Also you can simplify your code like this:

use App\Models\TimeEntry; $openTimeEntriesCount = TimeEntry::select('id')->where('start_time', 'startTime)->where('end_time', 0)->count(); 

A simple way to do this is to merge the custom attribute to the request :

$timeEntry= new TimeEntry; $openTimeEntries = $timeEntry->Where('start_time', 'startTime)->Where('end_time', 0)->get(); $count = $openTimeEntries->count(); $request->merge([ 'CustomeTimeEntryRule' => $count, ]); 

Then we can validate the attribute using the in rule, which will return a custom validation message which we can specify as a second argument, when the count is not equal to 0:

$request->validate([ 'comment' => 'string', 'candidateId' => 'required', 'startTime' => 'required|date', 'endTime' => 'date|nullable|after:startTime', 'CustomeTimeEntryRule' => 'in:0', ], [ 'CustomeTimeEntryRule.in' => 'You need to close the previous time entry before opening a new one' ]); 

How to check for incomplete POST request in PHP, I guess that the remote client is actually a browser with HTML page. otherwise, let me know and i'll try to adapt my solution.

Источник

Оцените статью