PHP 7.2 - Include file cannot access another include file - php

I am having an issue with an include file accessing another include file (my db connection)
I have a site with the following layout ::
root/conn.php :: db connection file
root/site/file1.php :: regular page
root/site/include/func.inc :: file with functions in it
Each file is listed below with appropriate code...
conn.php ::
<?php
$host = 'localhost';
$db = 'mydb';
$user = 'myuser';
$pass = 'mypass';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset);
?>
file1.php ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
{ code that calls functions in func.php }
func.inc ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
{ various functions }
When I browse to /file1.php, I get the following error ::
PHP Notice: Undefined variable: conn in C:\inetpub\root\site\include\func.inc on line 231
PHP Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\inetpub\root\site\include\func.inc:231
my func.inc file cannot seem to find the conn.php file. I have also tried removing the include function from func.inc. There are other files in the /include folder that can access the conn.php file with the same include function.

The issue relates to something called the variable scope (https://www.php.net/manual/en/language.variables.scope.php)
==> Please read that to get detailed information
The second example describes your problem
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
// to illustrate the issue, the include can be simplified to
// $conn = "something"; // => global scope variable
function myFunc(){
echo $conn; //no output - $conn exists ONLY in the local scope --> not available inside thisfunction
}
Solution 1:
func.inc
<?php
function myFunc($conn){
echo $conn; //outputs $conn
}
file1.php
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
//call function and pass the $conn, it's available here in the global scope
myFunc($conn);
Solution 2
but keep in mind global is considered as bad practice
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
function myFunc(){
global $conn; //$conn is declared global in the local scope of this function
echo $conn; //outputs $conn from conn.php if you call myFunc from anywhere
}

Related

How to fix Fatal error: Cannot redeclare connectdb()

I am new for PHP and MYSQL. I have tried some learnings using xampp. when I try to connect database with the script it shows below error.. this showing on index.php
Fatal error: Cannot redeclare connectdb() (previously declared in
C:\xampp1\htdocs\core.php:18) in C:\xampp1\htdocs\core.php on line 24
I have a search on google and try to fix this. but it's not worked...
core.php line 18th to 24 th codes as follows.
function connectdb()
{
global $dbname, $dbuser, $dbhost, $dbpass;`
$conms = #mysql_connect($dbhost,$dbuser,$dbpass); //connect mysql`
if(!$conms) return false;`
$condb = #mysql_select_db($dbname);`
if(!$condb) return false;`
return true;`
}
config.php codes as follows
$dbname = "aw"; //change to your mysql database name
$dbhost = "localhost"; //database host name
$dbuser = "sam";
$dbpass = "1234";
$max_buds=100; //maximum number of buds
$topic_af = 120; //topic antiflood
$post_af = 45; //post antiflood
$onver = true; //isonline versoion
$timeadjust = (0 * 60 * 60); // 4 hours
putenv("TZ=Africa/Johannesburg");
It's called "include guard":
if(!function_exists('connectdb')) {
function connectdb() {
}
}
I think the issue that connectdb function already loaded.
Try use include_once instead of include.
example:
include_once 'Functions.php';
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, and include_once returns TRUE. As the name suggests, the file will be included just once.
https://www.php.net/manual/en/function.include-once.php
Try replacing your connectdb function with the following code:
if (!function_exists('connectdb')) {
function connectdb()
{
global $dbname, $dbuser, $dbhost, $dbpass;
$conms = #mysql_connect($dbhost,$dbuser,$dbpass); //connect mysql
if (!$conms) return false;
$condb = #mysql_select_db($dbname);
if (!$condb) return false;
return true;
}
}
It will only create the function if it does not exist.

Undefined variable with include or require

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
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);
...
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).

why am i getting a php fatal error for calling the same function twice?

https://plnkr.co/edit/ZNlAyky7TzT4jknpnoDJ?p=preview
here is a link to a plnkr with all my code written so far. I keep getting an
Fatal error: Cannot redeclare connect_to_db() (previously declared in
/var/www/html/News/config/dbconnect.php:5) in
/var/www/html/News/config/dbconnect.php on line 5
the plunkr wont have the folder structure because i could not figure out how to add folders however here is my code for dbconnect.php
<?php
$pdo = null;
function connect_to_db()
{
$dbengine = 'mysql';
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = 'password';
$dbname = 'news';
try{
$pdo = new PDO("".$dbengine.":host=$dbhost; dbname=$dbname", $dbuser,$dbpassword);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $pdo;
}
catch (PDOException $e){
$e->getMessage();
}
}
line 5 does not have a call to db connect so i dont know what is going on
You are using
require __DIR__.'/dbconnect.php'
In both your Index.php and your functions.php, while requiring your functions.php in Index.php.
Therefore connect_to_db() is being defined twice. Use require_once instead to prevent this:
require_once __DIR__.'/dbconnect.php'
http://php.net/manual/en/function.require-once.php

Can't call the function in PHP

I am having a problem with my index.php. Whenever I go to http://localhost/blog/admin/index.php I get an error:
Fatal error: Call to undefined function Blog\DB\connect() in C:\xampp\htdocs\blog\blog.php on line 6.
In the admin folder all I am requiring is my blog.php which is working fine in other files when I required them. I am stuck with this and can not understand why this is happening.
index.php in admin folder
My admin/index.php:
<?php
require '../blog.php';
My blog.php. It is requiring the db.php in which we have called the connect function.
<?php
require 'db.php';
$conn = \App\DB\connect($config);
if(!$conn)
die('Could not connect to db');
My db.php. It is just trying to establish a connection:
<?php namespace App\DB;
require 'config.php';
function connect($config)
{
try
{
$conn = new \PDO("mysql:host=localhost;dbname=blogs",
$config['DB_USERNAME'],
$config['DB_PASSWORD']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(PDOException $e)
{
return false;
}
}

problem with "real_escape_string"

i am having some troubles my the "real_escape_string" and i need some help
login.php
<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
$sql = $mysqli->real_escape_string($sql);
return $sql;
}
?>
local.php
<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
the error is
Undefined variable: mysqli
i've tried some things ( like moving the content of the local.php inside the login.php ) but nothing works
You can't access $mysqli inside your function.
If you want to, add global $mysqli; in your function to make it accessible. Alternatively, you could pass the $mysqli as a parameter.
Why not just use the function call directly.
My suggestion, just create a simpler (and easier to read function) called "esc" and use that anytime you need to escape anything sql related.
function esc($string, $mysqli = false) {
if (!$mysqli) global $mysqli;
return mysqli_real_escape_string($mysqli,$string);
}
And then just use this by doing the following:
$sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function
OR
$sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call

Categories