How could you create the equivalent of "content_for" in PHP?

I am working on a small page in PHP that does not need the strength of a full structure. One thing that I really missed in my previous work in Ruby-on-Rails is the ability to efficiently transfer page content using "content_for".

I was wondering, how could you create a page life cycle that would perform the same effect in PHP?

So here is a simple example:

Say you have a template defining an index page, only a repeating title and menu that you want to use on all of your pages. So your file index.phplooks basically like this:

...header stuff...
<body>
<?php include $file.'.php'; ?>
</body>
...footer stuff...

EDIT: Thanks for the tips on securing URLs, but let me assume that I am receiving a user request safely :)

Now let's say in the header you want to put:

<head>
<title><?php echo $page_title; ?></title>
</head>

It would be nice to specify the header in the included file, so in the url http://example.com/index.php?p=testyou load test.php, and this file looks like this:

<?php $page_title = 'Test Page'; ?>
... rest of content ...

Now, obviously, this will not work, because the included page (index.php) is loaded before the variable is set.

In Rails, here you can pass up-page stuff with a function content_for.

My question is this: what will be the easiest, fastest way that you can all imagine to implement such "content_for" functionality in PHP?

, - , , .

+3
3
  • include $_GET['p']. , URL-, , . .
  • - , , test.php, , , , , . :

    <?php ob_start(); ?>
    <body>
    <?php include $filename.'.php'; ?>
    </body>
    <?php $content = ob_get_clean(); 
     include 'header.php';
     echo $content;
     include 'footer.php';
     ?>
    
+4

( RoR ), . , "test.php" , ( , ; , , ).

, test.php :

<?php
$page_title = "Test Page";
$page_content = "Some sort of content";

// Or

function page_content()
{
    // Run some functions and print content at the end
}

?>

index.php

<?php include $_GET['p'].'.php'; ?>
...header stuff...
<title><?php print $page_title; ?></title>
<body>
<?php print $page_content; ?>
<!-- OR if function -->
<?php page_content(); ?>
</body>
...footer stuff...

, . , ( , ).

!
.

+1

XSS? / " " ?

mod_rewrite - PHP, , , Apache!

RewriteCond, RewriteRule :

RewriteRule / index.php? P = (. *) $ $ 1 [L, QSA]

It may be a different approach than the PHP functionality you were looking for, but it comes to mind ...

+1
source

Source: https://habr.com/ru/post/1780360/


All Articles