php curl application x www form urlencoded
Загрузка файла на сервер без использования формы
Со временем возникла необходимость через формы отсылать еще и файлы. Тогда консорциум W3C взялся за доработку формата POST запроса. К тому времени уже достаточно широко применялся формат MIME (Multipurpose Internet Mail Extensions — многоцелевые расширения протокола для формирования Mail сообщений), поэтому, чтобы не изобретать велосипед заново, решили использовать часть данного формата формирования сообщений для создания POST запросов в протоколе HTTP.
Главное отличие multipart/form-data от application/x-www-form-urlencoded в том, что тело запроса теперь можно поделить на разделы, которые разделяются границами. Каждый раздел может иметь свой собственный заголовок для описания данных, которые в нем хранятся, т.е. в одном запросе можно передавать данные различных типов (как в теле письма можно одновременно с текстом передавать файлы). Пример запроса:
Boundary (граница) — это последовательность байтов, которая не должна встречаться внутри передаваемых данных. Content-Length — суммарный объём, включая дочерние заголовки. Само содержимое полей при этом оставляется «как есть».
CURL, multipart/form-data
Файл get.php на сервере http://server.com:
Важный момент: на форуме PHPCLUB.RU встретил упоминание, что может потребоваться указание полного пути файла — иначе CURL выдает ошибку.
CURL, application/x-www-form-urlencoded
Файл get.php на сервере http://server.com:
Сокеты, multipart/form-data
Файл get.php на сервере http://server.com:
Сокеты, application/x-www-form-urlencoded
Файл get.php на сервере http://server.com:
Метод PUT
Описанные выше способы работают для относительно небольших файлов (примерно до 2-х мегабайт, для получения более точного значения необходимо смотреть в настройках PHP максимальный объем принимаемых данных методом POST). Чтобы обойти это ограничение, будем передавать файл методом PUT:
POST using cURL and x-www-form-urlencoded in PHP returning Access Denied
I’ve noticed as well that when I use Advanced Rest Client Extension for chrome and if I set the Content-Type to application/json I have to enter a login and a password that I don’t know what are those because even if I enter the id and secret key that I have in the code it returns 401 Unauthorized. So I’m guessing this code that I wrote is not forcing it to the content-type: application/x-www-form-urlencoded, but I’m not sure. Thank you for any help on this issue!
1 Answer 1
Can you try like that and see if it helps:
I guess the site expect simple authentication on top of the secret_key that you already provided.
Also it is possible to send a Cookie, so just in case it is good idea to store it and use it again in the next Curl calls.
Not the answer you’re looking for? Browse other questions tagged php post curl or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How can I send a raw JSON using PHP curl with the content type «application/x-www-form-urlencoded»?
Let me explain:
I’m communicating with a webserver that accepts HTTP POST requests with a JSON object as the body of the request where normally we are used to seeing HTTP query parameters.
In my situation, I need to send a request with the following content-type
The body must be raw JSON.
So, there are many possibilities. I tried the following:
I also tried to escape the json_encode() :
If the server was able to parse html parameters I could just do this:
However, that is not the case and I need a workaround.
2 Answers 2
Usually the application/x-www-form-urlencoded requires a key-value paired parameters for HTTP post. So it’s very hard to suggest anything to you without seeing a sample POST data format. As per the document, you must place the URLencoded data with a variable. For example your JSON should go like this.
You can try sending the data without any key parameter, and it should not work
I’m not entirely sure I understand your question, so I’m going to answer two different versions.
Send JSON data, but with an (inaccurate) application/x-www-form-urlencoded Content Type
I don’t know why you’d want to do this, but if you do, it should be fairly simple.
Bear in mind that you are, here, sending deliberately inaccurate data to the server. You’re sending JSON, but calling it urlencoded. You probably don’t want to do this; if, for some reason, you do need to do this, you’d probably be better off fixing whatever the real problem is, rather than using this hacky workaround.
Send urlencoded JSON data
This is an odd setup, but accurate. At least you wouldn’t be lying in your HTTP headers.
Basically the same as above, but add this:
What you probably really should do: send JSON as JSON.
Php curl application x www form urlencoded
PHP поддерживает libcurl, библиотеку, созданную Daniel»ом Stenberg»ом, которая даёт возможность соединяться с серверами различных типов и по разным протоколам.
libcurl в настоящее время поддерживает протоколы http, https, ftp, gopher, telnet, dict, file и ldap.
libcurl также поддерживает сертификаты HTTPS, HTTP POST, HTTP PUT, загрузку по FTP (это можно сделать также РНР-расширением ftp), загрузку на основе форм HTTP, прокси, куки и аутентификацию user+password.
Эти функции были введены в PHP 4.0.2.
curl_init
Описание
resource curl_init([string url])
Функция curl_init() инициализирует новую сессию и возвратит CURL-дескриптор для использования в функциях curl_setopt(), curl_exec() и curl_close(). Если необязательный параметр url предоставлен, то опция CURLOPT_URL получит значение этого параметра. Вы можете вручную устанавливать его с помощью функции curl_setopt().
curl_setopt
Описание
bool curl_setopt (resource ch, string option, mixed value)
Функция curl_setopt() устанавливает опции для CURL-сессии, идентифицируемой параметром ch. Параметр option является опцией, которую вы хотите установить, а value это значение опции option.
Параметр value должен быть long для следующих опций (специфицированных параметром option):
Параметр value должен быть строкой для следующих значений параметра option:
Следующие опции ожидают дескриптора файла, который получается с помощью функции fopen():
Параметр value должен быть функцией следующего вида long write_callback (resource ch, string data) для следующих значений параметра option:
Параметр value должен быть функцией следующего вида string read_callback (resource ch, resource fd, long length)<> для следующих значений параметра option:
urlencode
(PHP 4, PHP 5, PHP 7, PHP 8)
urlencode — URL-кодирование строки
Описание
Эта функция удобна, когда закодированная строка будет использоваться в запросе, как часть URL, в качестве удобного способа передачи переменных на следующую страницу.
Список параметров
Строка, которая должна быть закодирована.
Возвращаемые значения
Примеры
Пример #1 Пример использования urlencode()
Пример #2 Пример использования urlencode() и htmlentities()
Примечания
Будьте внимательны с переменными, которые могут совпадать с элементами HTML. Такие сущности как &, © и £ разбираются браузером и используется как реальная сущность, а не желаемое имя переменной. Это очевидный конфликт, на который W3C указывает в течение многих лет. Смотрите подробности: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2
Смотрите также
User Contributed Notes 25 notes
urlencode function and rawurlencode are mostly based on RFC 1738.
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
Here is a function to encode URLs according to RFC 3986.
I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!
Don’t use urlencode() or urldecode() if the text includes an email address, as it destroys the «+» character, a perfectly valid email address character.
Unless you’re certain that you won’t be encoding email addresses AND you need the readability provided by the non-standard «+» usage, instead always use use rawurlencode() or rawurldecode().
I needed a function in PHP to do the same job as the complete escape function in Javascript. It took me some time not to find it. But findaly I decided to write my own code. So just to save time:
urlencode is useful when using certain URL shortener services.
The returned URL from the shortener may be truncated if not encoded. Ensure the URL is encoded before passing it to a shortener.
(tilde), while urlencode does.
Below is our jsonform source code in mongo db which consists a lot of double quotes. we are able to pass this source code to the ajax form submit function by using php urlencode :
If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as.
. pass the url value through the PHP urlencode() function twice, like this.
However, some weird things happen when dealing with characters like (these are HTML entities): ‼ ▐ ┐and Θ have weird things going on.
If you try to pass one in Internet Explorer, IE will *disable* the submit button. Firefox, however, does something weirder: it will convert it to it’s HTML entity. It will display properly, but only when you don’t convert entities.
The point? Be careful with decorative characters.
This very simple function makes an valid parameters part of an URL, to me it looks like several of the other versions here are decoding wrongly as they do not convert & seperating the variables into &.
$vars=array(‘name’ => ‘tore’,’action’ => ‘sell&buy’);
echo MakeRequestUrl($vars);
Will output: action=sell%26buy&name=tore
Constructing hyperlinks safely HOW-TO:
= ‘machine/generated/part’ ;
$url_parameter1 = ‘this is a string’ ;
$url_parameter2 = ‘special/weird «$characters»‘ ;
$link_label = «Click here & you’ll be » ;
Shortly:
— Use urlencode for all GET parameters (things that come after each «=»).
— Use rawurlencode for parts that come before «?».
— Use htmlspecialchars for HTML tag parameters and HTML text content.
look on index.php
array (size=0)
empty
test-bla-bla-4%253E2-y-3%253C6
look on test-bla-bla-4%253E2-y-3%253C6
array (size=1)
‘token’ => string ‘bla-bla-4>2-y-3
Simple static class for array URL encoding
/**
*
* URL Encoding class
* Use : urlencode_array::go() as function
*
*/
class urlencode_array
<