How can I replace the text on the active document body on a PHP file on code execution?
Do I have to import a file, replace text on it and then echo it or can I just manipulate the document I run the PHP script on?
I am trying to use templates for easier HTML editing like :usernamecomeshere: and then replacing that :usernamecomeshere: with the actual value. I am wondering If I can do it on one file only instead of loading a file and then displaying it.
If I'm getting your question correctly, you don't need to important a file and echo the document. You can directly manipulate the document itself. For example, in the below sample, you can directly echo the contents of $username in a way that's interspersed with HTML code.
index.php
<?php
// handle code to login
$username = "David";
?>
<html>
<body>
<p>Hello, your username is <?php echo $username ?></p>
</body>
</html>
Worth pointing out is that PHP itself is a templating engine. If you want to replace text, you can do it using PHP such as:
<?php
$user = 'Ugur';
?>
<html><head></head>
<body>
<h1>Hello <?php echo $user; ?></h1>
</body>
</html>
Beyond this sort of simple usage, you may want to look at various template engines, which allow you to do much more elegant things, but are more complex. Take a look at mustache, perhaps?
If you're trying to make these modifications after the page has loaded, remember that PHP runs on the server-side, not the user-side. For that, you need Javascript.
you'll want to look up str_replace() on google. You can search an entire string and replace specified keywords simply.
Related
I have some large HTML code that I want to put in a PHP variable without losing the syntax highlight. I would also like for when it is put in as a variable, it will be shown as a normal string not HTML code.
Is there a way like:
<?php
$var =
?>
HTML GOES HERE
<?php
;
echo $var;
?>
I know my code here doesn't make sense, but it's just to describe the situation.
If the code is very long - say a menu div or something, you can use include. It won't give you a variable to use, but the result is the same.
<?php
include file_with_my_code.php;
?>
In file_with_my_code.php (doesn't have to be .php, .html works just fine as well) you simply paste the code as if you were creating a standalone html file.
Just found it!
$var = <<<HTML
<HTML GOES HERE>
HTML;
I absolutely don't post a question here in SO unless I really can't find a way to solve my problem myself. I did a lot of googling and was not able to find a solution for this one problem I am about to describe.
Here is the problem. I am creating a templated php website. With templated I mean something like below:
<?php include("header.php");?>
<div id="content">
<div id="main">
<h2><?php echo($page_title);?></h2>
<?php
echo ($page_content);
?>
</div>
<?php include("sidebar.php");?>
</div>
<?php include("footer.php");?>
As you can see here page template ECHOES the content of the $page_content variable between header and footer sections to build the page.
To keep the code clean and separated (in my own way) I have been placing the html content in .txt files (let's say page1_content.txt) and assigning the txt content to this variable ($page_content) as below:
$page_content = file_get_contents("page1_content.txt");
My problem starts when I place some php code in page1_content.txt, lets' call this file page2_content.php (yes, I change the file from .txt to .php). Then I assign the content of this file to $page_content variable as below as usual:
$page_content = file_get_contents("page2_content.php");
Now, when the page template ECHOES page2_content.php contents the php code in it is also echoed as string and not executed, but I am trying to query a database and do some stuff in this file with some php code. I mean, I want the php code inside page2_content.php to be executed and the cumulative html code to be echoed by the "echo" line inside the template file.
How can I achieve this?
Please ask me any questions if you need more info/clarification.
Thanks
EDİT:
As many people here suggested the solution was including the file. Actually, I tried including the file before but it didn't look like it was working, it broke my template, so I though I was on the wrong track and quit the "include" way of doing this. Since everybody here is advising to use include I tried that again. I replaced the php code in "page2_content.php" with a basic 1-line code just to see if it gets executed before adding generated html code without breaking the template and it worked. Apparently my php code had a problem at first place and hence broke my template execution.
Now I have changed the template structure slightly and pages using the template, and it seems to work nicely. Thanks a lot everybody. I have up-voted every answer suggesting that I use include :)
As #Ali suggested, you could include the files. The other option which I highly suggest you do not use is the eval() function.
I think what you want to do is to include your content PHP file, not echo it (as you are doing with header.php and footer.php).
echo($page_content);
Would become as below:
include("page2_content.php");
You've already done this in your footer and sidebar, just use include()
Rookie here, so please correct me if I have anything wrong.
So here's a snippet of my HTML:
<html><body>
<h2>Home Page</h2>
Welcome back <?= $fgmembersite->UserFullName(); ?>!
</body></html>
The function, $fgmembersite->UserFullName(), returns a string (100%, if I call the function within tags it prints out correctly). How do I get it to echo out in the HTML?
I think an alternative would be to echo the entire HTML code, and I think it'd work then, but I don't want to do it that way because I read somewhere that echoing all of your HTML is bad. Could somebody also confirm/deny that?
Right now, this is what shows on the site:
Welcome back UserFullName(); ?>!
No idea why
Thanks for your time!
I think you want the code to look like this...
Welcome back <?php echo $fgmembersite->UserFullName(); ?>!
This will ECHO the result of the function call.
What you are seeing is the result of the browser trying to parse the PHP. It is trying to treat <?= $fgmembersite-> as an unknown tag and then renders the rest as text.
There are two possible reasons for this:
You need to pass it through a PHP engine first.
You need to access the file through a web server which supports PHP and is configured to run your file through PHP when it is requested (typically this is done by using a .php file extension).
Note that installing a web server then double clicking a PHP file in your file manager isn't sufficient - the browser will just load the file from the file system. You need to type http://etc etc.
It is also possible that you have short_open_tag disabled (which is common and sensible) and are using PHP 5.3 or older (which isn't a great idea, 5.3 is still supported but it is the oldest branch that is).
If this is the case, your options are:
Upgrade PHP
Use <?php echo ... ?> instead of <?= ... ?>
Enable short_open_tag
Can't you just do
<?php echo $fgmembersite->UserFullName(); ?>
?
use it as follows:
<html><body>
<h2>Home Page</h2>
Welcome back <?php echo $fgmembersite->UserFullName(); ?>!
</body></html>
Do you have short_open_tag enabled on your server? You need to have that enabled to use that syntax. If you don't have that, use <?php echo $fgmembersite->UserFullName(); ?> like the other users suggested.
You can check the setting on you server by creating a file containing <?php phpinfo(); in it, and accessing that.
Also, echoing all your HTML inside the <?php tags are considered a bad practice because you should separate your business logic and your HTML. Echoing HTML directly from inside the PHP tags quickly leads to a mix of HTML and PHP, and it will be harder to read (for others, and yourself later on)
So I would have a template file called template.php and inside, it would have:
<html>
some other content
<?php $name ?>
</html>
Essentially, I want to pull the name from the database and insert it into $name and save that entire page as a new file.
So let say in the database, I had a name called Joe, the new file I create would have the following content inside:
<html>
some other content
Joe
</html>
The only issue I am having is finding the right functions to actually replace the variable from the template file, and being able to save it into a new file.
That's not how templates usually work. You should have a template file, substitute variables for their values, and display it to the user. You can cache these generated templates (the ones that are always the same) but you never make a new template file for each user and save it permanently. That makes managing and updating the application way more difficult than you want.
I recommend using a simple template system like RainTPL. That's what I use for most of my projects... it's very simple to use and provides all the basic functionality you would need.
You can also use just PHP for this... there are a few answers on SO that cover this so I won't get into it.
Using PHP as template engine
Using Template on PHP
Look at the answer I gave to this question a while back. There I explain how "variable parsing" usually works.
When I create a template loader I generally use output buffering with php include. This allows you to run the page as a php file without displaying its content before you are ready. The advantage to "parsing" your php files this way is that you can still run loops and functions.
Here's an example of how to use output buffering with PHP to create what you're wanting.
The Template template.php
<html>
some other content
<?php $name ?>
</html>
Where your database code and stuff is index.php
<?php
$name = 'John Doe';
if( /* some sort of caching system */ ) {
$parsed_template = file_get_contents('parsed_template.html');
}else {
ob_start();
include 'template.php';
$parsed_template = ob_get_clean();
file_put_contents('parsed_template.html', $parsed_template);
}
echo $parsed_template;
?>
I've been working on a small page in PHP, one that doesn't need the power of a full-fledged framework behind it. One thing that I'm really missing from previous work in Ruby-on-Rails is the ability to effectively pass content up the page using "content_for".
What I was wondering is, how could you create a page lifecycle that would accomplish this same effect in PHP?
So, here's a simple example:
Let's say you have a template that defines an index page, just a recurring header and menu you want to use on all your pages. So your index.php file looks basically like this:
...header stuff...
<body>
<?php include $file.'.php'; ?>
</body>
...footer stuff...
EDIT: Thanks for the tips on URL security, but let's just assume I'm getting the user request safely :)
Now, lets say in the header you want to put this:
<head>
<title><?php echo $page_title; ?></title>
</head>
It would be nice to be able to specify the title in the included file, so at the url http://example.com/index.php?p=test you're loading test.php, and that file looks like this:
<?php $page_title = 'Test Page'; ?>
... rest of content ...
Now, obviously this doesn't work, because the including page (index.php) is loaded before the variable is set.
In Rails this is where you could pass stuff 'up the page' using the content_for function.
My question is this: What would be the simplest, leanest way that you all can think of to effect this kind of 'content_for' functionality in PHP?
Ideally I'd like suggestions that don't involve strapping on some big framework, but some relatively light boilerplate code that could be used in a lot of different applications.
Never do include $_GET['p']. This opens a huge security hole in your site, as include accepts filenames and URLs, so anybody would be able to read any file on your site and also execute any code on your server. You may want to check and sanitize the value first.
If you need something simple, you may put header and footer in separate files, execute your test.php which would set the variables, capture its output using output buffering, then include the header, output the middle part and include the footer. Example:
<?php ob_start(); ?>
<body>
<?php include $filename.'.php'; ?>
</body>
<?php $content = ob_get_clean();
include 'header.php';
echo $content;
include 'footer.php';
?>
If I understand you correctly (I have not used RoR extensively), you could put your data in a variable or a function. If your content was in a variable, your "test.php" could simply hold all your variables and you could load it at the very beginning of your index file (likewise for a function depending on how complicated your needs are; if you're doing a lot of extra work, you may need to use a function as a variable won't work).
For example, your test.php would look something like this:
<?php
$page_title = "Test Page";
$page_content = "Some sort of content";
// Or
function page_content()
{
// Run some functions and print content at the end
}
?>
Then, in your 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...
This way everything should load properly. You could also split things up, but that would complicate your structure (especially if there is no need for an elaborate framework, this would be unnecessary).
Good luck!
Dennis M.
Are you worried about XSS? Or are you going to filter/whitelist the "filenames" from the query string?
My answer would be to use mod_rewrite -- if you're using PHP, you're likely using Apache!
You could filter out files with a RewriteCond and your RewriteRule could be:
RewriteRule /index.php?p=(.*)$ $1 [L,QSA]
This may be a different approach than the PHP functionality you were looking for, but it comes to mind...