Send parameters to a URL and get output from that page - php

I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:
abc.php:
<?php
$id="123";
$name="blahblah";
//need to send the value to def.php & get value from that page
// echo $value=Print the "Value received" msg from def.php;
?>
def.php:
<?php
$id=$_GET['id'];
$name=$_GET['name'];
if(!is_null($id)&&!is_null($name))
{ echo "Value received";}
else{echo "Not ok";}
?>
Is there any kind heart who can help me solve the issue?

First make up your mind : do you want GET or POST parameters.
Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :
$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.

You can try without cURL (I havent tried though):
Copy pasted from : POSTing data without cURL extension
// Your POST data
$data = http_build_query(array(
'param1' => 'data1',
'param2' => 'data2'
));
// Create HTTP stream context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('http://example.com', false, $context);

Taken from the examples page of php.net:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
Edit: To send parameters
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));

use CURL or Zend_Http_Client.

<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
'manufacturer' => 'kraft',
'packaging_type' => 'bag'
);
if ($method == 'POST'){
//Make POST request
$data = http_build_query($data);
$context = stream_context_create(array(
'http' => array(
'method' => "$method",
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data)
)
);
$response = file_get_contents($url, false, $context);
}
else {
// Make GET request
$data = http_build_query($data, '', '&');
$response = file_get_contents($url."?".$data, false);
}
echo $response;
?>
get inspired by trix's answer, I decided to extend that code to cater for both GET and POST method.

Related

Coinmarketcap API Call with PHP

I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);

Pass whole incoming data to curl - Laravel

I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}
If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,
Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.

How to output the contents of file_get_contents

I'm trying to figure out how to get a php file (html, css and javascript) and load it into the content section below.
The following is the original...
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'Help',
'content' => 'HTML CONTENT',
I have tried the following but fails. I added a file_get_contents (first line), and then tried pull it in with 'content' => $adminhelp,
The following is with my amended code...
$adminhelp = file_get_contents('admin-help.php');
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'WTV Help',
'content' => $adminhelp,
Any ideas what's wrong?
If you want the output of the PHP file to be saved as $adminhelp use:
$adminhelp = file_get_contents('http://YOUR_DOMAIN/admin-help.php');
Right now you're loading the source code of admin-help.php into $adminhelp.
Another example for getting the output of a webpage is cURL:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://YOUR_DOMAIN/admin-help.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$adminhelp = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
If this doesn't answer your question, please include the error message that you're receiving.

PHP cURL Google reCaptcha2 Header Injection

i have some Trouble with cURL and Google reCaptcha2 to avoid "Robot" & "Spammer" Auto-Reg´s.
So i Chose google´s reCaptcha2 to check the User´s on WWW Site .
The Problem:
after checking the code, i found there is an
Header Injection in 'curl_setopt_array' via '$curlConfig'
My Serverside reCaptcha using cURL because of PHP File getContent blocked by PHP Config.
My reCaptcha Code:
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
$privatekey = '######### Priv Key ###############';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $privatekey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
$ch = curl_init();
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
curl_close($ch);}
So, as result we decode the data from json String back:
$jsonResponse = json_decode($response);
if ($jsonResponse->success == "true") { Good } else { Exit not good! }
The Injection ? Data= Array ? $Serve ?
thanks for help
i don't see any code injection vulnerabilities here, but you don't show us how you handle the event of no g-recaptcha-response being in the POST request at all. most likely, you don't handle that event, and all an hacker needs to do, to get past your captcha, is to not send the g-recaptcha-response field at all. instead of if (isset($_POST['g-recaptcha-response'])) , do something like if (empty($_POST['g-recaptcha-response'])) {http_response_code(400);die('no captcha answer provided!');}}

Send AJAX-like post request using PHP only

I'm currently working on some automatization script in PHP (No HTML!).
I have two PHP files. One is executing the script, and another one receive $_POST data and returns information.
The question is how from one PHP script to send POST to another PHP script, get return variables and continue working on that first script without HTML form and no redirects.
I need to make requests a couple of times from first PHP file to another under different conditions and return different type of data, depending on request.
I have something like this:
<?php // action.php (first PHP script)
/*
doing some stuff
*/
$data = sendPost('get_info');// send POST to getinfo.php with attribute ['get_info'] and return data from another file
$mysqli->query("INSERT INTO domains (id, name, address, email)
VALUES('".$data['id']."', '".$data['name']."', '".$data['address']."', '".$data['email']."')") or die(mysqli_error($mysqli));
/*
continue doing some stuff
*/
$data2 = sendPost('what_is_the_time');// send POST to getinfo.php with attribute ['what_is_the_time'] and return time data from another file
sendPost('get_info' or 'what_is_the_time'){
//do post with desired attribute
return $data; }
?>
I think i need some function that will be called with an attribute, sending post request and returning data based on request.
And the second PHP file:
<?php // getinfo.php (another PHP script)
if($_POST['get_info']){
//do some actions
$data = anotherFunction();
return $data;
}
if($_POST['what_is_the_time']){
$time = time();
return $time;
}
function anotherFunction(){
//do some stuff
return $result;
}
?>
Thanks in advance guys.
Update: OK. the curl method is fetching the output of php file. How to just return a $data variable instead of whole output?
You should use curl. your function will be like this:
function sendPost($data) {
$ch = curl_init();
// you should put here url of your getinfo.php script
curl_setopt($ch, CURLOPT_URL, "getinfo.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then you should call it this way:
$data = sendPost( array('get_info'=>1) );
I will give you some example class , In the below example you can use this as a get and also post call as well. I hope this will help you.!
/*
for your reference . Please provide argument like this,
$requestBody = array(
'action' => $_POST['action'],
'method'=> $_POST['method'],
'amount'=> $_POST['amount'],
'description'=> $_POST['description']
);
$http = "http://localhost/test-folder/source/signup.php";
$resp = Curl::postAuth($http,$requestBody);
*/
class Curl {
// without header
public static function post($http,$requestBody){
$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 ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
// with authorization header
public static function postAuth($http,$requestBody,$token){
if(!isset($token)){
$resposne = new stdClass();
$resposne->code = 400;
$resposne-> message = "auth not found";
return json_encode($resposne);
}
$curl = curl_init();
$headers = array(
'auth-token: '.$token,
);
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => $headers ,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $http ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}

Categories