Post and get result with PHP - php

From a PHP page, I'm trying to POST some data to another PHP page and get data back.
Here is what I currently have:
<?php
// Initialize cURL session
$ch = curl_init('postpage.php');
// Set some options on the session
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('field1' => 'Andrew'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute post
$result = curl_exec($ch);
var_dump($result);
// Close the session
curl_close($ch);
?>
and in postpage.php:
<?php
echo 'Receipt of post request. field1:'.$_POST["field1"];
?>
All the var_dump gives me is this:
string(0) ""
Why am I not getting the text back?
Thanks!

The curl executed from your php script is not aware of the current environment, that is, you cannot use relative urls. The url you supply to curl_init must be absolute (i.e. including http://)

If this is indeed the actual initialization you're doing, the error may lie in the arguments of curl_init() which expects a fully qualified URL.
Also, you might want to employ some error diagnostics. curl_exec returns FALSE on failure. The reason why can be determined with curl_error():
$ch = curl_init( ... );
// ... some curl_setopt()
$result = curl_exec($ch);
if ($result === FALSE)
{
die("cURL error: " . curl_error($ch));
}

Related

cURL results in NULL although JSON is valid

I'm curling a url that drops a json result. The result of the curl is always NULL though.
main.php
function getUserSettings(){
...
$json = json_encode($userSettings);
header('Content-Type: application/json');
return $json;
}
getusersettings.php
...
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();
$result = $api->getUserSettings();
echo $result;
...
settings.php
<?php
session_start();
if(isset($_SESSION['uid'])) {
//get the user settings
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, 'https://www.url.com/api/getstgs');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
print_r($obj);die();
}
...
generate html
...
?>
The json looks like this:
{"lcns":[{"product_name":"Addon: Addonname","license_key_decrypted":"XXXXXXXXXXXXXX","expires_at":"0000-00-00 00:00:00"}],"stgs":[{"Type":"1","Amount":"0"}]}
Per the shown code, the cURL call is expected to 'fail'.
This is because cURL makes a new request which does not automatically include session information or cookies. Such behavior can be duplicated using cURL from the command-line or a browser tab in a new incognito window. (Checking the result of web requests from other tools can diagnose a number of issues much quicker than code changes.)
The following is expected to fail the request instead of returning the desired JSON unless the session "uid" value has previously been established this request. It does not matter if there is a session "uid" value in the request which invoked cURL: the request made by cURL is separate.
$api->uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : die();

PHP & CURL scraping

I have a problem when I run this script in Google Chrome I got a blank page. When I use another link of a web site, it works successfully. I do not what is happening.
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
echo $output;
There are some conditions which make your result blank. Such as:
Curl error.
Redirection without response body and the curl doesn't follow the redirection.
The target host doesn't give any response body.
So here you have to find out the problem.
For the first possibility, use curl_error and curl_errno to confirm that the curl wasn't errored when its runtime.
For the second, use CURLOPT_FOLLOWLOCATION option to make sure the curl follows the redirection.
For the third possibility, we can use curl_getinfo. It returns an array which contains "size_download". The size_download shows you the length of the response body. If it is zero that is why you see a blank page when printing it.
One more, try to use var_dump to see the output (debug purpose only). There is a possibility where the curl_exec returns bool false or null. If you print the bool false or null it will show a blank.
Here is the example to use all of them.
<?php
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
$ern = curl_errno($curl);
if ($ern) {
printf("An error occurred: (%d) %s\n", $ern, $err);
exit(1);
}
curl_close($curl);
printf("Response body size: %d\n", $info["size_download"]);
// Debug only.
// var_dump($output);
echo $output;
Hope this can help you.
Update:
You can use CURLOPT_VERBOSE to see the request and response information in details.
Just add this
curl_setopt($curl, CURLOPT_VERBOSE, true);
It doesn't need to be printed, the curl will print it for you during runtime.

Curl showing but not returning data

I'm trying to write a simple curl function that queries the freegeoip.net site with the IP address of a site visitor. This is usually done by typing "https://freegeoip.net/csv/{IP Address}" in the browser address line. The site then processes the request and returns a csv file that can be opened or saved. I'm trying to access the csv data directly so that I can parse and use it. This is the code that I am using:
<?php
$ip=$_SERVER["REMOTE_ADDR"];
$geturl = "http://freegeoip.net/csv/".$ip;
$data = curl_get_contents($geturl);
echo ("<br>Data = '".$data."'<br>");
function curl_get_contents($url)
{
$ch = curl_init($url);
if($ch)
{
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
else
{
echo "Curl not loaded!<br>";
}
}
?>
This is what I am getting back:
...,US,United States,ST,State,City,?????,America/New_York,.*****,-.****,***
Data = '1'
As you can see, my function is accessing and showing the csv data but not returning it to the $data variable. Apparently, the data is being shown when the "curl_exec($ch);" command is being executed. I want to parse and use the returned data but can't until the data is returned. What am I doing wrong?
The documentation of curl_exec() says:
Return Values
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
What it doesn't say is explained in the documentation page of curl_setopt(), on the CURLOPT_RETURNTRANSFER option:
Option: CURLOPT_RETURNTRANSFER
Set value to: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
That is, by default, curl_exec() outputs the body of the response it gets. In order to make it return the value and not output it, you have to use curl_setopt():
$ch = curl_init($url);
curl_exec($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
you need to add following line before curl_exec other wise the result will output instead of returning it to $tmp variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
You aren't telling Curl that you want the data to be returned rather than output:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_URL, "http://freegeoip.net/csv/".$ip);
$csv=curl_exec($ch);
But this is rather verbose when, depending on your config, you can:
$csv=file_get_contents("http://freegeoip.net/csv/".$ip);

PHP file_get_contents does not return an error when it should

I am using file_get_contents to get the json from URLs. The same URL works sometimes and sometimes it doesn't. When it doesn't, file_get_contents does not return any error and just stops the whole script. It's too confusing.
What's error you get? It's warning or Fatal Error?
if it's warning, please add # to befor file_get_contents like: #file_get_contents
if other, please check data before execute other process
$jsondata =#file_get_contents('YOur URl');
if($jsondata){
// Process your code
}else{
//do nothing
}
What a URL is returning when the correct data is not outputted ?
1)
$json_data =file_get_contents('URl');
if($json_data){
//parse the data
}else{
//show error
}
2 to find what exactly the url returns
$json_data =file_get_contents('URl');
var_dump($json_data);
3 use cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj)

passing variable to another page when it is called using curl_setopt

I am usig curl_setopt to eval another file from a different server, the link is something like this "http://somewhere.com/index.php?vars=hello"
now in somewhere.com/index.php i need to get the value of vars that was passed using curl, but so far i cant get any values at all.
here is my sample code for your reference this is from the file calling somewhere.com:
$d = "http://somewhere.com/index.php?vars=hello";
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_URL, $d);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, TRUE);
$data1 = curl_exec($ch1);
eval($data1);
curl_close($ch1);
in somewhere.com/index.php i already did print_r($_GET); to view any passed values to the file but it returned nothing.
What is happening in the index.php file with the variable "hello"? When you do a curl post to another page that other page typically will echo out a response and that response is what you evaluate. Can you post your code from index.php so we can see what you are trying to do?
Edit: Also you can use chrome inspector, fiddler or some other network monitor to see if the http request actually is being fired off and to check that you are actually getting a 200 response back.
Edit: I don't know what you are using eval either, just echo the response. If you have an output buffer issue then start buffering before you echo the response like:
ob_start():
echo $data1;
ob_end_clean();
Also if you want to see if you are getting any errors just do this:
if(curl_exec($ch1) === false)
{
echo 'Curl error: ' . curl_error($ch1);
}
else
{
echo $data1;
}
// Close handle
curl_close($ch1);
can't you just use $_GET[]?
i.e.
$variables = $_GET['vars'];

Categories