Php post form data with curl

How can I use cURL to post form data in php?

I need to run this command via php, but I’m having trouble, presumably with the form file data. I tried the following, however echoing or var_dumping the result seems to show nothing, just a blank page or a blank string.

'@'.$file_name_with_full_path); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$target_url); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_VERBOSE,true); $result=curl_exec ($ch); curl_close ($ch); var_dump($result);?> 

7 Answers 7

since no answer got it right thus far (at least not with an approach that would work in php 5.6+), here goes: the equivalent php curl_ code would be:

$ch = curl_init ( 'https://apiprovider.com/api/v0/imports?token=[KEY]' ); curl_setopt_array ( $ch, array ( CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array ( 'file' => new CURLFile ( '/home/USERNAME/import.csv' ) ) ) ); curl_exec ( $ch ); 

(i would also recommend setting CURLOPT_ENCODING to emptystring, especially if you expect the response to be compressible, that would be the equivalent of adding —compressed to the curl command line, and might speed things up)

'@'.$file_name_with_full_path); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$target_url); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_VERBOSE,true); $result = curl_exec ($ch); $curlresponse = json_decode($result, true); var_dump($curlresponse); ?> 

One way is to use CURLFile instead of @ for PHP version above 5.5

$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]' $file_name_with_full_path ='/home/USERNAME/import.csv'; // Create a CURLFile object $cfile = new CURLFile($file_name_with_full_path,mime_content_type($file_name_with_full_path),'imported_csv'); // Assign POST data $post = array('imported_csv_file' => $cfile); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$target_url); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_VERBOSE,true); $result=curl_exec ($ch); curl_close ($ch); var_dump($result); 

Maybe something like this could work:

'@'.$file_name_with_full_path); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL,$target_url); curl_setopt($curl, CURLOPT_POST,1); curl_setopt($curl, CURLOPT_POST, count($post) curl_setopt($curl, CURLOPT_POSTFIELDS, $post); curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); curl_setopt($curl, CURLOPT_VERBOSE,true); $result = curl_exec($curl) if(!$result) < die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl)); >curl_close($curl); var_dump($result); ?> 
$curl = new Curl(); $curl->post('https://www.example.com/login/', array( 'username' => 'myusername', 'password' => 'mypassword', )); 

that definitely will not upload $file_name_with_full_path — but maybe this would (idk, i dont know that library): $curl->post(‘https://www.example.com/login/’, array( ‘username’ => ‘myusername’, ‘password’ => ‘mypassword’, ‘file’=>new CURLFile($file_name_with_full_path) ));

Читайте также:  Тэг meta по html

Hi, This library is one of best curl lib for php. Please add library with instruction in this url [link]github.com/php-curl-class/php-curl-class/blob/master/README.md[/… this. and then You can use some examle of this like file uploader. file uploader example: [link]github.com/php-curl-class/php-curl-class/blob/master/examples/…

I don’t know that library, and although I might check it out, I have little interest in learning it. But the point is, your example code does NOT do what OP wants to do, you should probably fix that (also I’m the author of another curl_ wrapper that does pretty much the same, and it’s working fine for me, thus my disinterest)

You need to read file data and then attach data on post fields.

Try this, this should work. If doesn’t work, make sure fread() can read your file. Reading can be failed due to many reason.

$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]' $file_name_with_full_path ='/home/USERNAME/import.csv'; $fileHandler = fopen($file_name_with_full_path, 'r'); $fileData = fread($fileHandler, filesize($file_name_with_full_path)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, target_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); $headers = array('file'=>'@'.$file_name_with_full_path); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_INFILE, $fileHandler); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_name_with_full_path)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fileData); $result = curl_exec($ch); curl_close ($ch); var_dump($result); 

Источник

Using PHP Curl to submit form and get results [duplicate]

Once you fill out a value in name=»userName» and click name=»userBtn» the page refreshes and changes the value of name=»userName» to the information that I want. How would I go about submitting a form and then retrieving the data that it writes?

1 Answer 1

See this detailed example, Begin by creating a new connection.

$curl_connection = curl_init('http://www.domainname.com/target_url.php'); 

A new connection is created using curl_init() function, which takes the target URL as parameter (The URL where we want to post our data). The target URL is same as the “action” parameters of a normal form, which would look like this:

Now let’s set some options for our connection. We can do this using the curl_setopt() function. Go to curl_setopt() reference page for more information on curl_setopt() and a complete list of options.

curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); 

What options do we set here?

Читайте также:  Сумма арифметической прогрессии питон

First, we set the connection timeout to 30 seconds, so we don’t have our script waiting indefinitely if the remote server fails to respond.

Then we set how cURL will identify itself to the remote server. Some servers will return different content for different browsers (or agents, such as spiders of the search engines), so we want our request to look like it is coming from a popular browser.

CURLOPT_RETURNTRANSFER set to true forces cURL not to display the output of the request, but return it as a string.

Then we set CURLOPT_SSL_VERIFYPEER option to false, so the request will not trigger an error in case of an invalid, expired or not signed SSL certificate.

Finally, we set CURLOPT_FOLLOWLOCATION to 1 to instruct cURL to follow “Location: ” redirects found in the headers sent by the remote site.

Now we must prepare the data that we want to post. We can first store this in an array, with the key of an element being the same as the input name of a regular form, and the value being the value that we want to post for that field.

For example,if in a regular form we would have:

we add this to our array like this:

$post_data['firstName'] = 'Name'; $post_data['action'] = 'Register' 

Do the same for every form field.

Data will be posted in the following format: key1=value1&key2=value2

In order to format the data like this, we are going to create strings for each key-value pair (for example key1=value1), put them in another array ($post_items) then combine them in one string using PHP function implode() .

 foreach ( $post_data as $key => $value) < $post_items[] = $key . '=' . $value; >$post_string = implode ('&', $post_items); 

Next, we need to tell cURL which string we want to post. For this, we use the CURLOPT_POSTFIELDS option.

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); Finally, we execute the post, then close the connection.

$result = curl_exec($curl_connection); curl_close($curl_connection); 

By now, the data should have been posted to the remote URL. Go check this, and if it did not work properly, use curl_getinfo() function to see any errors that might have occurred.

print_r(curl_getinfo($curl_connection)); 

This line displays an array of information regarding the transfer. This must be used before closing the connection with curl_close();

Читайте также:  Custom scrollbar css online

You can also see number and description of the error by outputting curl_errno($curl_connection) and curl_error($curl_connection).

So let’s put everything together. Here is our code:

 $value) < $post_items[] = $key . '=' . $value; >//create the final string to be posted using implode() $post_string = implode ('&', $post_items); //create cURL connection $curl_connection = curl_init('http://www.domainname.com/target_url.php'); //set options curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); //set data to be posted curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); //perform our request $result = curl_exec($curl_connection); //show information regarding the request print_r(curl_getinfo($curl_connection)); echo curl_errno($curl_connection) . '-' . curl_error($curl_connection); //close the connection curl_close($curl_connection); ?> 

Источник

What is the right way to POST multipart/form-data using curl?

The file is around 500K in size. First of all, I see content length to be 254 on the transmit side. Later the server response’s content length is 0. Where am I going wrong? Here is the complete trace of the command.

* Couldn't find host xxx.xxx.xxx.xxx in the _netrc file; using defaults * About to connect() to xxx.xxx.xxx.xxx port yyyy (#0) * Trying xxx.xxx.xxx.xxx. * Adding handle: conn: 0x4b96a0 * Adding handle: send: 0 * Adding handle: recv: 0 * Curl_addHandleToPipeline: length: 1 * - Conn 0 (0x4b96a0) send_pipe: 1, recv_pipe: 0 * Connected to xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx) port yyyy (#0) * POST /zzzzzz/UploadFile HTTP/1.1 * User-Agent: curl/7.32.0 * Host: xxx.xxx.xxx.xxx:yyyy * Accept: */* * Content-Length: 254 * Expect: 100-continue * Content-Type: multipart/form-data; boundary=------------------------948a6137eef50079 * * HTTP/1.1 100 Continue * HTTP/1.1 100 Continue * HTTP/1.1 200 OK * HTTP/1.1 200 OK * Server Apache-Coyote/1.1 is not blacklisted * Server: Apache-Coyote/1.1 * Server: Apache-Coyote/1.1 * Added cookie JSESSIONID="C1D7DD042E250211D9DEA82688876F88" for domain xxx.xxx.xxx.xxx, path /zzzzz/, expire 0 * Set-Cookie: JSESSIONID=C1D7DD042E250211D9DEA82688876F88; Path=/zzzzzz/; * HttpOnly * Set-Cookie: JSESSIONID=C1D7DD042E250211D9DEA82688876F88; Path=/zzzzzz/; HttpOnly * Content-Type: text/html;charset=ISO-8859-1 Content-Type: text/html;charset=ISO-8859-1 * Content-Length: 0 * Content-Length: 0 * Date: Tue, 01 Oct 2013 11:54:24 GMT * Date: Tue, 01 Oct 2013 11:54:24 GMT * Connection #0 to host xxx.xxx.xxx.xxx left intact 

Источник

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