This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
I declared configuration variables in a configuration file and want to access these variables from within a function on the same page. This function will make a SOAP call to a service to fetch some data.
I include this configuration file on various pages, but when I access the function, the variables are empty, even when I declare a global score. My (simplified) code looks like this:
config.php
// Set environment
$environment = 'dev';
switch($environment){
case 'dev':
$username = 'dev';
$client = new SoapClient('http://dev.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
break;
case 'prod';
$username = 'prod';
$client = new SoapClient('http://prod.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
break;
default:
$username = 'prod';
$client = new SoapClient('http://prod.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
}
function fetch_data($request_id){
global $username;
$xml_post_string = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ver="https://example.com">
<soapenv:Header/>
<soapenv:Body>
<ver:options>
<ver:rid>'.$request_id.'</ver:rid>
<ver:uid>'.$username.'</ver:uid>
</ver:options>
</soapenv:Body>
</soapenv:Envelope>
';
echo '<pre>';
echo 'Var: '.$username; // = empty
echo '</pre>';
// Curl headers
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: "https://example.com",
"Content-length: ".strlen($xml_post_string),
);
// Curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/call?wsdl');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute Curl call
$response = curl_exec($ch); // = credential error
}
On page.php i include & call the function like this:
require_once('config.php');
[..]
$response = fetch_data('1');
When I type the username in the XML string I get the response I want, but when I use the variable (as in the example) I get an empty value for $username.
But why?
edit: changed exit; to break; and added process & output example
** edit 2:**
The code between the [..]
require_once('config.php');
global $current_user, $wp_query;
$user = wp_get_current_user();
$user_meta = get_user_meta($user->data->ID, 'exID');
$user_member_number = trim($user_meta[0]);
// Set locale for date notation
setlocale(LC_ALL, 'nl_NL');
$policy_id = $_GET['polis'];
$customer_call = array(
'options' => array(
'Credentials' => array(
'UserId' => $username // Normally more credentials like password are required as well
)
)
);
$customer_response = $client->FetchCustomer($customer_call);
$member_details = $customer_response->FetchCustomerResult->Result->PlatformCustomer;
$product_call = array(
'options' => array(
'Credentials' => array(
'UserId' => $username // Normally more credentials like password are required as well
)
),
);
$product_response = $client->FetchProduct($product_call);
if($product_response->FetchProductResult->Succeeded){
// Extract results
$product_info = $product_response->FetchProductResult->Result;
// Differentiate product response, depending on the amount of rows returned
if($product_info->SummarizedProductInfo >= 2){
$products = $product_response->FetchProductResult->Result->Summary;
}else{
$products = $product_response->FetchProductResult->Result;
}
// Policy numbers for given user (for authentication purpose)
$member_active_policies = array();
// Iterate through policies and write policy number to array
foreach($products as $product){
array_push($member_active_policies, $product->PolicyNumber);
}
// Check if requested polis belongs to user
if(in_array($policy_id, $member_active_policies)){
// Iterate through products to find the requested
foreach($products as $product){
if($product->PolicyNumber == $policy_id){
// Set member variables, all with prefix $member_
// Set product variables, all with prefix $product_
// Fetch information about other members
$all_members = fetch_data(1)->GetProductInfo;
I can see 2 problems here.
Your fetch_data function is not returning anything. I guess it should return $xml_post_string ?
Even if you return $xml_post_string , your code will work if your environment is "dev", when you will supply "prod", it will exit from the script on "exit", therefore your script will not be having fetch_data function.
Related
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);
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.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
I have this snippet of a function inside a larger php class.
I also get some simple data from my database which I have trouble getting into the array when fetching the variables.
$json = array();
$params = array(
'receiver_name' => $var,
'receiver_address1' => 'this works'
);
$ch = curl_init();
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, self::API_ENDPOINT . '/' . 'shipments/imported_shipment');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
$output = json_decode($output, true);
I've tried to assign the variable before the array starts, like this:
$var = $row['field_1'];
But it doesn't work when I try to insert this code. So I then tried:
$var2 = "'$var'"; // but quickly went back.
Since I thought it might have something to do with the quotes. I've tried several other ways of getting the variable to pass properly into the array. But when I don't know exactly what to read up on, I get stuck like this.
$params = array(
'receiver_name' => ".$var.", //this prints ..
'receiver_name' => "'.$var.'", //this prints '..'
Perhaps someone on here can tell me what terminology I should use for searching for more information related to this subject, as I seemingly have alot to read up on?
Update
I think everything should be cut out and simplified nicely now?
<?php
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$p_name = $row['input_name'];
}
echo $p_name; // echo's correctly
class labels {
public function myFunction() {
$json = array();
$params = array(
'token' => $this->_token,
'name' => $p_name,
'hardcoded' => 'works fine'
);
}
}
echo $p_name; // echo's correctly
?>
You're trying to use a variable that is declared outside of the local scope of the class. You need to pass that variable as parameter for the class method.
class labels {
public function myFunction($p_name) {
$json = array();
$params = array(
'token' => $this->_token,
'name' => $p_name,
'hardcoded' => 'works fine'
);
}
}
And when you call your method
$labels = new labels();
$labels->myFunction($p_name);
Then it should work.
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;
}
}
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.