Search code examples
phpmysqlvariablesscoperequire-once

Require_once across different files, global scope


I've been learning PHP for a couple of days now and I came across a strange issue for me. I have two files :

login.php that stores database access data (user, pw, host, db)
security.php that have functions that manipulate strings/queries to prevent sql/xss injections and also stores salt prefix and suffix for password hashing.

Then I have my index.php, register.php and signin.php. My problem is : when I put require_once '../login.php'; in register.php I can normally call a variable or function like $var. On the other hand, exactly the same pattern in signin.php is not working, PHP tells that that variables are not declared. I tried to do : global $var, and it was working but I have feeling that it's completely insecure.

1) What is the proper way to solve this problem?
2) Is it connected with app architecture?
3) Should all functions (and etc.) that use db connection be written in a single file?


Solution

  • Step 1 - Create a php file , write all database connection into it(example- db.php)
    Step 2 - Include this php (db.php) wherever you have a database related operation.

    require 'db.php';  //add your database php file here..
    
    


    This will be easy to organize, and minimizes errors when you migrate your app from one server to another in php there is require and include. require is good since it will stop executing code if file is not available.

    Also this is easy to organize and minimizes the errors caused when migrating from one server to another