Posting to a file using Curl
I'm trying to post to a file as soon as user enters a website assuming they have clicked from an ad.
Example url = http://myFabSite.com/?tr=213
This is what I'm trying but its not capturing the tr URL variable or the referrer:
if($_GET['tr']){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://myFabSite.com/actions/tracksAds.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'referrer' => $_SERVER['HTTP_REFERER'],
'track_code' => $_GET['tr']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
trackAds.php:
$mysqli = dbConnect();
$referrer = $mysqli->real_escape_string(urldecode(trim($_REQUEST['referrer'])));
$track_code = $mysqli->real_escape_string($_REQUEST['track_code']);
$query = "insert into ad_tracking ( tracking_code, referrer ) VALUES ( '$track_code', '$referrer' )";
$result = $mysqli->query($query);
Anything obvious?
UPDATE
This is from print_r($data);
Array
(
[referrer] => none
[track_code] => fb1
)
This is $query from trackAds.php
insert into ad_tracking ( tracking_code, referrer ) VALUES ( '', '' )
So, the array is not being passed, either at all or correctly, to trackAds.php
You're missing quotes in $_GET[tr] on the first line. Change it to $_GET['tr'].
Also, use $_POST instead of $_REQUEST in trackAds.php. There's a great chance here that you are inadvertently getting a cookie value instead of a POST value, or simply have the wrong data in $_REQUEST. See this page in the documentation.
Actually found a different method which works ok, still no clue why the other doesn't.
This assumes PHP 5+
$url = 'http://myFabSite.com/actions/tracksAds.php';
$data = array('referrer' => $_SERVER['HTTP_REFERER'], 'track_code' => $_GET['tr']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
Related
I am having the following code to make a GET statement to the REST API of Parse server using PHP:
$query = json_encode(
array(
'where' => array( 'userid' => "8728792347239" )
));
echo $query;
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers?'.$query);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'X-Parse-Application-Id: *hidden*',
'X-Parse-REST-API-Key: *hidden*',
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
print_r($response);
However I am getting the following error:
{"code":102,"error":"Invalid parameter for query: {\"where\":{\"userid\":\"8728792347239\"}}"}
What am I doing wrong?
without having read the documentation, i bet it's supposed to be url-encoded, not json-encoded -OR- that the data is supposed to be in the POST body, not the URL query.
if guess #1 is correct, then your problem is that you're using json_encode instead of http_build_query eg
$query = http_build_query(
array(
'where' => array( 'userid' => "8728792347239" )
));
if guess #2 is correct, then your problem is that you're adding the data to the url query instead of adding it to the request body, eg
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers');
curl_setopt($ch,CURLOPT_POSTFIELDS,$query);
I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);
I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
You know how in PHP there's a method called file_get_content that gets the content of the page for the provided url? Is there an opposite method for it? Like, for example, file_post_content, where you can post data to external websites? Just asking for educational purposes.
You can use without cURL but file_get_contents PHP this example:
$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
See the PHP website: http://php.net/manual/en/function.file-get-contents.php#102575
Could write one:
<?php
function file_post_content($url, $data = array()){
// Collect URL. Optional Array of DATA ['name' => 'value']
// Return response from server or FALSE
if(empty($url)){
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
if(count($data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$svr_out = curl_exec ($ch);
curl_close ($ch);
return $svr_out;
}
?>
I am submitting some data from website1 to website2 using curl.
When I submit data via then on receiving end I get it like
Array
(
[ip] => 112.196.17.54
[amp;email] => test#test.com
[amp;user] => test123,
[amp;type] => point
[amp;password] => password
)
According to me http_build_query() producing wrong results.
"ip" field is correct rest are incorrect.
Please let me know why it happens.
curl function is given below: http_build_query($config)
function registerOnPoints($username ,$password,$email,$ip , $time )
{
$ch = curl_init("http://website2c.com/curl-handler");
curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, 1);
$config = array( 'ip' => $ip,
'user' => $username,
'email' => $email,
'password'=> $password,
'time' => $time,
'type' => 'point') ;
# add curl post data
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($config));
curl_setopt($ch, CURLOPT_POST, true);
# execute
$response = curl_exec($ch);
# retreive status code
$http_status = curl_getinfo($ch , CURLINFO_HTTP_CODE);
if($http_status == '200')
{
$response = json_decode($response);
} else {
echo $http_status;
}
// Close handle
curl_close($ch);
}
If it is php version issue then, clearly speaking I have no permission to change the version of php because only the curl function is producing error rest project is completed and working as expected.
Please help me.
i guess you could try:
http_build_query($config, '', '&');
Or alternative:
$paramsArr = array();
foreach($config as $param => $value) {
$paramsArr[] = "$param=$value";
}
$joined = implode('&', $paramsArr);
//and use
curl_setopt($ch, CURLOPT_POSTFIELDS, $joined);