Results 1 to 31 of 31

Thread: Master Pages in PHP

  1. #1

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Master Pages in PHP

    Hello,
    I can create master page in asp.net and can use it with many pages. Can i able to create masterpage in php?

  2. #2
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Master Pages in PHP

    This is how I always design my sites, so yes you can.

    Something like this is the basic understanding:

    echo "Welcome to my site <br />";
    if ($page=="aboutus")
    {
    include "aboutus.php";
    }
    elseif ($page=="contact")
    {
    include "contact.php";
    }
    else
    {
    include "home.php";
    }

  3. #3
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Master Pages in PHP

    You could shorten that with:
    Code:
    if(file_exists($page.".php")){
      include $page.".php";
    }
    Though if you're getting $page from a query string, you'd want to sanitize it first.

  4. #4
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    a better way to do it might be to either make an array containing all of the valid links and then checking if a key exists, or using a switch statement to validate it. this is much less verbose than a bunch of IF statements:

    PHP Code:
    <?php
      
    //if $page contains the page to include

      
    switch($page){
        case 
    "home":
        case 
    "about":
        case 
    "contact":
          require(
    $page ".php");
        default:
          require(
    "error.php");
      }
    ?>
    this will display only "valid" pages. it would be a good idea to also use file_exists() to make sure the file is present, and it would be simple to make this database driven, if desired, as well.

  5. #5
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Master Pages in PHP

    I just dislike the idea of having to update such code for each new "valid" page. If your root directory isn't "safe," make a sub-directory to put your "valid" pages in - if it's in there, it's valid, if not, don't put it there.

  6. #6
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    what you were doing was still potentially insecure though; if you don't validate $page in some way in your case, then I can include any PHP file that exists on your server as long as I create a relative path. this may have been something you knew, but I'm willing to bet some other people who will take your advice wouldn't have known ;) I don't personally use either of the methods I described (for basically the reason you stated -- maintainability), but I have in the past. and, for the most basic implementations, they're simple and easy.

  7. #7
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Master Pages in PHP

    this may have been something you knew
    Indeed, and this was implied by "you still need to sanitize." I consider "making sure a user can't manipulate your script to access any page they want" as [a rather important] part of sanitizing. Strip out slashes, double periods, etc.

    I suppose I assume someone wouldn't take a piece of code with a caveat and dump it into their script as-is, but I suppose I assume too much.

    And then there's the reason I keep insisting on easier-to-maintain code... I'm lazy.

  8. #8
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    I actually didn't see that you said something about sanitation! I was writing before you had made your own post and ended up only skimming it. though, I will conclude that some people might confuse sanitation of a query string with something like the way you sanitize a variable before putting it into an SQL query; but I have no clue. so whatever. anyhow -- being lazy (but in a way that makes or enables you to write efficient, "self-maintaining"? code) is a sign of a good programmer!

  9. #9
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Master Pages in PHP

    There are several security issues here that would make me suggest a different approach:

    • File Inclusion vulnerabilities: If the page variable is not fully validated you could put anything you like in it. At the very least it needs to be a name of the file and checked for file path meta characters such as "/" "\" and "."
    • Linkability: using a page name to find your inclusion page could give away information about the naming conventions you have used on your server and the name and / or location of pages on the server. A potential attacker could then attempt to access the page independent of the master page (of course, the page you are including should be outside the document route and terminate if run directly but in reality this is not always the case).
    • Access control vulnerabilities: this again comes from the use of page names. An attacker could change the query string and explore parts of the site that you did not intend. Again in the ideal world there will be a proper access control system in place that does not allow you to open the included pages without being authenticated, in reality this is not always the case.


    My recommendation would be to give each page a random integer identifier and have a lookup array in your master page, this an be moved to a database table if required.

    PHP Code:
    $pages = array(2563 => 'page1'27573 => 'page2'58968 => 'page3'); 
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  10. #10

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Hi,
    I am little bit confused with this idea. I want to navigate pages from links. My Masterpage coding is below. When i click the links the corresponding page must be opened in a masterpage. Any ideas? Thankyou
    Code:
    <body>
    	<table width="100&#37;" border="0" cellpadding="0" cellspacing="0">
    		<tr>
    			<td id="header">
    				<?PHP
    					include ('include/header.php');
    				?>
    			</td>
    		</tr>
    		<tr>
    			<td id="center">
    				<table width="100%" border="0" cellpadding="0" cellspacing="0">
    					<tr>
    						<td id="left">
    							<a href="">Register</a>
    							<a href="">Recover</a>
    						</td>
    						<td id="right">
    							<?PHP
    							 switch($page){
        							case "register":
        							case "recover":
          							require($page . ".php");
        							default:
          							require("login.php"); 
    							?>
    						</td>
    					</tr>
    				</table>
    			</td>
    		</tr>
    		<tr>
    			<td id="footer">&nbsp;</td>
    		</tr>
    	</table>
    </body>

  11. #11

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Hi,
    When i use these arrays, how to navigate a page with these arrays on corresponding links clicl. I want to navigate pages from links. My Masterpage coding is below. When i click the links the corresponding page must be opened in a masterpage. Any ideas? Thankyou
    Code:
    <body>
    	<table width="100&#37;" border="0" cellpadding="0" cellspacing="0">
    		<tr>
    			<td id="header">
    				<?PHP
    					include ('include/header.php');
    				?>
    			</td>
    		</tr>
    		<tr>
    			<td id="center">
    				<table width="100%" border="0" cellpadding="0" cellspacing="0">
    					<tr>
    						<td id="left">
    							<a href="">Register</a>
    							<a href="">Recover</a>
    						</td>
    						<td id="right">
    							<?PHP
    							 $pages = array(2563 => 'register.php', 27573 => 'recover.php'); 
    							?>
    						</td>
    					</tr>
    				</table>
    			</td>
    		</tr>
    		<tr>
    			<td id="footer">&nbsp;</td>
    		</tr>
    	</table>
    </body>

  12. #12
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    if you're using an array rather than a switch statement, then you should define $pages at the beginning of your script, and then define what page is being requested (most likely via your query string). then, you must check if this page request exists in that array, and if it does you can include the file associated with that number inside of your array. this is a somewhat simple example that would do it all for you; I've used a ternary operator, but if you're not too familiar with them you may want to just read the comments and duplicate what it does with nested IF statements or something.

    PHP Code:
    <?php
      
    //path to include files
      
    $path '../includes/';

      
    //pages array
      
    $pages = array(124 => 'home.php'2432 => 'about.php'404 => 'error.php');

      
    //get the current request
      
    $page = (isset($_GET['p'])) ? (isset($pages[$_GET['p']]) && file_exists($path $pages[$_GET['p']]) ? $_GET['p'] : 404) : key($pages);

      
    /* this ternary sequence does the following:
       * if $_GET['p'] is set:
       *   - checks if it's a valid value within the $pages array and if that file exists
       *   - sets $page to 404 if the page is invalid or the file doesn't exist
       * elseif $_GET['p'] is not set:
       *   - sets the default page to the first key in the array (in this case, 124)
       */

    ?>
    <!-- "top" of your HTML template -->
    <?php

      
    require($pages[$page]);

    ?>
    <!-- the rest of your HTML template -->
    hope that helps.

  13. #13

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Thankyou this helps me a lot. I can use this, is it possible to add AJAX here. I am having 2 div, left and right. the content in the left div is always same, only right div content will change according to the menu in the left div.

  14. #14
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    it's possible to have ajax in just about anything, but that depends on what you actually want to do. if you mean you want to use ajax to load new pages rather than actually reloading the page when they navigate, then I'm sure it could be done. it would almost defeat the purpose of having a "master page" in the first place, though, as that would be like legacy behaviour if javascript wasn't enabled. if you're not too familiar with ajax, I wouldn't bother trying to do anything like that right now.

  15. #15

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    I simply want to show new pages in the right div, according to the leftmenu clicks. When i use master pages, the left div content also loads again when the right div loads. So that i need to use ajax.

  16. #16
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    uh. no, you don't need to use ajax. I think you're confusing ajax with something else. ajax is for dynamically updating things without refreshing a page; what you're describing has absolutely no reason to use ajax.

    a "master page" in ASP.NET lets you simply create a template file that has a content placeholder for where your content will go. then, you assign an ASP file this template and the content in this ASP file appears in the content place holder. with PHP, it's much less structured in that you need to make this system yourself -- this is because PHP is just a language (as is ASP), but ASP.NET is ASP using the .NET framework. just as well, there are many frameworks written in PHP that could help you do the same thing easily, but I won't get into those.

    so, if you want to take the code I wrote in my last post:

    PHP Code:
    <?php
      
    //path to include files
      
    $path '../includes/';

      
    //pages array
      
    $pages = array(124 => 'home.php'2432 => 'about.php'404 => 'error.php');

      
    //get the current request
      
    $page = (isset($_GET['p'])) ? (isset($pages[$_GET['p']]) && file_exists($path $pages[$_GET['p']]) ? $_GET['p'] : 404) : key($pages);

      
    /* this ternary sequence does the following:
       * if $_GET['p'] is set:
       *   - checks if it's a valid value within the $pages array and if that file exists
       *   - sets $page to 404 if the page is invalid or the file doesn't exist
       * elseif $_GET['p'] is not set:
       *   - sets the default page to the first key in the array (in this case, 124)
       */

    ?>
    <html>
      <head>
        <title></title>
      </head>
      <body>
        <h1>title</h1>
        <div id="left">
          <ul>
            <li>navigation</li>
          </ul>
        </div>
        <div id="right">
    <?php

      
    require($pages[$page]);

    ?>
        </div>
        <div id="footer"></div>
      </body>
    </html>
    if you look at how I've structured the HTML in this example, you'll see that this is incredibly similar to ASP's "master pages" with just a little extra. at the top of the script you have the code that handles a request, and then you start your template. in the middle of your template, you have a "content placeholder" where you use require() to include the content file (in this case, $pages[$page] -- which would be equal to "home.php" if $page was 124).

    again, this has nothing to do with ajax. unlike ASP.NET, PHP does not give you a ton of unnecessary mark-up (including javascript) to get basic functionality. PHP lets you build everything yourself. javascript (or ajax) is used specifically for user interaction to make a better browsing experience; this is not something used for "basic functionality."
    Last edited by kows; Jan 26th, 2010 at 10:39 AM.

  17. #17
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Master Pages in PHP

    If you want that sort of functionality, I'm tempted to say frames would be a better choice than AJAX. They don't require JS, they won't disrupt the user's ability to use the back button (a typical user complaint about AJAX), they'd be simpler to make and maintain.

    Or you could accept that it's normal, conventional behavior for the whole page to load, and that users expect that.

    Edit: kows got in before me - was responding to the post prior.

  18. #18

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Thankyou for making me clear with AJAX. That code is very useful, thankyou.

  19. #19
    Hyperactive Member
    Join Date
    May 2008
    Location
    >> ( ҉ )
    Posts
    413

    Re: Master Pages in PHP

    Easiest way.

    PHP Code:
    <?php
    if($_GET['Action'] == "Example") {
    include(
    "Example.php");
    }
    if(
    $_GET['Action'] == "") {
    }
    ?>

  20. #20
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    um. that's probably the worst way; way too much code going on, very hard to maintain. the solutions above are much better.

  21. #21
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    Re: Master Pages in PHP

    Pls help, I tried you c0d and it gave me e33or
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  22. #22
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    1,023

    Re: Master Pages in PHP

    most of this code is made by kows but i improved it a bit and i hope kows accepts that i post this code... http://www.vbforums.com/showthread.php?t=593662
    this is what i use:
    PHP Code:
    <?php

      $path 
    "./pages/"
      
    $extension ".php";
      
    $valid "main,test1,test2"/*pages allowed to be in ?page= separate by comma*/
      
    $x 0;
      
      if(isset(
    $_GET['page'])){
          
    $page explode(","$valid); 
        foreach(
    $page as $pages) {
        if (
    $pages == $_GET['page']) {
        
    $x++;
        }
        }
        if (
    $x 0) {
        
    $allow "true";
        if(
    file_exists($path $_GET['page'] . $extension)){
          
    $action $_GET['page'];
        }else{
          
    $action "error"// just incase
        
    }
      } else {
        
    $allow "false"// goes to $action = "main";
      
    }
      }
      if(!isset(
    $action)){
      
    $allow "true";
      
    $action "main";
      }
    ?>
    <html>
    <head>
    <style type = "text/css">
    </style>
    <title>Title here</title>
    </head>
    <body>
    <?php 
    if ($allow == "true") {
    require_once(
    $path $action $extension); 
    } else {
    require_once(
    $path "main"$extension);  // if invalid page this will show
    }
    ?>
    </body>
    </html>

  23. #23
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    rather than having a string delimited by a comma, you're better off having an array that holds all of those values instead. this way, you avoid breaking up $valid yourself and then looping through every element just to see if this $action is valid. you can use isset() to check if the key exists:

    PHP Code:
    <?php
      $valid 
    = array("main""test1""test2");

      if(isset(
    $valid[$action])){

        include( .... );

      }
    ?>
    you can throw in your error checking to make sure this file exists and all that, but you'll be better off doing something like this rather than what you're doing now.

    andddd one last thing: you're using strings as boolean values -- I would suggest you don't do that. use boolean values instead! much easier to deal with:

    PHP Code:
    <?php

      $myVar 
    false;
      if(
    $myVar){  //checks if myVar is true, which it isn't
        
    echo 'This will not echo';
      }

      
    $myVar "false";
      if(
    $myVar){   //this still checks if myVar is true, which it is
        
    echo 'This will echo';
      }
    ?>
    this is because any value that is not false or equal to zero is true. limiting the amount of code you need to write is a good thing.

  24. #24
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    1,023

    Re: Master Pages in PHP

    well i haven't been much into arrays so i couldn't figure that one out...

  25. #25
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    oops: a note of my hastiness to type that all out during class was that my example won't exactly work as intended. isset($valid[$action]) is checking for the key named $action within the array $valid; but the array I made with $valid doesn't has numeric keys! either two things could fix this -- you can either define a key in the array and then give each key properties (which is usually what I do), something like:

    PHP Code:
    <?php
      
    //simple:
      
    $valid = array(
                     
    "main"  => "Main",
                     
    "test1" => "Test page 1",
                     
    "test2" => "Test page 2"
                     
    );
                     
      
    //complex:
      
    $valid = array(
                     
    "main"  => array(
                                      
    "caption" => "Main",
                                      
    "file"    => "main.inc.php",
                                      
    "access"  => 0
                                      
    ),
                     
    "test1"  => array(
                                       
    "caption" => "Test page 1",
                                       
    "file"    => "test1/file.php",
                                       
    "access"  => 1
                                       
    ),
                     
    "test2"  => array(
                                       
    "caption" => "Test page 2",
                                       
    "file"    => "../test2/main.inc.php",
                                       
    "access"  => 3
                                       
    )
                    );
    ?>
    however, as you'd imagine, using the more complex model is incredibly difficult to do manually. this is generally the way I format an array when loading a menu from a database. it lets me only allow a certain user to view certain pages by only loading those pages into the array. this way, there would be no possible way for that user to view an unrestricted page by accident -- the system would simply not realize that that page existed at all.

    then, like Samba said before, doing things like this using arrays or switches in the first place can be really hard to maintain. that's why I use these models technically, but everything comes from a database. I would never manually build arrays like these for a large project.

    then again, you'd need to be pretty comfortable with arrays to do something like this, I suppose!

  26. #26

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    but everything comes from a database. I would never manually build arrays like these for a large project.
    Hi,
    Can you please post the sample code which you are loading from database?

  27. #27

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Hi,
    I am navigating pages with query string.
    Code:
    http://localhost/mvb22/home.php?nav=520&id=113
    I dont want to display the querystrings in address bar. I want like the link to be displayed to be as
    Code:
    http://localhost/mvb22/home.php?
    This is becoz when i change the id and nav in the address bar, the link goes to the unauthorized page for the current user.
    Any ideas?

  28. #28
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    if you're trying to say that the user is going to a page that they should not be allowed to go to, then that's something you can just implement security for. you just have to make sure they have authorization to visit the page before displaying anything for that page.

    if you just don't want the query string displayed in the address bar, then ... there isn't really anything you can do besides just stopping using the address bar. you could use sessions instead, but this could present other issues that I'm not sure you would know how to deal with. you could also just mask your URLs using the mod_rewrite package in Apache (or the equivalent in IIS7), but this really wouldn't solve your issue if you don't want the navigation number and the ID being displayed in the address bar at all.

    try to explain a little better or give some context, perhaps, so that we know what you're actually trying to do.

  29. #29

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    Ya i need to navigate pages with the help of query string, think of a profile page, every user can view others profile page, and also his/her profile page and if the profile page belongs to logged user means then only they can able to edit their profile.
    So i used this query string.
    Code:
    http://localhost/mvb22/home.php?nav=520&id=113&mode=edit
    So when the user simply adds "mode=edit" in the address bar means, they are able to edit other members profile page also.
    How to get rid of these?

  30. #30
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Master Pages in PHP

    like I said:
    Quote Originally Posted by kows View Post
    that's something you can just implement security for. you just have to make sure they have authorization to visit the page before displaying anything for that page.
    you're the one who needs to implement that security. if you don't want a user to be able to edit another user's profile, then you need to check if the logged in user is editing his own profile or not. or, better yet, scrap the way you're doing it now and make a new page altogether that's named "editprofile." this can take the ID from the current session and display a form for editing that user's profile only. this would solve the problem of needing to authenticate a user when trying to edit a profile.

  31. #31

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: Master Pages in PHP

    ya thankyou, i will try that.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width