簡體   English   中英

拒絕繼承或使用PHP類

[英]Denying a PHP class to be inherited or used

對於我的項目,我創建了一個名為DBAccess的文件夾,其中包含所有與數據庫相關的PHP文件,包含PHP類,常量函數等。在文件夾的外部,我創建了一個名為DBAccess.php的php文件。 以下是我的目錄結構

Project1
  |_DBAccess
  |       |_functions.php
  |       |_class.php
  |       |_constants.php         
  |_DBAccess.php
  |_index.php
  |_aboutus.php  
    .......

現在我希望限制根目錄中的任何頁面使用除DBAccess.php文件之外的DBAccess文件夾的內容。它是否可以在PHP中使用.htaccess或其他東西?

你可以這樣做:

DebugAccess / foo.php

<?php
$trace = debug_backtrace();

if (isset($trace[0])) {
  $dir =  basename(dirname($trace[0]['file']));
  $file = basename($trace[0]['file']);
  if ($file != 'DBAccess.php' && $dir != 'DBAccess') {
    throw new Exception("Nice try butthead");
  }
}

echo "Access Granted\n";

DBAccess.php

<?php
include_once("DBAccess/foo.php");

NoDBAccess.php

<?php
include_once("DBAccess/foo.php");

> php DBAccess.php 
Access Granted

> php NoDBAccess.php 

Fatal error: Uncaught exception 'Exception' with message 'Nice try butthead' in /Users/seanberry/so/DBAccess/foo.php:7
Stack trace:
#0 /Users/seanberry/so/NoDBAccess.php(3): include_once()
#1 {main}

您可以創建一個處理此問題的函數,您所要做的就是在_DBAccess.php或您需要訪問這些文件的任何其他文件中調用該函數。

試試這個功能:

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        require $filename;
    }
}

然后你只需要用foldername調用該函數。

include_all_php("_DBAccess")

如果您希望文件不包含這些文件,那么不要求它們:)

是的你可以 :

a)通過在DBAccess.php中定義全局變量,例如

define('DB_LIB',true)

並在文件夾中的所有其他文件中使用DB_LIB常量

(bit cheep trick但這可以確保這些文件不會直接訪問上下文)

b)通過將定義為final來停止繼承

間接回答問題

c)停止重新發明輪子(如果您正在創建一個訪問層,如您的示例所示)並使用已有的一個PDO

d)使用一些合適的OO設計模式, 例如並檢查 你的反應是什么原因? 因為使用模式將修復許多繼承和依賴性問題,例如在訪問層的情況下,子對象將不會被實例化,除非它不是使用依賴對象創建的,例如在工廠案例中

f)使用公共,私人和受保護關鍵字的用戶

  • .htaccess與PHP無關,它是Apache Web服務器的設置文件。 Apache無法阻止PHP代碼讀取磁盤上的文件。

  • 您可以通過例如要求定義某個常量來防止意外訪問:

     // DBAccess.php define('CAN_ACCESS_DB', true); // functions.php if( !defined('CAN_ACCESS_DB') ){ die('You are not allowed to access this file'); } 

    ......但是沒有辦法阻止故意訪問。

你最好的機會可能是重新考慮你的設計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM