Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict access to mysql connection from other classes?

Tags:

php

mysql

Sup! We have core class with mysql connection, than we include plugin and we need that plugin cant access to our DB without core class methods.

index.php

<?php
    class Core
    {
        function connect()
        {
            $db = @mysql_connect($host, $user, $pass);
            @mysql_select_db($base, $db);
        }

        function query($sql)
        {
            return mysql_query($sql);
        }
    }

    global $c;
    $c = new Core();

    include('plugin.php');
    $p = new Plugin();
    echo $p->not_work_connection();
    echo $p->work_connection();
?>

plugin.php

<?php
    class Plugin
    {
        function not_work_connection()
        {
            $sql = 'SELECT * FROM `net_country` LIMIT 0 , 1';
            $result = mysql_query($sql); 
            while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
            {
                return print_r($row, 1);
            }
        }

        function work_connection()
        {
        global $c;
            $result =$c->query('SELECT * FROM `net_country` LIMIT 0 , 1'); 
            while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
            {
                return print_r($row, 1); 
            }
        }
    }
?>

I need restrict access from included scripts, but thay can use core methods to make queries. How i can make it?

like image 589
Barif Avatar asked Dec 28 '22 07:12

Barif


2 Answers

mysql_query without the second param uses the last link used by mysql_connect, so you could create a dummy connection after the real one :

<?php
class Core
{
    private $db;
    function connect()
    {
        $this->db = @mysql_connect($host, $user, $pass);
        @mysql_select_db($base, $db);

        //dummy 
        @mysql_connect();
    }

    function query($sql)
    {
        //notice second param
        return mysql_query($sql, $this->db);
    }
}

global $c;
$c = new Core();

include('plugin.php');
$p = new Plugin();
echo $p->not_work_connection(); //doing a mysql_query will use the dummy resource and fail
echo $p->work_connection();
?>
like image 188
capi Avatar answered Jan 17 '23 07:01

capi


Create for each class what doing some on database separate connection to separate user and keep handle to this connection in for example Plugin class, and use Database library to make operations on this handle. I think this is good solution.

Of course you setting permissions to users. (Separate user for each class or group of classes)

like image 23
Svisstack Avatar answered Jan 17 '23 06:01

Svisstack