Including the same file over many pages - php

I am writing a simple app for a school project that is not too big. I have the following files:
signup.php
login.php
view_photos.php
that have the following in common: they connect to a database and execute queries. In every file I find myself repeating the your typical database connection code snippet:
$mysql = new mysqli( 'localhost', 'root', '', 'imagebox');
if( $mysql->connect_errno ) {
echo "Connection failure: " . $mysqli->connect_error;
exit();
}
Is there a way to do this once in the index.php file and pass the connection to other pages without having to repeat the same line in every page that requires a database connection?

Use PHP's include feature, though I recommend using require instead (as require aborts script execution if the file doesn't exist).
Documentation is here: http://php.net/manual/en/function.require.php
Use require_once to prevent duplicate inclusion if you have cycles in your include-dependency tree.

Place your common code in a separate file. Then use
include('myfile.php');
where you want the common code to appear

Related

SFTP Opendir failing when called via Function

I have a bunch of php pages that are running on a schedule that pull data from different SFTP sources, to try and minimise this as a temporary fix I am turning them into functions and having one page that calls each of them
However, when converting these to functions the pages are giving me error 500, through process of elimination I have found that it is when it using the opendir function via sftp
I have called the function page by itself with a reference to call itself as a test and it connects fine, but when called from another page it errors out.
The variables being used to open the directory via sftp are generated on the 'required' page so it's not losing anything via session variables
If I point it to an incorrect directory it is being caught by the error handling in place, but when it 'successfully' connects I get the error 500
Page1.php
<?php
require 'Page2.php';
sftpFunc();
?>
Page2.php
<?php
Function sftpFunc()
{
/* variable declarations and value assignments go here*/
if (!$FTP_CONN = ssh2_connect($FTP_HOST, $FTP_PORT))
die('Unable to connect');
if (!ssh2_auth_password($FTP_CONN, $FTP_USER, $FTP_PASS))
die('Unable to authenticate.');
if (!$FTP_STRE = ssh2_sftp($FTP_CONN))
die('Unable to create a stream.');
if (!$FTP_OPEN = opendir("ssh2.sftp://{$FTP_STRE}{$FTP_DIRI}"))
die('Could not open the directory');
}
?>
Updated the php version on the site from 7.2.34 to 7.3.11 and it seems to have done the trick, hadn't seen any version specific issues with opendir() before and it seemed to only happen when using it through a function on a different page.
Not sure on the why, but at least this worked.

Connecting To Separate 'Database Connect File'

I have two php files. One PHP file is my details to connect to a mysql database
The second PHP file performs a SELECT function on the database
My problem is that the second PHP file does not seem to be actioning the first PHP file.
I have just moved to using PDO commands instead of MYSQL commands. When I used a Require('connect_db'); function everything worked. Since I've moved to PDO commands it does not work
I am getting the error
Call to a member function execute () on a non object in................
My code is as below:-
The connect_db file is (I have not shown the strings for password, user , database:-
try
{
$mysql_link= new PDO("mysql:host=$servername;dbname=dbname;charset=utf8",$username,$password);
$mysql_link->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$mysql_link->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected Success";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
My SELECT file is as follows:-
Require('connect_db.php');
$stmt=$mysql_link->prepare("SELECT cif_train_uid,cif_stp_indicator FROM schedule WHERE cif_train_uid=:cif_train_uid");
$stmt->execute(array(':cif_train_uid'=>$cif_train_uid));
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['cif_train_uid'];
echo $row['cif_stp_indicator'];
}
$mysql_link=null;
If I merge all the code into one file it works fine. (Both scripts are in the same folder). So its just the Require () function that does not seem to be working but I cannot see why. Any help gratefully received
The only reason I can see that a included / required file results in a problem that does not occur when you put the code in the including file, is when there are no opening php tags in the included file:
<?php
^^^^^ this...
try
{
$mysql_link= new PDO("mysql:host=$servername;dbname=dbname;charset=utf8",$username,$password);
...

is mysql_connect in header bad practice?

I have a normal website. It uses PHP to call a MySQL table. To save on typing it out all the time, I include() a connect.php file which connects to the database for me on every page. The website keeps getting a "mysql too many connections" error. Is it a bad idea to connect at the start of a page like this?
Should I create a new connection each time a PHP script needs it, then close that connection with mysql_close after that script is done? I had avoided doing as it would add repeated lines of code to the website but I'm wondering if that's what's causing the issue?
So at the moment my code is similar to this:
<?php
include("connect.php"); //connects to database using mysql_connect() function
...
PHP script that calls mysql
...
another PHP script that calls mysql
?>
Should I change it to something like this?
<?php
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
PHP code that calls mysql
mysql_close();
...
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
more PHP code that calls mysql
mysql_close();
?>
You should avoid making new connections to your database, as long as possible.
Making connection to database is a slow and expensive process. Having an opened connection consume few resources.
By the way, stop using mysql_* functions. Use mysqli_* or PDO.
Should I create a new connection each time a PHP script needs it [...] ?
Yes, that makes most sense, especially if not every page needs a mysql connection.
In PHP this works by setting up the database credentials in the php.ini file and you can just call mysql_select_db and it will automatically connect to the configured database if no connection exists so far.
If you write new code, encapsulate the database connection in an object of it's own so that you can more fine-grained control when to connect to the database.
Modern frameworks like for example Silex allow you to lazy load such central components (Services), so you have configured them and can make use of them when you need them but you don't need to worry about the resources (like the connection limit in your example).
[...] close that connection with mysql_close after that script is done?
You don't need that normally because PHP does this for you.
I do not think there is anything really wrong with this style of coding. It all depends on what kind of app you are writing. Just make sure you check your scripts well and get ride of any errors, you should be fine.
This is what i usually do
<?php session_start(); include "inc/config.php";
//require_once('chartz/lib/idiorm.php');
if ($_SESSION["login1"]== "Superadmin" or $_SESSION["login1"]== "User" or $_SESSION["login1"]=="Administrator")
{
$snames = $_SESSION["name1"];
$id = $_SESSION["id1"];
$stype = $_SESSION["login1"];
$stokperm = $_SESSION['stokperm'];
$navtype = $_GET['nav'];
include("inc/ps_pagination.php");
}
else
{
header ("location: ../../../index.php");
}
?>
Am not saying its the very best way out there, we are all still learnig...
I also thing you should take the advice of blue112 very seriously. Most of my apps are writing in the old fashion way, but Use mysqli_* or PDO is the way to go.

PHP Require() does not execute required file in the scope of parent script

I'm trying to offload the process of connecting to a database to a DBConfig.php file, as suggested pretty much everywhere, because I'll need to reuse the code in several files.
The suggestion is always framed as (edited to reflect my actual code):
-------DBConfig.php-------
<?php
$link = mysql_connect('localhost','user','pass');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db_name : ' . mysql_error());
}
?>
-------Parent.php-------
<!DOCTYPE html>
<?php
require_once 'DBConfig.php';
$something = mysql_query("SELECT * FROM `table` LIMIT 0, 30 ");
// This query works fine if the mysql_connect() and
// mysql_select_db() stuff is in this script in place
// of the require_once.
$listofthings = array();
while($temp = mysql_fetch_array($something)){
$listofthings[] = $temp;
}
// Do other things too
?>
But when I try to do mysql_fetch_array($something), it fails with the warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.
Keeping in mind that everything works beautifully if I simply drop the contents of DBConfig.php into the parent script instead of require 'DBConfig.php';...
And also noting that print(require 'DBConfig.php'); //- 1 (PHP is returning a 1 to indicate that it is successfully locating and including the file. See example 5)...
What is going on, and how do I fix it? I am using the default configuration for WAMPServer (Apache 2.4.2, PHP 5.4.3), running on Windows 7 x64.
If this
require 'DBConfig.php';
is literally what you are doing, there is absolutely no way the script can be executed in some other scope. If you were using a http:// URL, it would be the cause but not if you use a relative path like you do.
You are not doing any error checking after connecting to your database, nor after the mysql_query() call, so it's more likely it's simply the query breaking. Add proper error checking to your queries and you will know more.
Another possibility is if you call DBConfig.php inside a function. Functions will mess with your include's scope. But there's none in your example, so I'm assuming that is not the issue.
Probably your query has some mistake. Try
mysql_query($query) or die( mysql_error() );
mysql_query() returns FALSE (boolean) on error.
If this is exact code that You are using, please change the:
require 'DBConfig.php';
to:
require('DBConfig.php');
Need to know what are you giving in variable $pretend_this_var_is_a_querystring.
This error is usually generated if the query fails. We need to know what string you are passing in mysql_query() function.
Please do check your query string.
Also in your DBConfig.php. It should be
$db_selected = mysql_select_db('db_name', $link);
I think that you include the wrong file. (with the same name, but in different location).
If the DBConfig.php file that you want is in the same directory of your Parent.php try to do
require_once dirname(__FILE__).'/DBConfig.php';
When you include your DBConfig.php file, the effect MUST be the same (in your case) if you copy and paste the code of DBConfig in your parent.php file.
If this not happens, it's because:
The file that you include is not that you think. (some set_include_path in other folder)
The content of the file that you include is not that you think.
There's no other way.

Using same MySQL Connection in different PHP pages

I am creating a simple Web Application in PHP for my college project. I am using the MySQL database.
I connect to the database in login.php. After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
In main.php I write $conn = $_SESSION["conn"]. But the connection in $conn does not work.
I thought that as the login.php script ends, the connection gets closed. So I tried using mysql_pconnect instead of mysql_connect but that too does not work.
I know I can reconnect to the database in every PHP file. But I don't want to do this. I want to use the same connection in all PHP files.
Instead of saving the DB connection in a session you should make the connection calls in a separate file such as db.php and then require it from each of your scripts. For example, place your connection in db.php:
mysql_connect('...', '...', '...');
mysql_select_db('...');
and then bring it in in login.php:
require('db.php');
$res = mysql_query('...');
You can then do the same for each PHP file that needs access to the DB and you'll only ever have to change your DB access credentials in one file.
After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
You'll probably want to read up on PHP sessions. You can't store resources (database connections, file handles, etc) in a session, because they can not be serialized and stored.
Keep in mind that each and every visit to a PHP script invokes a new instance of the PHP interpreter (via CGI, via FastCGI, or via a built-in module), and invokes a new instance of the script. Nothing is shared between script calls, because the entire environment goes away when the script exits.
The other answers are correct -- you'll need to connect to the database on every script call. Place the connection in a common include file for convenience.
The second request may not be served by the same web server process as the first, which means that you will have a completely separate set of database resources. You'll need to connect again in this new process in order to run queries.
What I normally have is a Connection class that pages will require in order to establish a connection. Something along the lines of:
class Connection {
public $dbConnection = null;
public $isConnectionActive = false;
private $dbServer = null;
private $dbCatalog = null;
private $dbUser = null;
private $dbPassword = null;
}
This class handles opening and closing of the connection on any pages.
It sounds that you want to make your php connections persistants , in that way and if it is so , then you have to create a PDO Object with the required parameters to create a new PHP PDO Object that will attempt to connect to mysql , and in the object instanciation , try to pass persistancy option value to true , you may have available in every php scripts the same PDO Connection Objetc but you will end up to face issues with that way ... but it is not reconmmanded as PHP Programming Best Pratices ... the best way to do so is to include a connection file for every script in your project. Read PHP Documentation for Persistant Connections in order to learn more about Issues found for these Connection Objets especially for recent php versions. PHP Announced that Persistant Connections are on the way to be dropped from futur version as it may increase server workload with persistant ressources ... Sorry if it is too late

Categories