Related
This is the $_POST
Array
(
[name] => image.png
[type] => image/png
[tmp_name] => C:\xampp5\tmp\phpA637.tmp
[error] => 0
[size] => 16412
)
And here's the code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "2403",
CURLOPT_URL => "http://".cfg('api_ip').":2403/sk_group/update_profile_pic", //url
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{\"groupId\":\"".$group."\",\"profile_pic\":\"".$name."\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_pic\"; filename=\"".$file."\"\r\nContent-Type: ".$type."\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"SessionId: ".$_SESSION['session']."",
"VersionCode: ".cfg('version_code')."",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
redirect("/meme/me/group"."?msg=".urldecode('Update icon group succes')."&type_msg=success");
}
i want to know how to $file to the image for success upload, cause $_POST only display the filename not with the fullpath.
Update
this is the full function in controller i have
function one()
{
$filename = $_FILES['icon']['name'];
$filedata = $_FILES['icon']['tmp_name'];
$filetype = $_FILES['icon']['type'];
two($_POST['group'], $filename, $filedata, $filetype);
}
this function on my helper
function two($group, $name, $file, $type)
{
$cFile = new CURLFile($file,$type,$name);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "2403",
CURLOPT_URL => "http://".cfg('api_ip').":2403/sk_group/update_profile_pic",
CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{\"groupId\":\"".$group."\",\"profile_pic\":\"".$name."\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"profile_pic\"; filename=\"".$cFile."\"\r\nContent-Type: ".$type."\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"SessionId: ".$_SESSION['session']."",
"VersionCode: ".cfg('version_code')."",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
redirect("/meme/me/group"."?msg=".urldecode('Update icon group succes')."&type_msg=success");
}
}
still with same question like i asking..., where the file? and how to post it until success?
I have posted the same answer here
From PHP 5.5 and above the CURL will use CURL File to upload the files, for the lower PHP version, you need to manually generate the form boundary and then send the file. The following code sample handles both the cases.
For ease, here's the main part:
<?php
$file = "websites.txt";
upload_with_compatibility($file);
function upload_with_compatibility($file){
if (version_compare(phpversion(), '5.5', '>=')) {
echo "Upload will be done using CURLFile\n";
upload($file); //CURL file upload using CURLFile for PHP v5.5 or greater
}else{
echo "Upload will be done without CURLFile\n";
compatibleUpload($file); //CURL file upload without CURLFile for PHP less than v5.5
}
}
//Upload file using CURLFile
function upload($file){
$target = "http://localhost:8888/upload_file.php";
$host = parse_url($target);
$cFile = new CURLFile($file,'text/plain', $file);
$data = array(
'log_file' => $cFile,
);
//you can play around with headers, and adjust as per your need
$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36';
$curlHeaders = array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding: gzip, deflate',
'Accept-Language: en-US,en;q=0.8',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36', //change user agent if you want
'Connection: Keep-Alive',
'Pragma: no-cache',
'Referer: http://localhost:8888/upload.php', //you can change referer, if you want or remove it
'Host: ' . $host['host'] . (isset($host['port']) ? ':' . $host['port'] : null), // building host header
'Cache-Control: max-age=0',
'Cookie: __utma=61117235.2020578233.1500534080.1500894744.1502696111.4; __utmz=61117235.1500534080.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', //adjust your cookie if you want
'Expect: '
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_HEADER , true); //we need header
curl_setopt($curl, CURLOPT_USERAGENT,$agent);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$r = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfull
print_r($r);
}
}
curl_close($curl);
}
//Upload file without using CURLFile, because we are upload a file, so we need to generate form boundry
function compatibleUpload($file){
$target = "http://localhost:8888/upload_file.php";
//use this to send any post parameters expect file types
//if you are not sending any other post params expect file, just assign an empty array
// $assoc = array(
// 'name' => 'demo',
// 'status' => '1'
// );
$assoc = array(); //like this
//this array is used to send files
$files = array('log_file' => $file);
static $disallow = array("\0", "\"", "\r", "\n");
// build normal parameters
foreach ($assoc as $k => $v) {
$k = str_replace($disallow, "_", $k);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"",
"",
filter_var($v),
));
}
// build file parameters
foreach ($files as $k => $v) {
switch (true) {
case false === $v = realpath(filter_var($v)):
case !is_file($v):
case !is_readable($v):
continue; // or return false, throw new InvalidArgumentException
}
$data = file_get_contents($v);
$v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
$k = str_replace($disallow, "_", $k);
$v = str_replace($disallow, "_", $v);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
"Content-Type: application/octet-stream",
"",
$data,
));
}
// generate safe boundary
do {
$boundary = "---------------------" . md5(mt_rand() . microtime());
} while (preg_grep("/{$boundary}/", $body));
// add boundary for each parameters
array_walk($body, function (&$part) use ($boundary) {
$part = "--{$boundary}\r\n{$part}";
});
// add final boundary
$body[] = "--{$boundary}--";
$body[] = "";
// set options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_HEADER , true); //we need header
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => implode("\r\n", $body),
CURLOPT_HTTPHEADER => array(
"Expect: ",
"Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
),
));
$r = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfully uploaded
print_r($r);
}
}
curl_close($ch);
}
?>
I get error reading data from json source, I get a blank page error.
I am making a mistake.
I just want to get the category BetTypeId = 3.
Could you help?
<?php
error_reporting(1);
header("Content-type: text/xml; charset=utf-8");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.misli.com/scripts/BetList.aspx?action=get&BetTypeId&3",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
),
));
$ok = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "<Maclar>";
if($ok->BetTypeId=="3")
{
$tarih = $ok->CloseDate;
$ulke = $ok->CountryName;
echo '<ulke="'.$ulke.'" tarih="'.$tarih.'" />';
}
echo "</Maclar>";
}
?>
The target site you want to fetch data will check the browser agent.
Add the agent and fix the problem pointed out by Scuzzy, then your code will work.
You could refer the following code. Please note there may be error of your xml format, that will cause the browser doesn't display the response data normally. But I did get the response <Maclar><ulke="Şampiyonlar Ligi" tarih="2018-02-13T22:45:00" /></Maclar>
The code:
<?php
error_reporting(1);
header("Content-type: text/xml; charset=utf-8");
$agent= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.misli.com/scripts/BetList.aspx?action=get&BetTypeId&3",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_USERAGENT=>$agent,
CURLOPT_HTTPHEADER => "accept: application/json"
));
$ok = curl_exec($curl);
//echo $ok;
$ok = json_decode($ok);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else {
echo "<Maclar>";
if($ok[0]->BetTypeId=="3")
{
$tarih = $ok[0]->CloseDate;
$ulke = $ok[0]->CountryName;
echo '<ulke="'.$ulke.'" tarih="'.$tarih.'" />';
}
echo "</Maclar>";
}
?>
Hope it helps.
I am using this code to get the contents of a post request url using php curl
Code looks as below:
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www1.ptt.gov.tr/tr/interaktif/sonuc-yd.php',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'barcode' => 'CP021325078TR',
'security_code' => $capcha2
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo "<pre>";
var_dump($resp);
echo "</pre>";
The result doesn’t seem to return anything at all.
What is wrong with this code?
Try this:
$url = 'http://www1.ptt.gov.tr/tr/interaktif/sonuc-yd.php';
$postvals = array(
'barcode' => 'CP021325078TR',
'security_code' => $capcha2
);
$resp = Request($url,$postvals);
echo "<pre>"; var_dump($resp); exit;
...
function Request($url,$params=array()){
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
if(!empty($params)){
$curlOpts[CURLOPT_POST] = true;
$curlOpts[CURLOPT_POSTFIELDS] = $params;
}
curl_setopt_array($ch,$curlOpts);
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch); exit;
}
curl_close($ch);
return $answer;
}
EDIT:
I tested this and got:
Could not resolve host: www1.ptt.gov.tr
So make sure you're calling the right endpoint.
Actually you need to set this variable
$captcha2
To use it here -
'security_code' => $capcha2
I'm getting a very strange behavior when I do multiple requests with curl. Here's the function I have:
function http_request($curl, $url, $post = null)
{
echo (isset($post) ? 'POST ' . $url : 'GET ' . $url) . PHP_EOL;
try
{
$cookie_path = tempnam(null, 'b');
curl_setopt_array($curl, array
(
CURLOPT_COOKIEFILE => $cookie_path,
CURLOPT_COOKIEJAR => $cookie_path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => count($post),
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
CURLOPT_HTTPHEADER => array
(
'Accept-Language: en-US;q=0.6,en;q=0.4',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
));
return curl_exec($curl);
}
catch(Exception $exception)
{
echo $exception;
}
}
Here's the code I use to call it:
$curl = curl_init();
http_request($curl, "http://host.com/url1");
http_request($curl, "http://host.com/url2", "postdata=123");
http_request($curl, "http://host.com/url3");
http_request($curl, "http://host.com/url4");
curl_close($curl);
This is the output I'm getting:
GET http://host.com/url1
POST http://host.com/url2
GET http://host.com/url3
GET http://host.com/url4
So far so good, but using packet analyzer (wireshark), the output looks like this:
POST http://host.com/url1
Content-Length: 0;
POST http://host.com/url2
Content-Length: 12;
POST http://host.com/url3
Content-Length: 0;
POST http://host.com/url4
Content-Length: 0;
Then I rewrote the code like this:
function http_request($curl, $url, $post = null)
{
echo (isset($post) ? 'POST ' . $url : 'GET ' . $url) . PHP_EOL;
try
{
$cookie_path = tempnam(null, 'b');
curl_setopt_array($curl, array
(
CURLOPT_COOKIEFILE => $cookie_path,
CURLOPT_COOKIEJAR => $cookie_path,
CURLOPT_COOKIESESSION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0',
CURLOPT_HTTPHEADER => array
(
'Accept-Language: en-US;q=0.6,en;q=0.4',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
));
if($post != null)
{
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
return curl_exec($curl);
}
catch(Exception $exception)
{
echo $exception;
}
}
but still the same thing happens, if I remove this code from the function:
if($post != null)
{
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
In packet analyzer I get:
GET http://host.com/url1
GET http://host.com/url2
GET http://host.com/url3
GET http://host.com/url4
It makes no sense how it gets set to POST on the first request, even my $post argument is not set. Thanks!
I vaguely remember I had the same problem some time ago. Try setting CURLOPT_HTTPGET explicitly as well:
if($post != null)
{
curl_setopt($curl, CURLOPT_HTTPGET, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
else
{
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, null);
}
I would like to know how to send a post request in curl and get the response page.
What about something like this :
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://www.example.com/yourscript.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'field1' => 'some date',
'field2' => 'some other data',
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
// result sent by the remote server is in $result
For a list of options that can be used with curl, you can take a look at the page of curl_setopt.
Here, you'll have to use, at least :
CURLOPT_POST : as you want to send a POST request, and not a GET
CURLOPT_RETURNTRANSFER : depending on whether you want curl_exec to return the result of the request, or to just output it.
CURLOPT_POSTFIELDS : The data that will be posted -- can be written directly as a string, like a querystring, or using an array
And don't hesitate to read the curl section of the PHP manual ;-)
$url = "http://www.example.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
curl_close($ch);
You need to set the request to post using CURLOPT_POST and if you want to pass data with it, use CURLOPT_POSTFIELDS:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$contents = curl_exec($ch);
curl_close($ch);
try the one in the comments: http://php.net/manual/en/curl.examples-basic.php
(but add curl_setopt($ch, CURLOPT_POST, 1) to make it a post instead of get)
or this example: http://php.dzone.com/news/execute-http-post-using-php-cu
<?php
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
?>
I think you need to add
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
Using JSON DATA with CURL
client.php
<?php
$url="http://192.168.44.10/project/server/curl_server.php";
$data=['username'=>'abc','password'=>'123'];
$data = json_encode($data);
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
echo $result; //here you get result like: username: abc and password: 123
?>
curl_server.php
<?php
$data = file_get_contents('php://input');
$Data= json_decode($data,true);
echo 'username: '.$Data['username']." and password: ".$Data['password'];
?>
Check out my code in this post
https://stackoverflow.com/a/56027033/6733212
<?php
if (!function_exists('curl_version')) {
exit("Enable cURL in PHP");
}
$url = "https://www.google.com/";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Host: " . url($url),
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"accept-encoding: gzip, deflate",
"cache-control: no-cache",
),
));
function url($url)
{
$result = parse_url($url);
return $result['host'];
}
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "<textarea>" . $response . "</textarea>";
}
http://codepad.org/YE6fyzCA