I have two files, one config.php and source.php in a subdirectory. In the config file I have something that looks like this
<?php
//app settings
$GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; //ex:
//demo mode
$GLOBALS['demo_mode'] = 0; //possible values: 0 or 1
$GLOBALS['db_table']['sms'] = 'sms_numbers';
$GLOBALS['db_table']['sms_history'] = 'sms_history';
?>
In the config.php file, I have this string $GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; for the base URL and I'd like to make it so that the base URL is automatically detected. I'd like to use something similar to this <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>. I'm using these files under different directories and that's why I'd like to combine them in order to make it automatic without me having to update the base URL manually every time I create a new subdirectory.
Also, inside config.php I have:
//Admin access
$GLOBALS['admin_username'] = 'admin';
$GLOBALS['admin_password'] = 'password';
These values are not in a database but a local file named source.php and I'd like to be able to update the values "admin" and "password" from this source.php file.
Inside the source.php file I guess I'd have to have something thta'd look like this: $username = 'admin';
I'm really sorry but I'm new and would like to learn this stuff. I appreciate any help I can get.
Thank you
Use global constants in config.php
define('APP_URL', 'http://www.website.com/subdirectory');
Then anywhere in the code you can do:
$path = APP_URL . "/path/to/file"
I dont recommend storing admin_username and admin_password as global variables or constants, instead you can create a class in your config.php that contains the values.
Config Example:
config.php
define('APP_URL','http://www.website.com/subdirectory');
define('DEMO_MODE',0); //possible values: 0 or 1
.....
class DB{
var $conn;
public function __construct()
{
$user = "admin";
$pass = "pass";
$host = "127.0.0.1";
$database = "database_name";
$this->conn = mysqli_connect($host, $user, $pass, $database);
}
}
Then in your index.php file you do:
require_once("config.php")
$db = new DB;
$conn = $db->conn();
....
Related
I'm creating a CMS that provides dynamic database creation at the initial project setup stage.
I have defined the database configuration details as constants in config.php file:
//Database Name
define('DEFAULT_DB_NAME', 'cms');
//User Name
define('DEFAULT_USER_NAME', 'root');
//Password
define('DEFAULT_PASSWORD', '');
//Host Name
define('DEFAULT_HOST_NAME', 'localhost');
I included the config.php file in my database connection file (db.class.php):
<?php
include_once '../../config/config.php';
class Db{
protected $conn;
protected $host = DEFAULT_HOST_NAME;
protected $username = DEFAULT_USER_NAME;
protected $password = DEFAULT_PASSWORD;
protected $dbname = DEFAULT_DB_NAME;
public function __construct(){
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if($this->conn->connect_error){
die("<h3>Connection Failed!!! Error: " . $this->conn->connect_error . "</h3>");
}
}
}
I also have created a dynamic Style sheet (admintheme.php) that modifies the admin panel based on user preference:
<?php
header("Content-type: text/css;");
include_once '../../model/admintheme.class.php';
$theme = new Admintheme();
$result = $theme->ReadAdminTheme();
if($result == '' || $result == '0'){
$sidebarBg = "#111";
$sidebarPosition = "left";
$sidebarunset = "left";
$sidebarright = "unset";
}
else{
$row = $result->fetch_assoc();
$sidebarBg = $row['sidebarbg'];
$sidebarPosition = $row['sidebar_position'];
if($sidebarPosition == "left"){
$sidebarunset = "right";
}
else{
$sidebarunset = "left";
}
}
?>
/*-- ------------------------xx----------------------- */
/***** Content Section Starts *****/
.content{
margin-<?= $sidebarPosition; ?>: auto;
}
/***** Content Section Ends *****/
/**** Side Bar Section Starts *****/
.sidebar-nav{
background-color: <?= $sidebarBg; ?>;
<?= $sidebarPosition; ?>: 0px;
}
The issue is that when I use static data in "db.class.php" file (ex. directly write "localhost" in place of the constant and so on..) then "admintheme.php" works fine and displays the desired output, but when I use constants in place of the static data then all other functionalities of the project work fine and retrieve data from the database except "admintheme.php".
The "admintheme.php" also works fine when the constants are defined inside the "db.class.php" or if the "config.php" file is in the same directory as of the "db.class.php" but while including the the "config.php" file from other directory, all other data is retrieved except "admintheme.php".
**No direct error is received but in the browser's console, it states (include_once(../../config/config.php): failed to open stream: No such file or directory...)
**Included path is correct in both "db.class.php" and "admintheme.php".
Any help is greatly appreciated.
Adding "DIR" magic constant solved the issue.
Im trying to get data from my database and echo it with a variable, but I have a problem with that. When I try to get my variables from different files it shows me this error:
Undefined variable: con in.
Here some codes:
Code from functions.php:
include "authentication.php";
function GetData() {
$id = session_id();
$result3 = mysqli_query($con,"SELECT * FROM accounts where id='$id'");
while($row3 = mysqli_fetch_array($result3));
{
$email=$row3['email'];
$fullname=$row3['fullname'];
$usualname=$row3['usualname'];
$lastname=$row3['lastname'];
}
}
Code from authentication.php:
$DATABASE_HOST = 'localhost';
$DATABASE_USER = '***';
$DATABASE_PASS = '***';
$DATABASE_NAME = '***';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
This also happens when I try to get variables from other files..
Here you get some screenshots of the error from different files and different variables:
Both files are in the same directory called PHPscripts:
This looks like a problem of scoping.
Remember that in PHP, variables in the global scope cannot be accessed from a function. You must explicitly do something like global $con; inside the function GetData() before you try to access $con.
From a system design point of view this isn't the best approach. It will make it hard to keep track of your variables. You won't know who (which part of your script) is accessing that global and you won't know how it is being modified or in what order. This can lead to some bugs that are very difficult to identify.
require_once dirname(__FILE__) . auth.php;
Require_once or require with Unix full path works like a charm. Replace include stroke in your code.
I am working on a school-project (writing a website) and I ran into the problem of providing the password for the connection to our database. Because of our Open-Source license we have to publish the sourcecode but that would mean that everyone could connect to the database and see tha data.
Currently our connection (a php file) looks like this:
$host="************";
$password="************";
$this->conn = new mysqli($host, $user, $password, $dbname).mysqli_connect_error());
Now my question is: how can i provide the password to connect to the database without needing to write $password=... ?
Ok, here's the one with the ini file:
xxx.php
<?php
$db_params = parse_ini_file( dirname(__FILE__).'/db_params.ini', false );
// .....
$this->conn = new mysqli($db_params['host'], $db_params['user'], $db_params['password'], $db_params['dbname'], $db_params['port'], $db_params['socket']).mysqli_connect_error());
// ...
?>
db_params.ini
host=mysql.example.com
port=3306
socket=
user=testuser
password=myPasswort
dbname=myDatabase
Use a single file to contain your configuration variables and exclude this file when sharing your code.
For example:
require_once('config.php');
$this->conn = new mysqli($config['db']['host'], $config['db']['user'], $config['db']['pass'], $config['db']['dbname']);
The config.php file would include:
$config['db']['username'] = 'user';
$config['db']['password'] = 'pass';
...
You could/should expand this to include the host, port, database name etc.
I will be straight to the point with this. Can't seem to find it anywhere on the internet. Maybe it is not even possible, i dont know. I do really like to use the method "divide and rule", created it myself. Splitting as much files as possible for easy management (small files and such).
But here is my problem:
I have 5 files:
index.php
inc/config.php
inc/Database.class.php
inc/sidebar.php
inc/forms.php
Okay, what i have done is this:
in my config.php file i included the Database.class.php file and created an object.
include 'Database.class.php';
$user = "root";
$pass = "";
$host = "localhost";
$database = "blah blah";
$db = new Database($user, $pass, $host, $database);
$db->connect();
So i included this config.php and sidebar.php in my index.php file.
(shortened the code, but it functions the same)
include 'inc/config.php';
include 'inc/sidebar.php';
In my sidebar i have a form, for users to login.
in sidebar.php i just include forms.php, this is the forms.php:
(I used print_r to debug my file, to see if anything returns and i left out the method loginFormShow because it is very long and not relevant)
function loginFormProcess($user, $pass)
{
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
if (!isset($_POST['submit'])) {
loginFormShow();
} else {
if ($_POST['user'] == "")
{
loginFormShow(1);
}
else if ($_POST['pass'] == "")
{
loginFormShow(2);
}
else
{
$user = $_POST['user'];
$pass = $_POST['pass'];
loginFormProcess($user, $pass);
}
}
And thus, what the problem is. When i try to call the function loginFormProcess, it cant use the object $db.
Can i use 1 object for this? Because on the index page i am going to require some other data from the database. Do i need to create an object for the index page and one for the login form?
Is there any other solution?
If i am not clear, i would love to give some more explanation.
Cheers,
Clemenz
The best solution would be to pass the database object to the function's arguments as follows:
function loginFormProcess($user, $pass, Database $db) {
And call it with an appropriate Database object. This is what know as dependency-injection.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
For reference: http://php.net/manual/en/language.variables.scope.php
You need to declare $db as global.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
See: http://www.php.net/manual/en/language.variables.scope.php
The variable $db is created as a global variable in your config.php file. This is invisible from inside the loginFormProcess function. A shotcut solution you can use is declaring your intention of using a global variable by adding the statement global $db; as the first statement inside your function
Everything was working fine in my little project, until I decided to clean up a little bit and moved database-related php-files to their own folder. Then things went strange.
I am trying to use two functions here:
function getEntries () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error);
echo $dbHost; // prints host
return $result;
}
function getBiggestMonth () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
echo $dbHost; // prints nothing! why?
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error); // this line does not run, of course.
return $result;
}
I use another function in a different file (and folder) to call these functions, that starts like this:
function listTasks() {
require_once("db/mysqliFunctions.php");
// Get entries using mysqli.
$tasks = getEntries();
echo "<pre>";
var_dump($tasks);
echo "</pre>"; // program works fine this far.
$bm = getBiggestMonth(); // program breaks somehow during this function call.
My variables are in a php-file like so:
<?php
$dbHost = "host";
$dbUname = "username";
$dbPwd = "password";
$dbName = "databasename";
?>
If I switch the funtion's call order, then getBiggestMonth() runs fine and the other one won't. Also, all of this worked fine when all the files were located in the same folder (the functions were then static functions inside a class, but that shouldn't be an issue, the same problem persists here), so I dont understand how possible variable scope can be different here, and require_once should take care of other things. Help?
This is because you are using require_once. It will only include the configuration once. You can change it to use require so that it will work as you expect.
The require_once() statement is identical to require() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
You are using require_once to pull in a file into the scope of the getEntries() function. PHP keeps a record of the files that have been required in so when you then call require_once in getBiggestMonth() it knows it has already been included in getEntries(). Because it has already been included it does not require the file in again so you don't get your variables in your getBiggestMonth() scope.
require_once does not have anything to do with variables it just monitors the files that have been included into the current PHP process.
The echo statement after the return in getEntries() wont obviously work as the function exits after the return.