PHP - Protecting Class/include Files
I been wondering how to protect all the files that contain classes, functions and forms in php to prevent direct access to something that the user shouldnt be able to without the proper check's (typing http://server/inc/login.php insteand of http://server/), and i came to this small idea of checking if an object is set or not but i m wondering if this is really the best idea here's what i have (the case bellow will protect an login form to be accessed directly):
Code: [Select] <?php if(!isset($mysqlobj)) die(); if( isset( $_POST['username'] ) && isset( $_POST['password'] ) ){ $login = authentication::login( $_POST['username'], $_POST['password'] ); if( $login == true ){ header( 'location:?go=home' ); }else{ $_SESSION['message'] = 'loginfailed'; header( 'location:?go=login' ); } }else{ if( !empty($_SESSION['logged'] ) && $_SESSION['logged'] == true ){ header( 'location:?go=home' ); }else{ ?> <div id="loginform"> <form action="?go=login" method="post"> <table align="center"> <tr> <td><font size="2">Username</font></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><font size="2">Password</font></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Login" /></td> </tr> </table> </form> </div> <?php } } ?> Just looking for an "best practice" i tried google for it but i couldnt get to an straight awnser any enlightment is appreciated. Similar TutorialsUsing PHP Version 5.2.13 My question: How do I access a class and it's methods from an included file? I have an Index.php page that calls two methods: <?php get_header(); ?> <?php get_footer(); ?> and it creates a class in an include file <?php include_once($_SERVER['DOCUMENT_ROOT'].'/includes/common.html');?> $site = new WebSite($site_name); // Creates a bunch of properties, defines some methods, etc... $site->initialize(); <?php get_header(); ?> ends up including a another file (header.php) <?php get_header(); ?> ends up including a another file (footer.php) All calls in Index.php to methods in my class work. ie <?php $site->display_section('column'); ?> But calls in either the header.php or footer.php to methods in my class fail with "Call to a member function is not an object". I understand what the error means but I don't understand why. I thought all functions and classes defined in an include file have global scope. As per PHP.NET's documentation: "When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope." The include that creates the class is something that I have inherited from another developer and I actually can't change the scope. I've tried with global $site = new WebSite($site_name);. It actually breaks the entire site. How can I access classes, properties, methods in an include file? Any help would be appreciated. I've been racking my head for several days now on it and it's probably some newbie thing that I am completely overlooking. I hope I've provided enough background and info. Thanks, Brian Hi All, I'm trying to secure my web app which is currently in development, and came across this issue. I have a header.php and footer.php page which are included to every page, with the content in the middle. The problem is, if you visit header.php then it displays the header, with some blank text. What is the best way to protect this - i.e., if visited directly, it re-directs to index.php etc. My initial thought is to set a $happylink on each page and in the header and footer, checking basically doing the following if (isset($happylink) && !empty($happylink)) { blah blah; } else { Header("Location: index.php"); } Would that be the best way? Is there something easier? Hi! I would appreciate your help... How can i include files with get and post data in order to avoid sql injections? The including data has utf8 encoding... Any suggestions??? Thanks in advanced!!! Can you include a file and append info to be grabbed by using GET? For example, can you have an include file like this... Code: [Select] include('file.php?id=1'); And then in the file "file.php" I would use $_GET['id'] to do other things in the code. I tried it and it's not working. I'm getting this error... "Warning: include(file.php?id=1) [function.include]: failed to open stream: No such file or directory in..." Just want to find out if this should be doable before I continue testing why it's not working for me. If it should work, should I be using something other than include maybe? (like require or require_once?) hello , i have created web application in which i have divided the all parts of page like - main header part - contains the <!DOCTYPE to <body> part other header part - contains the logo,slideshow of the header of page then the main part and at the end footer part i have created on folder which contains the detail of page content info referenced from the other pages from main content.. here i am facing problem as the style sheet , javascripts and the other header part of file is not references well.. how to do it? please guide me with correct solution awaiting for better response... I have obviouslt done something wrong for I get the following errors/warnings when running a simple script:- Warning: include(/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include() [function.include]: Failed opening '/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include(includes/error-handler.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include() [function.include]: Failed opening 'includes/error-handler.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include(includes/get-input.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Warning: include() [function.include]: Failed opening 'includes/get-input.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Fatal error: Call to undefined function mssql_connect() in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 14 this from the code :- Code: [Select] <?php ini_set('include_path', dirname(__FILE__) .'/includes'); // require_once(dirname(__FILE__) . "/includes/body-background.php"); include(dirname(__FILE__) .'/includes/body-background.inc'); include('includes/error-handler.inc'); include('includes/get-input.inc'); Please tell me what I have done wrong. This with Apache2 on Ubuntu 10.4 and php 5.3. I've just gotten back into re learning web development, I have created a contact form however my server is forcing me to use SMTP which will require me to have a config include with my details inside. How do I ensure nobody can open the files in the browser? I have heard of putting the files outside of the webroot or using htaccess files however the passive aggressive answers I got from stack over flow didn't tell me HOW to implement them. The files are Form.HTML Bin/config.php Bin/mail.php Any help is appreciated. I've just changed my .shtml file to .php but the #include files don't seem to be picked up? Any idea what I can do to solve this? Code: [Select] <?php function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } // The form was submitted // if (isset($_POST['button'])) { if (isset($_REQUEST['name']) && $_REQUEST['name'] != '' && isset($_REQUEST['email']) && $_REQUEST['email'] != ''){ $fun = array( 'virusandmalwareremoval', 'fullservice', 'quickfix', 'upgrade', 'xbox360drivereplacement', 'xbox360laserreplacement', 'xbox360rrodrepair', 'ps3drivereplacement', 'ps3laserreplacement', 'ps3ylodrepair', 'databackup', 'websites', 'datarecovery', 'networkinstallation', 'mobilephoneissues', 'emailconfiguration' ); foreach ($fun as $value) { ${$value} = (isset($_REQUEST[$value]) ? $value . "\n" : ''); } $name = $_REQUEST['name']; $email = $_REQUEST['email']; $enquiry = $_REQUEST['enquiry']; if (ereg("[\r\n]", $name) || ereg("[\r\n]", $email)) { header( "Location: http://www.parkersmedia.com/byrne" ); } $mailcontent = "Name: ".$name; $mailcontent.= "\n\nEmail: ".$email; $mailcontent.= "\n\nInterested in: \n". $virusandmalwareremoval . $fullservice . $quickfix . $upgrades . $xbox360drivereplacement . $xbox360laserreplacement . $xbox360rrodrepair . $ps3drivereplacement . $ps3laserreplacement . $ps3ylodrepair . $databackup . $websites . $datarecovery . $networkinstallation . $mobilephoneissues . $emailconfiguration; $mailcontent.= "\n\nEnquiry: " . $enquiry; if (mail( "info@byrnecomputingservices.ie", "Enquiry from Byrne Computing Services","$mailcontent", "From: $name <$email>" )) { header( "Location: http://www.parkersmedia.com/byrne/thankyou.shtml" ); } else { echo 'Mail not sent'; } } else { echo 'Required fields are empty'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Byrne Computing Services</title> <link href="styles.css" rel="stylesheet" type="text/css" /> <script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="inc/jquery.js"></script> <script type="text/javascript" src="inc/easySlider.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#slider").easySlider(); }); </script> </head> <body> <div id="wrapper"> <!--#include file="inc_header.html" --> <!--#include file="inc_scrollingimages.html" --> <div id="boxesholder"> <!--#include file="inc_specials.html" --> <div id="main"> <div id="mainheader"> Contact Us</div> <div id="maincontent2"> <h2>Fill in the form below and we will contact you shortly.</h2> <p><img src="images/binarycode.jpg" alt="Binary Code" width="167" height="600" class="images" /><form id="form1" name="form1" method="post" action="contact-us.php"> <strong>Name: </strong><br /> <input name="name" type="text" class="formsingle" id="name" /> <br /> <br /> <strong>Email:</strong><br /> <input name="email" type="text" class="formsingle" id="emailaddress" /> <br /> <br /> <strong>Interested in:</strong><br /> <table border="0" cellspacing="0" cellpadding="0" class="table"> <tr> <td class="interestedin"><strong>Computer Repair</strong></td> <td class="interestedin"><strong>Console Repair</strong></td> <td class="interestedin"><strong>Other Services</strong></td> </tr> <tr> <td class="interestedin"> <input name="virusandmalwareremoval" type="checkbox" class="formcheckbox" id="virusandmalwareremoval" value="virusandmalwareremoval" /> <label for="virusandmalwareremoval">Virus and Malware Removal</label> </td> <td class="interestedin"> <input name="xbox360drivereplacement" type="checkbox" class="formcheckbox" id="xbox360drivereplacement" value="xbox360drivereplacement" /> <label for="ps3drivereplacement">Xbox 360 Drive Replacement</label> </td> <td class="interestedin"> <input name="databackup" type="checkbox" class="formcheckbox" id="databackup" value="databackup" /> <label for="databackup">Data Backup</label> </td> </tr> <tr> <td class="interestedin"> <input name="fullservice" type="checkbox" class="formcheckbox" id="fullservice" value="fullservice" /> <label for="fullservice">Full Service</label> </td> <td class="interestedin"> <input name="xbox360laserreplacement" type="checkbox" class="formcheckbox" id="xbox360laserreplacement" value="xbox360laserreplacement" /> <label for="ps3laserreplacement">Xbox 360 Laser Replacement</label> </td> <td class="interestedin"> <input name="websites" type="checkbox" class="formcheckbox" id="websites" value="websites" /> <label for="websites">Web Design</label> </td> </tr> <tr> <td class="interestedin"> <input name="quickfix" type="checkbox" class="formcheckbox" id="quickfix" value="quickfix" /> <label for="quickfix">Quick Fix</label> </td> <td class="interestedin"> <input name="xbox360rrodrepair" type="checkbox" class="formcheckbox" id="xbox360rrodrepair" value="xbox360rrodrepair" /> <label for="ps3ylodrepair">Xbox 360 RROD Repair</label> </td> <td class="interestedin"> <input name="datarecovery" type="checkbox" class="formcheckbox" id="datarecovery" value="datarecovery" /> <label for="datarecovery">Data Recovery</label> </td> </tr> <tr> <td class="interestedin"> <input name="upgrades" type="checkbox" class="formcheckbox" id="upgrades" value="upgrades" /> <label for="upgrades">Upgrades</label> </td> <td class="interestedin"><input name="ps3drivereplacement" type="checkbox" class="formcheckbox" id="ps3drivereplacement" value="ps3drivereplacement" /> <label for="ps3drivereplacement">PS3 Drive Replacement</label></td> <td class="interestedin"> <input name="networkinstallation" type="checkbox" class="formcheckbox" id="networkinstallation" value="networkinstallation" /> <label for="networkinstallation">Network Installation</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3laserreplacement" type="checkbox" class="formcheckbox" id="ps3laserreplacement" value="ps3laserreplacement" /> PS3 <label for="ps3laserreplacement"> Laser Replacement</label></td> <td class="interestedin"> <input name="mobilephoneissues" type="checkbox" class="formcheckbox" id="mobilephoneissues" value="mobilephoneissues" /> <label for="mobilephoneissues">Mobile Phone Issues</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3ylodrepair" type="checkbox" class="formcheckbox" id="ps3ylodrepair" value="ps3ylodrepair" /> <label for="ps3ylodrepair">PS3 YLOD Repair</label></td> <td class="interestedin"> <input name="emailconfiguration" type="checkbox" class="formcheckbox" id="emailconfiguration" value="emailconfiguration" /> <label for="emailconfiguration">Email Configuration</label></td> </tr> </table> <br /> <strong>Enquiry: </strong><br /> <textarea name="enquiry" class="formmulti" id="enquiry"></textarea> <br /> <br /> <input type="submit" name="button" id="button" value="Submit" /> </form> </p> <p><br /> </p> </div> </div> </div> <!--#include file="inc_offers.html" --> <!--#include file="inc_footer.html" --> </body> </html> when i expire a cookie, it expires on stand alone files but any references to $_COOKIE in include files still show the old cookie. How can i expire the cookie in include files. Php Folks, As you know, typing the same code over and over again on all files is daunting. I was wondering, if I can have an error_reporting.php file and then put:
include('error_reporting.php');
at the top of all my php files as header, where the error_reporting.php would have this content: <?php error_reporting(E_ALL); ini_set('error_reporting','E_ALL'); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); ?> Q1. Is that ok or not ?
Q2. Usually, I have a conn.php with content like this: <?php $conn = mysqli_connect("localhost","root","","db_database"); $db_server = 'localhost'; $db_user = 'root'; $db_password = ''; $db_database = 'test'; $conn->set_charset('utf8mb4');//Always use Charset. if (!$conn) { //Error Message to show user in technical/development mode to see errors. die("Database Error : " . mysqli_error($conn)); //Error Message to show User in Layman's mode to see errors. die("Database error."); exit(); } ?>
And then, on all my php files, I just reference to the conn.php by putting the following line on the header: include('conn.php');
Or:
require('conn.php');
And on each php file, just before dealing with mysql, I have a line like this: mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); $conn->set_charset("utf8mb4"); Now, I am wondering, why should I write the above 2 lines on all my php files that deal with mysql ? To keep things short, why don;t I just add those 2 lines in the error_reporting.php ? So, it looks like this:
error_reporting.php
<?php ini_set('error_reporting','E_ALL');//error_reporting(E_ALL); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); $conn->set_charset("utf8mb4"); ?>
Hi! I have a class with many functions/methods. I want to split this into different files so I can easily edit and add functions. I want every functions to be able to call eachother and with that I mean, they have to be for example in same document. My question is: I can't have a class and include functions like this: Code: [Select] class DB { include('select_functions.php'); //Only includes function's no class include('insert_functions.php'); //Only includes function's no class include('delete_functions.php'); //Only includes function's no class function test() { } } The includes will output fatal errors... How can I solve this so I can have all functions in different files but still use ONE object to call them! Thanks! How do you include files from a higher up directory? I'm currently working on a file in public_html/Directory/otherdirectory and want to include a config file that's in public_html/Directory so how would I include public_html/Directory/config.php in the public_html_Directory/otherdirectory/index.php file? I've tried using ../ and ../Directory/ in the includes line but got errors both times Edited April 11, 2020 by Nematode128I need some help with this. I created an index.php page and I inserted an include statement that referred to a header.html page. It works when working it in MS Webmatrix but when I put it on my server I only get my index.php page. My include statement will not get the header.html page. What am I doing wrong? I also tried changing all of my files to .php extensions also and still the same. Here is my index.php file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Braswell Electric</title> <link rel="stylesheet" href="braswellelectric.css"> </head> <body> <div> <?php include('/includes/header.html');?> <?php include('/includes/aside.html');?> <article class="About"> <header class="AboutHeader"> <h2>About Us</h2> </header> <p><b>Braswell Electric</b> is a family business owned and operated by Jim and Joyce Braswell located in Sylacauga, Alabama. Braswell Electris has been in business in Sylacauga for 25 years and covers the greater Talladega County area. We do new homes, remodels, or any small electrical issues you may have. We are licensed and insured and we are here for your residential needs.</p> <img src="pics/Coach Light.jpg" alt="Coach Light" > <img src="pics/Outside Plug.jpg" alt="Outside Plug"> <img src="pics/Service.jpg" alt="Service"> </article> </div> </body> </html> Here is my header.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <header class="Header"> <h1 style="display: none">Braswell Electric</h1> <img src="pics/lightning1.jpg" alt="Header Pic"> </header> </body> </html> Edited by Ch0cu3r, 27 August 2014 - 12:37 PM. I'm a little confused with the use of absolute paths in PHP. I've always used relative paths but it's becoming an issue with some of the apps I'm working with and absolute would solve the problem. The thing is, I'm getting different results in different places and I'm a little confused. With regular HTML I seem to be able to use / as the root of my site. So if I do the following... Code: [Select] <img src="/images/name.jpg" /> That works fine no matter what page it's called from in the site and no matter what directory that page is in. I need to be able to do that same thing with PHP. Now, in my custom 404 page I have the following... Code: [Select] if($AddressURL == 'http://www.domain.com/blog/files/filename.zip') { header('HTTP/1.1 301 Moved Permanently'); header('Location: /download/filename.zip'); exit(); } That actually works just fine. If I go to the /blog/files/filename.zip (which doesn't exist) in a web browser it winds up downloading the file at www.domain.com/download/filename.zip as expected. Now where I get confused is that include files don't seem to work like that with PHP. If I do this... Code: [Select] require_once('/includes/config.php'); That winds up looking for an /includes folder all the way back at the local server root, not just the web root. so it's looking for /var/includes instead of /var/www/includes and of course that doesn't end up working. So, how come the include file paths work differently than regular HTML paths or header redirects in PHP? Is there any simple way I can always refer to the SITE root no matter what server it's running from? I've tried playing with $_SERVER['DOCUMENT_ROOT'] but it only seems to return the root of the current document, not the root of the whole site. So if I use it within a php file located in /var/www/includes/test.php it considers /includes the root which is not what I want. Any information would be greatly appreciated. Thanks! Hi All, I have written the following to validate my dynamic includes, one question is i will be using sessions to control user access to certain pages. Obviously the session_start() has to go into my index.php file. Can anyone see any problems with this or my dynamic include validation code. My page varilable is populated using the mod_rewirte function in appache. <?PHP include('inc/settings.inc.php'); if(isset($_GET['page'])) { //remove slashes $page = stripslashes($_GET['page']); //rebuild the extension and file name $filename = 'lib/'.$page.'.php'; //Check to see if the file exists in lib if (file_exists($filename)) { //Dynamic Switch $allowed = array( array("test", "New Customers"), array("home", "Home Page"), ); $iffed = false; $get_section = $_GET['page']; //Create a dynamic switch to check for files being in my allowed array foreach($allowed as $rd) { if($get_section == $rd[0]) { $iffed = $rd; $content = $filename; foreach($rd as $value) { $page_title = $value; } } } if($iffed === false) { //File is not in my include list. die( "Page does not pass the validated inclusion list." ); } } else { //Page does not exist in my lib folder. die('Page does not exist, please contact the administrator.'); } } else { // If no page is requested then default home. $filename = 'lib/home.php'; $content = '1'; $page_title = 'Home'; } ?> Thanks in advance. Sam Let's say somebody opens some of my class files via: Example: http://admin.mysite.com/classes/main.php Can he do anything to harm my website? Is this important to protect? I keep protecting file by file with a function like: Code: [Select] include('pagevariables.php'); if($current_page == $file['mainclass']){ header('Location: '. $file['home']); } Is this possible via .htaccess? I don't know how to write htaccess. I have 2 php files. I am unable to get B's global variable from A's static method: A.php Code: [Select] class c_A { public static function f_A() { include_once( "B.php" ) ; print f_B() ; } } c_A::f_A( ); // only prints "B : " B.php Code: [Select] $gvs = "global variable from B" ; function f_B() { return "B : " . $GLOBALS[ "gvs" ] ; } any thoughts? thanks, Shannon Hi! I need help understanding how to access resource files using ResourceBundle Class and what should be ResourceBundle file format. I have an example of usage in the form of: $r = ResourceBundle::create( 'en', $fileName); but what is the correct format of Resource file? Can it be a format of property file in the form of key=value key=value? or can it be a .txt file of format?: root:table { myName:string { "Here goes my name" } } Can someone share a very simple example of ready to use Resource file with a plain text in it? Thank you! i use csv file reader class to read csv file...... i need to understand where i should create the sessions array so that i dont have to go back to this class everytime to reteive data..... I am rebuilding a CMS system that I have been developing over the last ~6 years. It needs to have many different kinds of modules depending on the installation (Like Drupal or Joomla does) I have a Core class that does the major processing. I am currently developing the part of the system that loads the actual module into the index.php page. While experimenting I came up with an idea that is probably really horrible but I started to wonder if maybe it could actually work well. I am looking for feedback on this Core class function: Code: [Select] public function LoadMods($ModsToLoad) { foreach ($ModsToLoad as $mod) { $MainFile = ABSPATH.DS.$mod.DS.'main.php'; if (file_exists($MainFile)) include ($MainFile); else $this->_MAIN .= 'Error: The "main" file for "'.$mod.'" module could not be found<br/>'; } } It will receive an array of Module names and those names correspond to a directory that holds the "main.php" file for that module. Example: index.php?mod=Photos Will load the "Photos" module. Here is the thing that has me concerned... A module might have it's own class or classes and that class will likely get included in the "main.php" file for that module. What effect is that going to have on my core class because it starts nesting classes inside classes. Is this an efficiency advantage or am I heading down a road paved by code stink? What's you opinion? |