PHP - How to make a GET pull a include?

Asked

Viewed 149 times

1

If I access a page like for example http://localhost/? color=blue

Using the following GET:

<?php echo  ($_GET["cor"]) ; ?>

The name will be printed Blue.

It is possible to make instead of appearing the name "Blue", be pulled a include?


Example: If the person type: http://localhost/? color=Green

Instead of being printed only the word "Green", will be printed a <div> that is inside file that was pulled for include, example (green.php):

<div>A cor selecionada foi <b>verde</b> </div>

The question is simple, it is possible to do a GET pull a include?

2 answers

5

Yes it is possible, in my projects I use so:

$page = $_GET['page'];
if (file_exists($page.".php")) {
    include($page.".php");
} else if (file_exists($path_paginas . "/".$page.".html")) {
    echo stripslashes(file_get_contents($path_paginas . "/".$page.".html"));
} else {
    include("principal.php");
}

2

It is possible yes, only you should be careful, this method is not recommended by the community.

You can do it this way:

function view($params = array()){
    /**
    * @params[0] retorna nome do arquivo
    * @params[1] retorna extensão do arquivo
    */

    if(file_exists($params[0].$params[1])){
        require_once($params[0].$params[1]);
    }else{
        require_once("404.php");
    }
}

view( array( $_GET["arquivo"], ".html" ) ); //executa função

By following this example model, you can create something a little bit more complete. Nowadays there are several standardized methods to work with this type of system, but as it is for knowledge, follow it.

  • The main problem of your method, is that the included file will be within the scope of the function, and all global variables that need to be used will have to be declared as global, in terms of security mine also checks if the file exists before giving the include, but if you want something more robust, just create an array with all the options allowed, but personally I find it unnecessary, since fileexists does not confirm remote files...

  • Yes. This is true. But in general the problem lies in the fact that he wants to do so. As he did not explain what he wanted, I made this example to show.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.