0

I'm trying to include a variable from a different file into my main php file but I keep getting Undefined variable.

accounts.php

# GUEST CREDENTIALS
$host = 'localhost';
$guestAccount = 'oncofinder';
$guestPassword = 'xxxxxx';
$database = 'oncofinder';

#LOGGER CREDENTIALS
$loggerAccount = 'logger';
$loggerPassword = 'xxxxx';

connections.php

function guestConnection() {



    try {
        require 'accounts.php';


        $conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
    }   catch (PDOException $e) {
        echo "Error : " . $e->getMessage() . "<br/>";
        die();
    }

    $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}

I tried to put my require in and out of my function but nothing works. I really thought this was straightfoward but I can't find an obvious solution.

Is there any thing I'm doing wrong? Isn't this the procedure?

Regards

molecoder
  • 423
  • 1
  • 7
  • 24
vftw
  • 1,547
  • 3
  • 22
  • 51

2 Answers2

3

I think you have variables defined in global scope but you try to use it in local scope.

To confirm naming scope issue try to:

require 'accounts.php';
function guestConnection() {
    global $host, $database, $guestAccount, $guestPassword;
    try {
       $conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
    ...

This should work if your guestConnection() is in global scope not under any namespace or class.

or do move require out of try to get errors if any (file does not exist?):

function guestConnection() {
    require('accounts.php');
    try {
       $conn = new PDO("pgsql:host=$host;dbname=$database", $guestAccount, $guestPassword);
    ...
Alex
  • 16,739
  • 1
  • 28
  • 51
  • this is a good point - are there any security risk implications with using global keyword with db vars? – treyBake Oct 17 '18 at 14:57
1

I had a similar problem on my CentOS server. Try using the full absolute path (server conf might not be configured to allow calling of same-level files this way):

require_once $_SERVER['DOCUMENT_ROOT']. '/path/to/accounts.php';

Note:

you can use require and it should still work. I just think require_once is safer (in terms of not accidentally duping code).

treyBake
  • 6,440
  • 6
  • 26
  • 57