How to pass database connection instance between PHP files without redeclaring it - php

I have created a database connection instance in PHP like:
$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");
I need to pass this database connection to other PHP files, since I have an HTML form that first inserts data into a database and then it goes to a PHP page that retrieves data.
I know that I must not instantiate the database connection each time but I do not know how to do it, because I am not so familiar with OO PHP.

You can just name a file connection.php and store your line for connection to database.
Then you can include your file like this :
require_once('connection.php');
This will be the content of connection.php :
$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");
And then this way, your file will never load twice.

If I understand you correctly, I think you misunderstand what you've read.
In PHP how most systems (phpBB, WordPress, etc) do it is there is a base include file that is included at the start of each PHP page. In phpBB it is called "Common.php" if I remember correctly.
Common.php goes through and does a few things:
It reads the database configuration files and connects via the most acceptable database connection type (mysql_connect, or mysqli_connect, depending, or another connection if you aren't using MySQL).
It then unsets the database password variable (so that someone, on an off chance, couldn't figure it out via SQL Injection)
includes other files necessary for the system to function - certain user-made functions or class definitions.
This is done via one of 4 functions:
include('common.php') will include the contents of the file at the point it is written in the file. E.G.
<?php
do_function();
include('common.php');
do_other_function();
?>
Will run do_function(), then run any script in the common.php file, which could theoretically hold the definition for do_other_function(), and then run do_other_function();
include_once('common.php') makes sure that a file is run through the process only once. This is good for things like class definitions as it ensures a class is not accidentally re-defined. E.G.
<?php
include_once('database_class.php');
//Code here code here
...
//Oh crap, did I include that database class? I can't remember. I think so...maybe not
include_once('database_class.php');
?>
Will only include the database class def one time. Where as the same example above with include('database_class.php'); instead of include_once would throw an error akin to the class 'database' is already defined
Note, include and include_once will only throw warnings if a file does not exist, and if you have error reporting set to only show fatal errors, you won't notice when something isn't included except for perhaps a "constant/function/class 'something' not defined" and you'll scratch your head for perhaps a long time. So if you try to include the file 'cmmon.php' when you meant 'common.php', you may or may not see an error.
then there is the require and require_once functions, they do effectively the same thing as include and include_once, but unlike the latter two the script will stop running if it cannot include the file and throw an error, like "could not include file 'something.php' on line # [line] in file [file path]"
Use require for scripts that are absolutely necessary - function/class/constants that your scripts will need in order run properly.
Use include for things that are voluntary, the first thought that came to mind would be plugins - things that don't necessarily have to be there in order for your system to work as intended.

If $mysqli is global, then all php files can see it by peeking the $GLOBALS array, assuming the php is included.
For example:
$mysqli = mysqli_connect(..); // in global space
another php file:
$GLOBALS["mysqli"]; // use that
inside a php function you could also do:
global $mysqli; // use that

Related

how to include a php file that already includes another file?

I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar
You can use include-once
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');
You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)

How to load only a specific variable from another php file?

In a maintenance script for a web server, I need to get the database settings for each website/application on that server. As most of the websites are based on Drupal, the main settings file is settings.php, within that file various variables (such as $database) are defined, but sometime it also contains ini_set() statements for that specific site.
The script could include the settings.php to obtain the database setting but then the script will throw errors such as
Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in include() (line 123 of /path/to/website/sites/default/settings.php).
Is there a way to only load (specific) variables from an included php file?
Of course, I mean something smooth. I know, I could load the file into a string, use regex to extract the database variable and eval() that, but I'd rather think there is a better way.
Instead of just including the settings.php (due to errors with ini_set() commands inside the included file I had to read the file into a string, get the desired part and eval() that.
In the example below, I am searching for the database settings inside a standard Drupal settings.php
#include $settings_path; // critical due to ini_set() commands.
$settings = file_get_contents($settings_path); // load file into string
$settings = preg_replace("#/\*.*?\*/#si", '', $settings); // get rid of comments to avoid confusion with preg_match
preg_match('#\$databases.*?;#si', $settings, $dbraw); // get the desired part of the string
eval("\$databases = " . $dbraw[0]); // eval() to create the variable

Open file from a php document, and close it from another?

I am trying to do the following:
Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.
I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.
Thanks in advance, I am quite new to php, and am trying to learn.
When you include a file, you are running all code inside it. The functions and classes will not be evaluated but will be defined for future use. If you open your file as this example:
util.php
<?php
$file_hand = fopen('/tmp/file.txt','r');
You will have a handle if the operation is completed. However, the variable $file_hand is global. If you need to use a function to close it, you will need the following code to do it:
other.php
function close_file(){
global $file_hand;
fclose($file_hand)
}
or you can pass the handle as parameter like:
function close_file($file_hand){
fclose($file_hand)
}
Doesn't matter how you will close the file. You have to make sure the variable you are using is the same created in utils.php. If you close like this:
function close_file(){
fclose($file_hand)
}
The variable you've created in until.php file is different of this one.

Accessing external functions from php class

Hello let's say that I have the following structure in my application .
<?
include('includes/functions.php');
include('includes/classes/login.class.php');
$login = new login();
?>
What I want is inside the login class to call a function that is defined in functions.php . But I can't get it to work.
PHP does not care in which file you have storred what function or class definition. Only namespaces, order or processing and of course where inside classes or functions you have what definitions matter.
What you are doing is correct.
Including php-code just adds the content of that file in the file where you execute the include. If this is not working there is something else wrong with your code.
You should close this question and make a new one. Include the content of the files you are including and the errors that are displayed.

Where to put the database sensitive information [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to secure database passwords in PHP?
Recently I was given a website project which was supposed to be done in PHP but I don't have much experience in PHP. Anyway, it is up and running but there is a big room to improve. The one thing that I am not feeling well is the way I am dealing with database: I put the database connection information in a separate db.php file and include it where needed. But I remember seeing PHP source files returned by the server many a time.
So now my question is: what is a better or the best way / place to put database sensitive data?
By the way, how NOT to let PHP show error messages on web pages when things are gone wrong? A custom error page or settings somewhere in php.ini? Thanks!
Note: I am using PHP in it's old flavor not object-oriented way. But I am open to object-oriented or MVC way if there are better approaches that way to prepare for future projects
I don't know if this is what you are looking for:
You can put your sensitive data in your db.php, but outside the web root directory (public_html or www).
For example, you could have a directory called config which is a sibling of your web root directory, and store your db.php file there.
You can include your db.php file like this:
require_once('../config/db.php');
I hope this helps.
Its fine to put it in a db.php file, just use require_once() just after the opening <?php tag of each document.
If basedir restriction is not in effect, move db.php file outside of your web/ftp root that way its definitely not accessible via http/ftp. Make sure permissions are set properly on this file though.
Since you aren't using OOP or an MVC structure for your code this is the best route to go.
I would personally create a file called db.php and place this above the public_html folder on your server
for example
<?php
error_reporting(0);
$link = FALSE;
$link = mysql_connect('hostname', 'username', 'password');
if ( ! $link)
{
die("Couldn't connect to mysql server!");
} else {
mysql_select_db('databasename');
}
?>
This turns off error reporting at the same time as connecting to your database, from your index.php you would include the file like so:
<?php require('../db.php'); ?>

Categories