1

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;
Cœur
  • 37,241
  • 25
  • 195
  • 267
Maurice
  • 1,082
  • 1
  • 20
  • 43
  • Please post full code, the [..] maybe overwrite the `$username` variable. Btw: Try to not depend on globals wherever you can. Use instead, for example: classes with static variables – Brain Foo Long Sep 06 '16 at 08:40
  • Stab in the dark: the place where you `require_once('config.php')` *is not global*, e.g. you're requiring that file within a function. Just try not to use globals at all, or at least make them constants. – deceze Sep 06 '16 at 08:46
  • There must be something happening between your require and the function call. Where you put the [...]. Because if I run your code everything is fine, echo returns dev. – Philipp Palmtag Sep 06 '16 at 08:46
  • There are like 130 lines of code in between the [..] part that process various calls to external API's which use the same variables `$username` and it works there. I'll add a minified version omitted redundant code (basically additional credentials and extended comments) I've checked if the variable is overwritten and as far as i can see it isn't. – Maurice Sep 06 '16 at 09:07
  • Any feedback on my stab into the dark and/or the linked duplicate…? – deceze Sep 06 '16 at 09:20
  • Sorry, missed it ;) But no, i don't require the file in a function. It's on the first line op page.php. And i've read before about not using globals, but how am i supposed to achieve this result without globals? Passing the values as arguments? – Maurice Sep 06 '16 at 09:22
  • Yes, pass the values as arguments. Alternatively, again, use constants, which have no scope. Alternatively alternatively, explicitly declare `$username` to be `global` in `config.php` too so you're sure it's actually created in the global scope (but again: globals, yuck!). – deceze Sep 06 '16 at 09:32
  • Interesting thought, didn't think of constants yet. Only thing is they can't store arrays/objects (right?) as for the Soap Call, but i can work around that. Thanks for the suggestion! – Maurice Sep 06 '16 at 09:52

1 Answers1

0

I can see 2 problems here.

  1. Your fetch_data function is not returning anything. I guess it should return $xml_post_string ?

  2. 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.

Arfeen
  • 2,553
  • 5
  • 29
  • 48
  • Sorry, stupid typo in this post. That `exit;` is supposed to be a `break;` (as it is in my working code). Also my code is just an example where i try to access the variable. I added the full code – Maurice Sep 06 '16 at 08:39