FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home  »  PHP  »  Sending POST form data with php CURL

by 27 comments

This brief guide explains 2 different reasons for wanting to send POST data with curl and how to do it. It is very handy to have the abililty to arbitrarily send POST data from a form to a script.

Sending POST data and placing the response into a variable

Many of my website clients want me to integrate their email newsletter program CoCoTalk throughout their sites.

CoCoTalk provides iframe code to stick on clients sites that automatically produces a form to sign up to the newsletter. But I use XHTML strict on my sites, so no iframes allowed.

The CoCoTalk iframe code and resulting HTML

<iframe src="http://www.cocotalk.com/cocotalk/subscribeForm_I.cfm" name="top" width="400" marginwidth="0" height="50"></iframe>
<form action="http://www.cocotalk.com/cocotalk/subscribeResponse_I.cfm" method="post" id="subscribeForm">
 <input type="hidden" name="listID" value="29" /><input type="hidden" name="request" value="suba" />
 Email:<input type="text" name="EmailAddress" class="bodyText" size="30" maxlength="100" />
  <input type="submit" name="SubscribeSubmit" value="Subscribe" class="bodyText" />
</form>

XHTML strict replacement CoCoTalk code

<form id="cocoTalkForm" class="FcocoW" action="http://www.askapache.com/cgi-bin/cocotalk.php" method="post">
  <label for="EmailAddress">Email:<input name="EmailAddress" id="EmailAddress" size="15" type="text" /></label>
  <label><input type="image" name="SubscribeSubmit" id="SubscribeSubmit" src="btn.png" value="Subscribe" /></label>
</form>

cocotalk.php

This code gets the correct EmailAddress from the POST data and then creates a 2nd POST request to the CoCoTalk url. It mimics the settings and vars of the original CoCoTalk form.

<?php
 define('POSTURL', 'http://www.cocotalk.com/cocotalk/Subscribe.cfm');
 define('POSTVARS', 'listID=29&request=suba&SubscribeSubmit=Subscribe&EmailAddress=');  // POST VARIABLES TO BE SENT
 
 // INITIALIZE ALL VARS
 $Email='';
 $ch='';
 $Rec_Data='';
 $Temp_Output='';
 
 if($_SERVER['REQUEST_METHOD']==='POST') {  // REQUIRE POST OR DIE
 if(isset($_POST['EmailAddress'])) $Email=$_POST['EmailAddress'];  // GET EMAIL INTO VAR
 
 $ch = curl_init(POSTURL);
 curl_setopt($ch, CURLOPT_POST      ,1);
 curl_setopt($ch, CURLOPT_POSTFIELDS    ,POSTVARS.$Email);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION  ,1);
 curl_setopt($ch, CURLOPT_HEADER      ,0);  // DO NOT RETURN HTTP HEADERS
 curl_setopt($ch, CURLOPT_RETURNTRANSFER  ,1);  // RETURN THE CONTENTS OF THE CALL
 $Rec_Data = curl_exec($ch);
 
 ob_start();
 header("Content-Type: text/html");
 $Temp_Output = ltrim(rtrim(trim(strip_tags(trim(preg_replace ( "/ss+/" , " " , html_entity_decode($Rec_Data)))),"ntrhv ")), "%20");
 $Temp_Output = ereg_replace (' +', ' ', trim($Temp_Output));
 $Temp_Output = ereg_replace("[rtn]","",$Temp_Output);
 $Temp_Output = substr($Temp_Output,307,200);
 echo $Temp_Output;
 $Final_Out=ob_get_clean();
 echo $Final_Out;
 curl_close($ch);
} else die('Hacking attempt Logged!');
 
exit;
?>

Relaying POST data, allowing the script to redirect

You could add a hidden input variable to your forms and then based on that variable you can redirect the POST vars to a certain script.

Code for send-email.php

This simply acts as a POST relay or proxy that you can use to send off your POST results to multiple scripts.

<?php
 if(isset($_POST['Name']))     $Name   = $_POST['Name'];
 if(isset($_POST['Email']))   $Email   = $_POST['Email'];
 if(isset($_POST['Message']))   $Message= htmlentities($_POST['Message']);
 
 $Curl_Session = curl_init('http://www.site.com/cgi-bin/waiting.php');
 curl_setopt ($Curl_Session, CURLOPT_POST, 1);
 curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "Name=$Name&Email=$Email&Message=$Message");
 curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
 curl_exec ($Curl_Session);
 curl_close ($Curl_Session);
 header("Location:http://www.site.com/cgi-bin/thanks.php");
?>

Code for waiting.php

This actually processes the post (the send_email function).

<?php
 if(isset($_POST['Name']))       $Name       = $_POST['Name']);
 if(isset($_POST['Email']))       $Email       = $_POST['Email'];
 if(isset($_POST['Message']))     $Message      = htmlentities($_POST['Message']);
 send_email($Name, $Email, $Message);
?>

Sending GET or POST variables invisibly

Create a file /dothis.php with contents

<?php
 $ch = curl_init('http://mysite.com/index.php');
 curl_setopt ($ch, CURLOPT_POST, 1);
 curl_setopt ($ch, CURLOPT_POSTFIELDS, "option=com_content&task=blogcategory&id=24&Itemid=55");
 curl_exec ($ch);
 curl_close ($ch);
?>

or to use GET instead of POST

<?php
 $ch = curl_init('http://www.mysite.com/index.php?option=com_content&task=blogcategory&id=24&Itemid=55');
 curl_exec ($ch);
 curl_close ($ch);
?>

Then in your .htaccess file do this:

RewriteEngine On
RewriteBase /
RewriteRule ^thispage$ /dothis.php[/code]

POST with a different Content-Type

You can always replace the internally generated headers with -H/--header. To make a simple HTTP POST with text/xml as content-type, do something like:

curl -d "datatopost" -H "Content-Type: text/xml"

CURL functions

curl_close - Close a cURL session
curl_copy_handle - Copy a cURL handle along with all of its preferences
curl_errno - Return the last error number
curl_error - Return a string containing the last error for the current session
curl_exec - Perform a cURL session
curl_getinfo - Get information regarding a specific transfer
curl_init - Initialize a cURL session
curl_multi_add_handle - Add a normal cURL handle to a cURL multi handle
curl_multi_close - Close a set of cURL handles
curl_multi_exec - Run the sub-connections of the current cURL handle
curl_multi_getcontent - Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read - Get information about the current transfers
curl_multi_init - Returns a new cURL multi handle
curl_multi_remove_handle - Remove a multi handle from a set of cURL handles
curl_multi_select - Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt_array - Set multiple options for a cURL transfer
curl_setopt - Set an option for a cURL transfer
curl_version - Gets cURL version information

curl_setopt

bool curl_setopt ( resource $ch, int $option, mixed $value )

Sets an option on the given cURL session handle.

Parameters

ch A cURL handle returned by curl_init().

option The CURLOPT_XXX option that you want to set

Value should be a bool for the following values of the option parameter:

CURLOPT_AUTOREFERER
TRUE to automatically set the Referer: field in requests where it follows a Location: redirect.
CURLOPT_BINARYTRANSFER
TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.
CURLOPT_COOKIESESSION
TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.
CURLOPT_CRLF
TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHE
TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERROR
TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIME
TRUE to attempt to retrieve the modification date of the remote document. You can then retrieve this value using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION
TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE
TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT
TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT
TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.
CURLOPT_FTP_USE_EPSV
TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.
CURLOPT_FTPAPPEND
TRUE to append to the remote file instead of overwriting it.
CURLOPT_FTPASCII
An alias of CURLOPT_TRANSFERTEXT. Use that instead.
CURLOPT_FTPLISTONLY
TRUE to only list the names of an FTP directory.
CURLOPT_HEADER
TRUE to include the header in the output.
CURLOPT_HTTPGET
TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNEL
TRUE to tunnel through a given HTTP proxy.
CURLOPT_MUTE
TRUE to be completely silent with regards to the cURL functions.
CURLOPT_NETRC
TRUE to scan your ~/.netrc file to find your username and password for the remote site that you're establishing a connection with.
CURLOPT_NOBODY
TRUE to exclude the body from the output.
CURLOPT_NOPROGRESS
TRUE to disable the progress meter for cURL transfers.
CURLOPT_NOSIGNAL
TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used.
CURLOPT_POST
TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_PUT
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
CURLOPT_SSL_VERIFYPEER
FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.
CURLOPT_SSL_VERIFYHOST
may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2).
TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.
CURLOPT_TRANSFERTEXT
TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.
CURLOPT_UNRESTRICTED_AUTH
TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed.
CURLOPT_UPLOAD
TRUE to prepare for an upload.
CURLOPT_VERBOSE
TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

Value should be an integer for the following values of the option parameter:

CURLOPT_BUFFERSIZE
The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however.
CURLOPT_CLOSEPOLICY
Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT
The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.
CURLOPT_DNS_CACHE_TIMEOUT
The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
CURLOPT_FTPSSLAUTH
The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide).
CURLOPT_HTTP_VERSION
_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
CURLOPT_HTTPAUTH
The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.
CURLAUTH_ANY
is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.
CURLAUTH_ANYSAFE
s an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.
CURLOPT_INFILESIZE
The expected size, in bytes, of the file when uploading a file to a remote site.
CURLOPT_LOW_SPEED_LIMIT
The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.
CURLOPT_LOW_SPEED_TIME
The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.
CURLOPT_MAXCONNECTS
The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRS
The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT
An alternative port number to connect to.
CURLOPT_PROXYAUTH
The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported.
CURLOPT_PROXYPORT
The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY.
CURLOPT_PROXYTYPE
Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5.
CURLOPT_RESUME_FROM
The offset, in bytes, to resume a transfer from.
CURLOPT_SSL_VERIFYHOST
1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.
CURLOPT_SSLVERSION
The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases you must set this manually.
CURLOPT_TIMECONDITION
How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE . Use CURL_TIMECOND_ISUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default. Added in PHP 5.1.0.
CURLOPT_TIMEOUT
The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEVALUE
The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.

Value should be a string for the following values of the option parameter:

CURLOPT_CAINFO
The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATH
A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE
The contents of the "Set-Cookie: " header to be used in the HTTP request.
CURLOPT_COOKIEFILE
The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
CURLOPT_COOKIEJAR
The name of a file to save all internal cookies to when the connection closes.
CURLOPT_CUSTOMREQUEST
A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0rnrn" would be incorrect.
CURLOPT_EGBSOCKET
Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.
CURLOPT_ENCODING
The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent.
CURLOPT_FTPPORT
The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE
The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVEL
The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation.
CURLOPT_PROXY
The HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWD
A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE
A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE
Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER
The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LIST
A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT
The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD
The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE
The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG".
CURLOPT_SSLENGINE
The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT
The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY
The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD
The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLKEYTYPE
The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_URL
The URL to fetch. You can also set this when initializing a session with curl_init().
CURLOPT_USERAGENT
The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWD
A username and password formatted as "[username]:[password]" to use for the connection.

Value should be an array for the following values of the option parameter:

CURLOPT_HTTP200ALIASES
An array of HTTP 200 responses that will be treated as valid responses and not as errors.
CURLOPT_HTTPHEADER
An array of HTTP header fields to set.
CURLOPT_POSTQUOTE
An array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_QUOTE
An array of FTP commands to execute on the server prior to the FTP request.

Value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

CURLOPT_FILE
The file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILE
The file that the transfer should be read from when uploading.
CURLOPT_STDERR
An alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADER
The file that the header part of the transfer is written to.

Value should be a string that is the name of a valid callback function for the following values of the option parameter:

CURLOPT_HEADERFUNCTION
The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. Using this callback function, it becomes your responsibility to write the header data. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION
The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_READFUNCTION
The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. Using this callback function, it becomes your responsibility to read the data. Return the number of bytes read. Return 0 to signal EOF.
CURLOPT_WRITEFUNCTION
The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. Using this callback function, it becomes your responsibility to write the data. Must return the exact number of bytes written or this will fail.

Predefined CURL Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

  • CURLOPT_AUTOREFERER
  • CURLOPT_COOKIESESSION
  • CURLOPT_DNS_USE_GLOBAL_CACHE
  • CURLOPT_DNS_CACHE_TIMEOUT
  • CURLOPT_FTP_SSL
  • CURLFTPSSL_TRY
  • CURLFTPSSL_ALL
  • CURLFTPSSL_CONTROL
  • CURLFTPSSL_NONE
  • CURLOPT_FTPSSLAUTH
  • CURLOPT_PORT
  • CURLOPT_FILE
  • CURLOPT_INFILE
  • CURLOPT_INFILESIZE
  • CURLOPT_URL
  • CURLOPT_PROXY
  • CURLOPT_VERBOSE
  • CURLOPT_HEADER
  • CURLOPT_HTTPHEADER
  • CURLOPT_NOPROGRESS
  • CURLOPT_NOBODY
  • CURLOPT_FAILONERROR
  • CURLOPT_UPLOAD
  • CURLOPT_POST
  • CURLOPT_FTPLISTONLY
  • CURLOPT_FTPAPPEND
  • CURLOPT_NETRC
  • CURLOPT_FOLLOWLOCATION
  • CURLOPT_FTPASCII
  • CURLOPT_PUT
  • CURLOPT_MUTE
  • CURLOPT_USERPWD
  • CURLOPT_PROXYUSERPWD
  • CURLOPT_RANGE
  • CURLOPT_TIMEOUT
  • CURLOPT_POSTFIELDS
  • CURLOPT_REFERER
  • CURLOPT_USERAGENT
  • CURLOPT_FTPPORT
  • CURLOPT_FTP_USE_EPSV
  • CURLOPT_LOW_SPEED_LIMIT
  • CURLOPT_LOW_SPEED_TIME
  • CURLOPT_RESUME_FROM
  • CURLOPT_COOKIE
  • CURLOPT_SSLCERT
  • CURLOPT_SSLCERTPASSWD
  • CURLOPT_WRITEHEADER
  • CURLOPT_SSL_VERIFYHOST
  • CURLOPT_COOKIEFILE
  • CURLOPT_SSLVERSION
  • CURLOPT_TIMECONDITION
  • CURLOPT_TIMEVALUE
  • CURLOPT_CUSTOMREQUEST
  • CURLOPT_STDERR
  • CURLOPT_TRANSFERTEXT
  • CURLOPT_RETURNTRANSFER
  • CURLOPT_QUOTE
  • CURLOPT_POSTQUOTE
  • CURLOPT_INTERFACE
  • CURLOPT_KRB4LEVEL
  • CURLOPT_HTTPPROXYTUNNEL
  • CURLOPT_FILETIME
  • CURLOPT_WRITEFUNCTION
  • CURLOPT_READFUNCTION
  • CURLOPT_PASSWDFUNCTION
  • CURLOPT_HEADERFUNCTION
  • CURLOPT_MAXREDIRS
  • CURLOPT_MAXCONNECTS
  • CURLOPT_CLOSEPOLICY
  • CURLOPT_FRESH_CONNECT
  • CURLOPT_FORBID_REUSE
  • CURLOPT_RANDOM_FILE
  • CURLOPT_EGDSOCKET
  • CURLOPT_CONNECTTIMEOUT
  • CURLOPT_SSL_VERIFYPEER
  • CURLOPT_CAINFO
  • CURLOPT_CAPATH
  • CURLOPT_COOKIEJAR
  • CURLOPT_SSL_CIPHER_LIST
  • CURLOPT_BINARYTRANSFER
  • CURLOPT_NOSIGNAL
  • CURLOPT_PROXYTYPE
  • CURLOPT_BUFFERSIZE
  • CURLOPT_HTTPGET
  • CURLOPT_HTTP_VERSION
  • CURLOPT_SSLKEY
  • CURLOPT_SSLKEYTYPE
  • CURLOPT_SSLKEYPASSWD
  • CURLOPT_SSLENGINE
  • CURLOPT_SSLENGINE_DEFAULT
  • CURLOPT_SSLCERTTYPE
  • CURLOPT_CRLF
  • CURLOPT_ENCODING
  • CURLOPT_PROXYPORT
  • CURLOPT_UNRESTRICTED_AUTH
  • CURLOPT_FTP_USE_EPRT
  • CURLOPT_HTTP200ALIASES
  • CURLOPT_HTTPAUTH
  • CURLAUTH_BASIC
  • CURLAUTH_DIGEST
  • CURLAUTH_GSSNEGOTIATE
  • CURLAUTH_NTLM
  • CURLAUTH_ANY
  • CURLAUTH_ANYSAFE
  • CURLOPT_PROXYAUTH
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_SLOWEST
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_OLDEST
  • CURLINFO_EFFECTIVE_URL
  • CURLINFO_HTTP_CODE
  • CURLINFO_HEADER_OUT
  • CURLINFO_HEADER_SIZE
  • CURLINFO_REQUEST_SIZE
  • CURLINFO_TOTAL_TIME
  • CURLINFO_NAMELOOKUP_TIME
  • CURLINFO_CONNECT_TIME
  • CURLINFO_PRETRANSFER_TIME
  • CURLINFO_SIZE_UPLOAD
  • CURLINFO_SIZE_DOWNLOAD
  • CURLINFO_SPEED_DOWNLOAD
  • CURLINFO_SPEED_UPLOAD
  • CURLINFO_FILETIME
  • CURLINFO_SSL_VERIFYRESULT
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD
  • CURLINFO_CONTENT_LENGTH_UPLOAD
  • CURLINFO_STARTTRANSFER_TIME
  • CURLINFO_CONTENT_TYPE
  • CURLINFO_REDIRECT_TIME
  • CURLINFO_REDIRECT_COUNT
  • CURL_VERSION_IPV6
  • CURL_VERSION_KERBEROS4
  • CURL_VERSION_SSL
  • CURL_VERSION_LIBZ
  • CURLVERSION_NOW
  • CURLE_OK
  • CURLE_UNSUPPORTED_PROTOCOL
  • CURLE_FAILED_INIT
  • CURLE_URL_MALFORMAT
  • CURLE_URL_MALFORMAT_USER
  • CURLE_COULDNT_RESOLVE_PROXY
  • CURLE_COULDNT_RESOLVE_HOST
  • CURLE_COULDNT_CONNECT
  • CURLE_FTP_WEIRD_SERVER_REPLY
  • CURLE_FTP_ACCESS_DENIED
  • CURLE_FTP_USER_PASSWORD_INCORRECT
  • CURLE_FTP_WEIRD_PASS_REPLY
  • CURLE_FTP_WEIRD_USER_REPLY
  • CURLE_FTP_WEIRD_PASV_REPLY
  • CURLE_FTP_WEIRD_227_FORMAT
  • CURLE_FTP_CANT_GET_HOST
  • CURLE_FTP_CANT_RECONNECT
  • CURLE_FTP_COULDNT_SET_BINARY
  • CURLE_PARTIAL_FILE
  • CURLE_FTP_COULDNT_RETR_FILE
  • CURLE_FTP_WRITE_ERROR
  • CURLE_FTP_QUOTE_ERROR
  • CURLE_HTTP_NOT_FOUND
  • CURLE_WRITE_ERROR
  • CURLE_MALFORMAT_USER
  • CURLE_FTP_COULDNT_STOR_FILE
  • CURLE_READ_ERROR
  • CURLE_OUT_OF_MEMORY
  • CURLE_OPERATION_TIMEOUTED
  • CURLE_FTP_COULDNT_SET_ASCII
  • CURLE_FTP_PORT_FAILED
  • CURLE_FTP_COULDNT_USE_REST
  • CURLE_FTP_COULDNT_GET_SIZE
  • CURLE_HTTP_RANGE_ERROR
  • CURLE_HTTP_POST_ERROR
  • CURLE_SSL_CONNECT_ERROR
  • CURLE_FTP_BAD_DOWNLOAD_RESUME
  • CURLE_FILE_COULDNT_READ_FILE
  • CURLE_LDAP_CANNOT_BIND
  • CURLE_LDAP_SEARCH_FAILED
  • CURLE_LIBRARY_NOT_FOUND
  • CURLE_FUNCTION_NOT_FOUND
  • CURLE_ABORTED_BY_CALLBACK
  • CURLE_BAD_FUNCTION_ARGUMENT
  • CURLE_BAD_CALLING_ORDER
  • CURLE_HTTP_PORT_FAILED
  • CURLE_BAD_PASSWORD_ENTERED
  • CURLE_TOO_MANY_REDIRECTS
  • CURLE_UNKNOWN_TELNET_OPTION
  • CURLE_TELNET_OPTION_SYNTAX
  • CURLE_OBSOLETE
  • CURLE_SSL_PEER_CERTIFICATE
  • CURLE_GOT_NOTHING
  • CURLE_SSL_ENGINE_NOTFOUND
  • CURLE_SSL_ENGINE_SETFAILED
  • CURLE_SEND_ERROR
  • CURLE_RECV_ERROR
  • CURLE_SHARE_IN_USE
  • CURLE_SSL_CERTPROBLEM
  • CURLE_SSL_CIPHER
  • CURLE_SSL_CACERT
  • CURLE_BAD_CONTENT_ENCODING
  • CURLE_LDAP_INVALID_URL
  • CURLE_FILESIZE_EXCEEDED
  • CURLE_FTP_SSL_FAILED
  • CURLFTPAUTH_DEFAULT
  • CURLFTPAUTH_SSL
  • CURLFTPAUTH_TLS
  • CURLPROXY_HTTP
  • CURLPROXY_SOCKS5
  • CURL_NETRC_OPTIONAL
  • CURL_NETRC_IGNORED
  • CURL_NETRC_REQUIRED
  • CURL_HTTP_VERSION_NONE
  • CURL_HTTP_VERSION_1_0
  • CURL_HTTP_VERSION_1_1
  • CURLM_CALL_MULTI_PERFORM
  • CURLM_OK
  • CURLM_BAD_HANDLE
  • CURLM_BAD_EASY_HANDLE
  • CURLM_OUT_OF_MEMORY
  • CURLM_INTERNAL_ERROR
  • CURLMSG_DONE

Tags

February 21st, 2007

Comments Welcome

  • beanbud

    great tutorial !

  • Jon

    Nothing difficult about it! very straight forward. nice working tutorial!

  • http://www.jehlion.org john

    very nice =) that really helped me out.. thanks

  • joe

    okay i am confused. are you telling me that this script is able to successfully redirect me to another page while using POST to send the vars

  • http://www.askapache.com/ AskApache

    @ joe

    Not sure what you mean joe.. It can do alot of things and is quite flexible.

  • adriano

    well I was googling to find a solution to a simple problem
    i build pbx based on asterisk
    one of the more time consuption activity is configure each single ip phone
    i already have a script to add users,extensions e build main asterisk conf files
    now with your examples I hope to add a new function to complete congfigure the ip phone

    if nteressted I'll post back the result thanks for support to the open community
    ciao!

  • http://www.ipssolutions.com marty meyers

    Very nice example. It solved a double problem in that I needed to "jump" to two different pages(separate php programs) depending on input from the first page and I have to POST a large amount of data. One remaining issue is that the browser window address bar for page 1 is displayed when I jump to either of the other pages using the Curl method. Any suggestion on how to update the address bar from the new pages?
    TIA for you help
    Marty

  • penter wood

    im trying the same with list from autoscout24. the site loads, but no cars in it, i think the post parameters were not sent. still trying

  • Krishan Rodrigo

    Thank you very much. This is exactly what I have been looking for in a different problem. Curl post solved my problem.

  • http://www.thewebsitedesign.co.uk tiggsy

    This is great. The php manual says to use an array for the data in CURLOPT_POSTFIELDS, but that doesn't work. Your method does.

  • http://thetechcorner.net/ Travis Cunningham

    Your send-mail.php script has a PHP error.

    You might want to check in to this one - just giving you the heads up.

  • TheCasTex

    very nice =) that really helped me out.

  • Ankur Aggarwal

    I have sent mail through php mail function. Now i need to operate on that html data send through on mail window according to the response of the window.
    kindly help me

  • RS

    Wow, what a post. Amazing. Thank you!

  • Sark

    I was googling to find a solution to a simple problem
    i build pbx based y have a script data. One remaining issue is that the browser window address bar for page 1 is display problem in that I needed to “jump” to two different pages(separate php programs) depending on input from the first page and I have to POST a large amount of data. One remaining issue is that the browser window address bar for page 1 is displayed when I jump to either of the other pages using the Curl method. Any suggestion on how to update the address bar on asterisk.

  • sachin B

    Thanks, Nice Curl Example

  • http://www.digitdude.com/ inzar

    thanks.... love the php curl for POST

  • HighConcept

    This tutorial is great! But if you want to be a hero, answer a question that has been asked hundreds of time on the Internet, with nothing but bad, or uninformed answers that I can find after _hours_ of searching.

    I have a script siteA.domain.com/script.php.

    Using a _pure_ PHP solution (no javascript), I want to POST parameters from inside this script, not using a form, but using cURL or fsockopen, etc., to: siteB.otherdomain.com/targetscript.php

    and I want to END UP (in the browser) at the latter site, with the response from the post showing in the browser. With your examples, the POSTing with cURL is easy, and the response shows up in the browser, but one remains at the _original_ site (i.e., siteA.comain.com). Adding a "Location" header via the cURL optional header option does no good.

    In other words, I want the browser to _act_ like the user filled out a form and the script posted it to another URL, but I don't want the form at all; I want the script to synthesize the POST and end up at the destination page.

  • http://www.thedreamstone.com Bruno Dsstudio

    It lear me how to use cURL...just in time when i needed this, thanks a lot
    (note ...im Brazilian, and i think this tuto very simple even for me).

  • Jayour

    Excellent post. Helped me perfectly. Thnx for taking the time to Post to others!

  • nev

    I don't see how your "Relaying POST data, allowing the script to redirect" two-script example could ever work.

    OK, so the send-email.php script is supposed to send the POST variables to waiting.php. If that happened, you wouldn't end up in your browser at waiting.php. All that would happen is that waiting.php would supposedly receive and process the POST variables.

    So what's the point of the location redirect header in waiting.php? No-one is ever going to see it, so no-one is ever going to be redirected.

    By the way, I say "the send-email.php script is *supposed* to send the POST variables to waiting.php" - because I find it doesn't send them. The email isn't sent, even when it's written properly as mail().

    • http://www.askapache.com/ AskApache

      @ nev

      Good points! The reason no email is being sent is because send_email is not a builtin function, meaning I defined that function myself but didn't publish it.

      You are absolutely right about the redirect header! It should have been in the send-email.php script instead, I updated the post to reflect that.. But you are missing the major paradigm-shifting point of this technique, which is one of my all-time favorite hacks.

      The idea behind this is that instead of POSTING to a php script that gets your POST variables AND processes those variables right then (such as a sending mail function), instead you POST the variables to a php script that DOES NOT process the variables itself, instead it sends the POST variables to a 2nd php script which is the script that does the actual processing (such as sending mail).

      The reason that I say this is one of my favorite all-time hacks is because of 1 thing. The 1 thing is how the 1st script is the one posting to the 2nd script, meaning instead of having to wait for the processing to finish to receive the page response, you can receive the page response (in this case a thank you page redirect) INSTANTLY because the 1st script is the one who has to 'wait' for the 2nd script to finish, meanwhile the visitor who initiated the request is already at the thanks page while the 2nd script processes the request in the background.

      I think I will write a new more detailed article on this, but it's one of those things that I consider so highly valuable that I am tempted to tell people to GRTFM.. not you but you know what I mean.

      Anyway thanks for the feedback, I like the way you actually tested this stuff before you posted about it!!!!!!!!! Just like I do.

  • http://www.korochzan.ru/logs/access_log Koroch

    Great post. I used to be checking constantly this blog
    and I'm impressed! Very useful info particularly the ultimate phase :) I handle such information a lot. I was looking for this certain info for a long time. Thank you and best of luck.

  • Sunni Kumar Sharma

    I need help to parse the pagination pages in php on the link of next page has a javascript function calling javascript:__doPostBack('AMCSchemelist1$GV_schdet','Page$Next') how to parse the next page please help me...? This is my blog link here.... http://www.project-codes.com

    • vanapandi

      Have u fininshed this task if so send me details...i am also searching for that

  • Pingback: POST redirect using a cURL in PHP | Admob TapIt MobFox Android

  • Naredra Baldha

    This post is very very useful.....
    lot's of thanksss

Popular Articles
My Online Tools

Related Articles
Newest Posts
Twitter


  •  t.co/ShKrGdqXuJ 
  • RUN GCC! This is a typical shirt I wear, from the  t.co/46LYbFr4k2  shop. A clerk at the LQ recognized it!  t.co/jjmT0dkCPu 
  • Merlin the Magician  t.co/iMmRbanUi4 
  • ROGUE CODE - Latest novel from @markrussinovich  t.co/apkn0LoPIt 
  • RTFM - surprisingly very helpful and way more comprehensive than it looks! @redteamfieldman #pwnAllTheThings  t.co/xiaJ5g0aC9 
  • Dear Hacker - Letters to the Editor of 2600, from Emmanuel Goldstein  t.co/JCfLab7FAJ 
  • The Mythical Man-Month - Essays on Software Engineering, by Frederick P. Brooks, Jr.  t.co/ilWN5GHElr 
  • "where wizards stay up late" - The Origins of the Internet. Favorite book detailing the birth of the net and IMPs  t.co/gY9VTGJgZz 
  • ZERO DAY - read before Trojan horse  t.co/pPMLGDJv8P 
  • Trojan Horse, a novel!  t.co/Hf8EtYaZVa 
  • The Hacker Playbook - very nice high level overview of attacks  t.co/lHwNVWi61u 
  • Clean Code - A Handbook of Agile Software Craftsmanship  t.co/hnJX0x1qIc 
  • Secrets of the JavaScript Ninja - By my absolute favorite JS hacker John Resig!  t.co/tZ42ljmcCl 
  • Hacking Exposed 7: Network Security Secrets & SolutionsMy all time favorite, basic but thorough and accurate.  t.co/jycW0RDVtZ 

Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman






[hide]

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

| Google+ | askapache

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain