PHP + curl, HTTP POST sample code?
Can anyone show me how to do a php curl with an HTTP POST?
I want to send data like this:
username=user1, password=passuser1, gender=1
To www.domain.com
I expect the curl to return a response like result=OK
. Are there any examples?
php http curl http-post
add a comment |
Can anyone show me how to do a php curl with an HTTP POST?
I want to send data like this:
username=user1, password=passuser1, gender=1
To www.domain.com
I expect the curl to return a response like result=OK
. Are there any examples?
php http curl http-post
add a comment |
Can anyone show me how to do a php curl with an HTTP POST?
I want to send data like this:
username=user1, password=passuser1, gender=1
To www.domain.com
I expect the curl to return a response like result=OK
. Are there any examples?
php http curl http-post
Can anyone show me how to do a php curl with an HTTP POST?
I want to send data like this:
username=user1, password=passuser1, gender=1
To www.domain.com
I expect the curl to return a response like result=OK
. Are there any examples?
php http curl http-post
php http curl http-post
edited Dec 9 '16 at 20:57
Vladimir Kovpak
10.6k43646
10.6k43646
asked Jan 26 '10 at 9:39
mysqllearnermysqllearner
4,350123543
4,350123543
add a comment |
add a comment |
10 Answers
10
active
oldest
votes
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") ... else ...
?>
22
no need to usehttp_build_query()
to handle parameters; just pass the array toCURLOPT_POSTFIELDS
is enough.
– Raptor
Apr 5 '16 at 3:13
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
Also if value ofCURLOPT_POSTFIELDS
is an array, theContent-Type
header will be set tomultipart/form-data
instead ofapplication/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php
– Chloe
Jul 21 '16 at 2:34
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
|
show 2 more comments
Procedural
// set post fields
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
Object oriented
<?php
namespace MyAppHttp;
class Curl
/** @var resource cURL handle */
private $ch;
/** @var mixed The response */
private $response = false;
/**
* @param string $url
* @param array $options
*/
public function __construct($url, array $options = array())
$this->ch = curl_init($url);
foreach ($options as $key => $val)
curl_setopt($this->ch, $key, $val);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
/**
* Get the response
* @return string
* @throws RuntimeException On cURL error
*/
public function getResponse()
if ($this->response)
return $this->response;
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
if (is_resource($this->ch))
curl_close($this->ch);
if (0 !== $errno)
throw new RuntimeException($error, $errno);
return $this->response = $response;
/**
* Let echo out the response
* @return string
*/
public function __toString()
return $this->getResponse();
// usage
$curl = new MyAppHttpCurl('http://www.example.com', array(
CURLOPT_POSTFIELDS => array('username' => 'user1')
));
try
echo $curl;
catch (RuntimeException $ex)
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
Side note here: it would be best to create some kind of interface called AdapterInterface
for example with getResponse()
method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.
Using HTTPS / encrypting traffic
Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed
.
What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.
Never, ever do that. Instead, you simply need to modify your php.ini
and tell PHP where your CA Certificate
file is to let it verify certificates correctly:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:phpcacert.pem
The latest cacert.pem
can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini
related settings remember to restart your webserver.
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
|
show 2 more comments
A live example of using php curl_exec to do an HTTP post:
Put this in a file called foobar.php:
<?php
$ch = curl_init();
$skipper = "luxury assault recreational vehicle";
$fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
$postvars = '';
foreach($fields as $key=>$value)
$postvars .= $key . "=" . $value . "&";
$url = "http://www.google.com";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
Then run it with the command php foobar.php
, it dumps this kind of output to screen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
A mountain of content...
</body>
</html>
So you did a PHP POST to www.google.com and sent it some data.
Had the server been programmed to read in the post variables, it could decide to do something different based upon that.
$postvars .= $key . $value;
should$postvars .= $key . $value ."&";
or not?
– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the$fields
array and it'll output a query string.
– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
Oh no don't try to build the post string yourself! use this:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave outhttp_build_query
like:curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
add a comment |
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
add a comment |
Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:
function curlPost($url, $data=NULL, $headers = NULL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($data))
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (!empty($headers))
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch))
trigger_error('Curl Error:' . curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
add a comment |
If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.
If you want to stick with the stock lib, just try addingcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
add a comment |
Here are some boilerplate code for PHP + curl
http://www.webbotsspidersscreenscrapers.com/DSP_download.php
include in these library will simplify development
<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;
# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
...
?>
add a comment |
A simpler answer IF you are passing information to your own website is to use a SESSION variable. Begin php page with:
session_start();
If at some point there is information you want to generate in PHP and pass to the next page in the session, instead of using a POST variable, assign it to a SESSION variable. Example:
$_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.'
Then on the next page you simply reference this SESSION variable. NOTE: after you use it, be sure you destroy it, so it doesn't persist after it is used:
if (isset($_SESSION['message'])) echo $_SESSION['message']; unset($_SESSION['message']);
add a comment |
If you try to login on site with cookies.
This code:
if ($server_output == "OK") ... else ...
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:s*([^;]*)/mi', $server_output))
echo 'post successful';
else echo 'not successful';
add a comment |
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_error($ch))
throw new Exception(curl_error($ch));
curl_close($ch);
return $response;
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
add a comment |
protected by Community♦ May 6 '16 at 20:50
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") ... else ...
?>
22
no need to usehttp_build_query()
to handle parameters; just pass the array toCURLOPT_POSTFIELDS
is enough.
– Raptor
Apr 5 '16 at 3:13
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
Also if value ofCURLOPT_POSTFIELDS
is an array, theContent-Type
header will be set tomultipart/form-data
instead ofapplication/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php
– Chloe
Jul 21 '16 at 2:34
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
|
show 2 more comments
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") ... else ...
?>
22
no need to usehttp_build_query()
to handle parameters; just pass the array toCURLOPT_POSTFIELDS
is enough.
– Raptor
Apr 5 '16 at 3:13
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
Also if value ofCURLOPT_POSTFIELDS
is an array, theContent-Type
header will be set tomultipart/form-data
instead ofapplication/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php
– Chloe
Jul 21 '16 at 2:34
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
|
show 2 more comments
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") ... else ...
?>
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") ... else ...
?>
edited Aug 7 '18 at 7:50
mimarcel
664720
664720
answered Jan 26 '10 at 9:40
mikumiku
128k33244272
128k33244272
22
no need to usehttp_build_query()
to handle parameters; just pass the array toCURLOPT_POSTFIELDS
is enough.
– Raptor
Apr 5 '16 at 3:13
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
Also if value ofCURLOPT_POSTFIELDS
is an array, theContent-Type
header will be set tomultipart/form-data
instead ofapplication/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php
– Chloe
Jul 21 '16 at 2:34
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
|
show 2 more comments
22
no need to usehttp_build_query()
to handle parameters; just pass the array toCURLOPT_POSTFIELDS
is enough.
– Raptor
Apr 5 '16 at 3:13
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
Also if value ofCURLOPT_POSTFIELDS
is an array, theContent-Type
header will be set tomultipart/form-data
instead ofapplication/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php
– Chloe
Jul 21 '16 at 2:34
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
22
22
no need to use
http_build_query()
to handle parameters; just pass the array to CURLOPT_POSTFIELDS
is enough.– Raptor
Apr 5 '16 at 3:13
no need to use
http_build_query()
to handle parameters; just pass the array to CURLOPT_POSTFIELDS
is enough.– Raptor
Apr 5 '16 at 3:13
4
4
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
@Raptor providing array directly to CURLOPT_POSTFIELDS actually curl makes slightly different type of POST. (Expect: 100-continue)
– Oleg Popov
Apr 14 '16 at 4:49
12
12
Also if value of
CURLOPT_POSTFIELDS
is an array, the Content-Type
header will be set to multipart/form-data
instead of application/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php– Chloe
Jul 21 '16 at 2:34
Also if value of
CURLOPT_POSTFIELDS
is an array, the Content-Type
header will be set to multipart/form-data
instead of application/x-www-form-urlencoded
. php.net/manual/en/function.curl-setopt.php– Chloe
Jul 21 '16 at 2:34
2
2
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
Using CURLOPT_RETURNTRANSFER means that curl_exec will return the response as a string rather than outputting it.
– wclear
Dec 28 '16 at 14:27
3
3
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
Didnt work without http_build_query...
– Denis Matafonov
Jul 3 '17 at 22:01
|
show 2 more comments
Procedural
// set post fields
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
Object oriented
<?php
namespace MyAppHttp;
class Curl
/** @var resource cURL handle */
private $ch;
/** @var mixed The response */
private $response = false;
/**
* @param string $url
* @param array $options
*/
public function __construct($url, array $options = array())
$this->ch = curl_init($url);
foreach ($options as $key => $val)
curl_setopt($this->ch, $key, $val);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
/**
* Get the response
* @return string
* @throws RuntimeException On cURL error
*/
public function getResponse()
if ($this->response)
return $this->response;
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
if (is_resource($this->ch))
curl_close($this->ch);
if (0 !== $errno)
throw new RuntimeException($error, $errno);
return $this->response = $response;
/**
* Let echo out the response
* @return string
*/
public function __toString()
return $this->getResponse();
// usage
$curl = new MyAppHttpCurl('http://www.example.com', array(
CURLOPT_POSTFIELDS => array('username' => 'user1')
));
try
echo $curl;
catch (RuntimeException $ex)
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
Side note here: it would be best to create some kind of interface called AdapterInterface
for example with getResponse()
method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.
Using HTTPS / encrypting traffic
Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed
.
What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.
Never, ever do that. Instead, you simply need to modify your php.ini
and tell PHP where your CA Certificate
file is to let it verify certificates correctly:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:phpcacert.pem
The latest cacert.pem
can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini
related settings remember to restart your webserver.
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
|
show 2 more comments
Procedural
// set post fields
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
Object oriented
<?php
namespace MyAppHttp;
class Curl
/** @var resource cURL handle */
private $ch;
/** @var mixed The response */
private $response = false;
/**
* @param string $url
* @param array $options
*/
public function __construct($url, array $options = array())
$this->ch = curl_init($url);
foreach ($options as $key => $val)
curl_setopt($this->ch, $key, $val);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
/**
* Get the response
* @return string
* @throws RuntimeException On cURL error
*/
public function getResponse()
if ($this->response)
return $this->response;
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
if (is_resource($this->ch))
curl_close($this->ch);
if (0 !== $errno)
throw new RuntimeException($error, $errno);
return $this->response = $response;
/**
* Let echo out the response
* @return string
*/
public function __toString()
return $this->getResponse();
// usage
$curl = new MyAppHttpCurl('http://www.example.com', array(
CURLOPT_POSTFIELDS => array('username' => 'user1')
));
try
echo $curl;
catch (RuntimeException $ex)
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
Side note here: it would be best to create some kind of interface called AdapterInterface
for example with getResponse()
method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.
Using HTTPS / encrypting traffic
Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed
.
What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.
Never, ever do that. Instead, you simply need to modify your php.ini
and tell PHP where your CA Certificate
file is to let it verify certificates correctly:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:phpcacert.pem
The latest cacert.pem
can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini
related settings remember to restart your webserver.
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
|
show 2 more comments
Procedural
// set post fields
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
Object oriented
<?php
namespace MyAppHttp;
class Curl
/** @var resource cURL handle */
private $ch;
/** @var mixed The response */
private $response = false;
/**
* @param string $url
* @param array $options
*/
public function __construct($url, array $options = array())
$this->ch = curl_init($url);
foreach ($options as $key => $val)
curl_setopt($this->ch, $key, $val);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
/**
* Get the response
* @return string
* @throws RuntimeException On cURL error
*/
public function getResponse()
if ($this->response)
return $this->response;
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
if (is_resource($this->ch))
curl_close($this->ch);
if (0 !== $errno)
throw new RuntimeException($error, $errno);
return $this->response = $response;
/**
* Let echo out the response
* @return string
*/
public function __toString()
return $this->getResponse();
// usage
$curl = new MyAppHttpCurl('http://www.example.com', array(
CURLOPT_POSTFIELDS => array('username' => 'user1')
));
try
echo $curl;
catch (RuntimeException $ex)
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
Side note here: it would be best to create some kind of interface called AdapterInterface
for example with getResponse()
method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.
Using HTTPS / encrypting traffic
Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed
.
What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.
Never, ever do that. Instead, you simply need to modify your php.ini
and tell PHP where your CA Certificate
file is to let it verify certificates correctly:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:phpcacert.pem
The latest cacert.pem
can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini
related settings remember to restart your webserver.
Procedural
// set post fields
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
Object oriented
<?php
namespace MyAppHttp;
class Curl
/** @var resource cURL handle */
private $ch;
/** @var mixed The response */
private $response = false;
/**
* @param string $url
* @param array $options
*/
public function __construct($url, array $options = array())
$this->ch = curl_init($url);
foreach ($options as $key => $val)
curl_setopt($this->ch, $key, $val);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
/**
* Get the response
* @return string
* @throws RuntimeException On cURL error
*/
public function getResponse()
if ($this->response)
return $this->response;
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
if (is_resource($this->ch))
curl_close($this->ch);
if (0 !== $errno)
throw new RuntimeException($error, $errno);
return $this->response = $response;
/**
* Let echo out the response
* @return string
*/
public function __toString()
return $this->getResponse();
// usage
$curl = new MyAppHttpCurl('http://www.example.com', array(
CURLOPT_POSTFIELDS => array('username' => 'user1')
));
try
echo $curl;
catch (RuntimeException $ex)
die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
Side note here: it would be best to create some kind of interface called AdapterInterface
for example with getResponse()
method and let the class above implement it. Then you can always swap this implementation with another adapter of your like, without any side effects to your application.
Using HTTPS / encrypting traffic
Usually there's a problem with cURL in PHP under the Windows operating system. While trying to connect to a https protected endpoint, you will get an error telling you that certificate verify failed
.
What most people do here is to tell the cURL library to simply ignore certificate errors and continue (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
). As this will make your code work, you introduce huge security hole and enable malicious users to perform various attacks on your app like Man In The Middle attack or such.
Never, ever do that. Instead, you simply need to modify your php.ini
and tell PHP where your CA Certificate
file is to let it verify certificates correctly:
; modify the absolute path to the cacert.pem file
curl.cainfo=c:phpcacert.pem
The latest cacert.pem
can be downloaded from the Internet or extracted from your favorite browser. When changing any php.ini
related settings remember to restart your webserver.
edited Aug 7 '18 at 7:52
Quentin
641k718631034
641k718631034
answered Aug 20 '15 at 8:15
emixemix
6,30042848
6,30042848
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
|
show 2 more comments
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
4
4
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
This should really be the accepted answer, because best-practice would be to let the HTTP library handle the encoding of your variables.
– Eric Seastrand
Mar 7 '16 at 14:57
4
4
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
This is not always the case. I've seen web servers that expect POST variables to be encoded in a certain way, causing them to fail otherwise. It seems to me that http_build_query() is actually more reliable than cURL for this.
– César
Mar 14 '16 at 15:25
4
4
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
HTTP spec is pretty straightforward on how the POST parameters should look like. The webserver software should comply to standards anyway.
– emix
Mar 15 '16 at 11:46
1
1
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
By using this way you will force cURL to use slightly different type of POST. (Expect: 100-continue). Check this article: support.urbanairship.com/entries/…
– Oleg Popov
Apr 14 '16 at 4:52
3
3
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
Expanding on @César's comment, the PHP documentation explicitly notes the following: "Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.". I recently spent an inordinate amount of time trying to troubleshoot why a cURL call was failing on a third-party endpoint only to eventually realize that they did not support multipart/form-data.
– Mark W
Sep 16 '16 at 19:31
|
show 2 more comments
A live example of using php curl_exec to do an HTTP post:
Put this in a file called foobar.php:
<?php
$ch = curl_init();
$skipper = "luxury assault recreational vehicle";
$fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
$postvars = '';
foreach($fields as $key=>$value)
$postvars .= $key . "=" . $value . "&";
$url = "http://www.google.com";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
Then run it with the command php foobar.php
, it dumps this kind of output to screen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
A mountain of content...
</body>
</html>
So you did a PHP POST to www.google.com and sent it some data.
Had the server been programmed to read in the post variables, it could decide to do something different based upon that.
$postvars .= $key . $value;
should$postvars .= $key . $value ."&";
or not?
– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the$fields
array and it'll output a query string.
– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
Oh no don't try to build the post string yourself! use this:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave outhttp_build_query
like:curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
add a comment |
A live example of using php curl_exec to do an HTTP post:
Put this in a file called foobar.php:
<?php
$ch = curl_init();
$skipper = "luxury assault recreational vehicle";
$fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
$postvars = '';
foreach($fields as $key=>$value)
$postvars .= $key . "=" . $value . "&";
$url = "http://www.google.com";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
Then run it with the command php foobar.php
, it dumps this kind of output to screen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
A mountain of content...
</body>
</html>
So you did a PHP POST to www.google.com and sent it some data.
Had the server been programmed to read in the post variables, it could decide to do something different based upon that.
$postvars .= $key . $value;
should$postvars .= $key . $value ."&";
or not?
– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the$fields
array and it'll output a query string.
– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
Oh no don't try to build the post string yourself! use this:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave outhttp_build_query
like:curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
add a comment |
A live example of using php curl_exec to do an HTTP post:
Put this in a file called foobar.php:
<?php
$ch = curl_init();
$skipper = "luxury assault recreational vehicle";
$fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
$postvars = '';
foreach($fields as $key=>$value)
$postvars .= $key . "=" . $value . "&";
$url = "http://www.google.com";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
Then run it with the command php foobar.php
, it dumps this kind of output to screen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
A mountain of content...
</body>
</html>
So you did a PHP POST to www.google.com and sent it some data.
Had the server been programmed to read in the post variables, it could decide to do something different based upon that.
A live example of using php curl_exec to do an HTTP post:
Put this in a file called foobar.php:
<?php
$ch = curl_init();
$skipper = "luxury assault recreational vehicle";
$fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
$postvars = '';
foreach($fields as $key=>$value)
$postvars .= $key . "=" . $value . "&";
$url = "http://www.google.com";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
?>
Then run it with the command php foobar.php
, it dumps this kind of output to screen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
A mountain of content...
</body>
</html>
So you did a PHP POST to www.google.com and sent it some data.
Had the server been programmed to read in the post variables, it could decide to do something different based upon that.
edited Sep 21 '14 at 12:48
answered Jan 14 '14 at 22:02
Eric LeschinskiEric Leschinski
86.1k37318272
86.1k37318272
$postvars .= $key . $value;
should$postvars .= $key . $value ."&";
or not?
– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the$fields
array and it'll output a query string.
– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
Oh no don't try to build the post string yourself! use this:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave outhttp_build_query
like:curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
add a comment |
$postvars .= $key . $value;
should$postvars .= $key . $value ."&";
or not?
– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the$fields
array and it'll output a query string.
– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
Oh no don't try to build the post string yourself! use this:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave outhttp_build_query
like:curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
$postvars .= $key . $value;
should $postvars .= $key . $value ."&";
or not?– Manwal
Aug 6 '14 at 7:41
$postvars .= $key . $value;
should $postvars .= $key . $value ."&";
or not?– Manwal
Aug 6 '14 at 7:41
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the
$fields
array and it'll output a query string.– user2629998
Nov 17 '14 at 11:54
Looking again at this answer, you can also replace your custom query string converter implementation with http_build_query, just give it the
$fields
array and it'll output a query string.– user2629998
Nov 17 '14 at 11:54
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
Be aware that you should encode your data in order for it to be submitted safely.
– wtf8_decode
Jan 16 '15 at 17:45
3
3
Oh no don't try to build the post string yourself! use this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
Oh no don't try to build the post string yourself! use this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
– oriadam
Sep 29 '15 at 0:21
3
3
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave out
http_build_query
like: curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
-1 because you are not escaping your post vars. The OP's example is sending user-submitted usernames and passwords for authentication. With your solution, a user with an & in their password will never be able to log in. oriadam's comment is correct, but you can leave out
http_build_query
like: curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
– Eric Seastrand
Mar 7 '16 at 14:56
add a comment |
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
add a comment |
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
add a comment |
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
answered Jun 16 '15 at 5:45
Vladimir KovpakVladimir Kovpak
10.6k43646
10.6k43646
add a comment |
add a comment |
Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:
function curlPost($url, $data=NULL, $headers = NULL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($data))
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (!empty($headers))
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch))
trigger_error('Curl Error:' . curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
add a comment |
Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:
function curlPost($url, $data=NULL, $headers = NULL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($data))
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (!empty($headers))
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch))
trigger_error('Curl Error:' . curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
add a comment |
Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:
function curlPost($url, $data=NULL, $headers = NULL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($data))
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (!empty($headers))
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch))
trigger_error('Curl Error:' . curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
Curl Post + Error Handling + Set Headers [thanks to @mantas-d]:
function curlPost($url, $data=NULL, $headers = NULL)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($data))
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (!empty($headers))
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_error($ch))
trigger_error('Curl Error:' . curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
answered Apr 28 '17 at 14:54
MSSMSS
1,7871321
1,7871321
add a comment |
add a comment |
If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.
If you want to stick with the stock lib, just try addingcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
add a comment |
If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.
If you want to stick with the stock lib, just try addingcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
add a comment |
If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.
If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.
edited Mar 29 '18 at 15:37
answered Jan 26 '10 at 9:47
AnthonyAnthony
27.2k2085147
27.2k2085147
If you want to stick with the stock lib, just try addingcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
add a comment |
If you want to stick with the stock lib, just try addingcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
If you want to stick with the stock lib, just try adding
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
If you want to stick with the stock lib, just try adding
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
– MarkHu
Apr 26 '16 at 21:32
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
The only downside is that you still have to deal with setting a cookie jar and other potential issues (like whether to follow redirects, how to deal with non HTTP-based authentication, etc). 6 years later, I would recommend the more generic concept of a "headless-browser" instead of that specific library (or anything on sourceforge, how dated, right?) And while I generally just deal with curl options directly, I would still advise looking at a headless-browser library that is PSR-7 compatible (Guzzle is the only one I know off-hand) to avoid headaches.
– Anthony
Sep 19 '16 at 12:53
add a comment |
Here are some boilerplate code for PHP + curl
http://www.webbotsspidersscreenscrapers.com/DSP_download.php
include in these library will simplify development
<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;
# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
...
?>
add a comment |
Here are some boilerplate code for PHP + curl
http://www.webbotsspidersscreenscrapers.com/DSP_download.php
include in these library will simplify development
<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;
# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
...
?>
add a comment |
Here are some boilerplate code for PHP + curl
http://www.webbotsspidersscreenscrapers.com/DSP_download.php
include in these library will simplify development
<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;
# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
...
?>
Here are some boilerplate code for PHP + curl
http://www.webbotsspidersscreenscrapers.com/DSP_download.php
include in these library will simplify development
<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;
# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
...
?>
answered Oct 10 '13 at 8:41
AziAzi
4,46632847
4,46632847
add a comment |
add a comment |
A simpler answer IF you are passing information to your own website is to use a SESSION variable. Begin php page with:
session_start();
If at some point there is information you want to generate in PHP and pass to the next page in the session, instead of using a POST variable, assign it to a SESSION variable. Example:
$_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.'
Then on the next page you simply reference this SESSION variable. NOTE: after you use it, be sure you destroy it, so it doesn't persist after it is used:
if (isset($_SESSION['message'])) echo $_SESSION['message']; unset($_SESSION['message']);
add a comment |
A simpler answer IF you are passing information to your own website is to use a SESSION variable. Begin php page with:
session_start();
If at some point there is information you want to generate in PHP and pass to the next page in the session, instead of using a POST variable, assign it to a SESSION variable. Example:
$_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.'
Then on the next page you simply reference this SESSION variable. NOTE: after you use it, be sure you destroy it, so it doesn't persist after it is used:
if (isset($_SESSION['message'])) echo $_SESSION['message']; unset($_SESSION['message']);
add a comment |
A simpler answer IF you are passing information to your own website is to use a SESSION variable. Begin php page with:
session_start();
If at some point there is information you want to generate in PHP and pass to the next page in the session, instead of using a POST variable, assign it to a SESSION variable. Example:
$_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.'
Then on the next page you simply reference this SESSION variable. NOTE: after you use it, be sure you destroy it, so it doesn't persist after it is used:
if (isset($_SESSION['message'])) echo $_SESSION['message']; unset($_SESSION['message']);
A simpler answer IF you are passing information to your own website is to use a SESSION variable. Begin php page with:
session_start();
If at some point there is information you want to generate in PHP and pass to the next page in the session, instead of using a POST variable, assign it to a SESSION variable. Example:
$_SESSION['message']='www.'.$_GET['school'].'.edu was not found. Please try again.'
Then on the next page you simply reference this SESSION variable. NOTE: after you use it, be sure you destroy it, so it doesn't persist after it is used:
if (isset($_SESSION['message'])) echo $_SESSION['message']; unset($_SESSION['message']);
edited Jun 28 '13 at 17:52
andrewsi
10.7k112947
10.7k112947
answered Jun 28 '13 at 17:33
user2532795user2532795
291
291
add a comment |
add a comment |
If you try to login on site with cookies.
This code:
if ($server_output == "OK") ... else ...
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:s*([^;]*)/mi', $server_output))
echo 'post successful';
else echo 'not successful';
add a comment |
If you try to login on site with cookies.
This code:
if ($server_output == "OK") ... else ...
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:s*([^;]*)/mi', $server_output))
echo 'post successful';
else echo 'not successful';
add a comment |
If you try to login on site with cookies.
This code:
if ($server_output == "OK") ... else ...
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:s*([^;]*)/mi', $server_output))
echo 'post successful';
else echo 'not successful';
If you try to login on site with cookies.
This code:
if ($server_output == "OK") ... else ...
May not works if you try to login, because many sites returns status 200, but the post is not successful.
Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.
Also the post can be successful, but the status can be redirect instead 200.
To be sure the post is successful try this:
Follow location after the post, so it will go to the page where the post do redirect to:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
And than check if new cookies existing in the request:
if (!preg_match('/^Set-Cookie:s*([^;]*)/mi', $server_output))
echo 'post successful';
else echo 'not successful';
answered Jan 17 '18 at 10:02
Atanas AtanasovAtanas Atanasov
413
413
add a comment |
add a comment |
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_error($ch))
throw new Exception(curl_error($ch));
curl_close($ch);
return $response;
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
add a comment |
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_error($ch))
throw new Exception(curl_error($ch));
curl_close($ch);
return $response;
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
add a comment |
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_error($ch))
throw new Exception(curl_error($ch));
curl_close($ch);
return $response;
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data)
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_error($ch))
throw new Exception(curl_error($ch));
curl_close($ch);
return $response;
edited Mar 30 '18 at 6:43
answered Apr 13 '16 at 16:35
Mantas DMantas D
2,39021320
2,39021320
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
add a comment |
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
2
2
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
No error handling, terrible.
– emix
Jun 21 '16 at 10:19
add a comment |
protected by Community♦ May 6 '16 at 20:50
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?