Using str_replace and include together (php) - php

I have a footer in a web page, the footer is called footer.php. I'd like the footer to have a different image depending on other variables. I want to do something like this:
if (x=1) {include (str_replace('logo1.jpg','logo2.jpg','footer.php'));}
else
{include 'footer.php';}
But this doesn't work, it just does a regular include. Is there a way to replace text in files while including them?

Use something like:
if (x==1) {
$image='logo1.jpg';
} else {
$image = 'logo2.jpg';
}
include('footer.php');
////footer.php
echo "<img src='".$image."'/>";
Basically, what you had would try to do the replace on the string 'footer.php', not the file itself. The appropriate approach here would be to use a variable for your image and have the footer use that variable when supplying the image.

Is there a way to replace text in files while including them?
Yes there is, but your included file would have to return its contents.
footer.php
<?
return "<img src='#image'>";
?>
then you can do
echo str_replace("#image", "image.jpg", include("footer.php"));
there's nothing wrong with this but it feels slightly weird, though.
If I were you, I would have the include() just work with a pre-set variable as Jonathan Fingland proposes, or fetch the contents of a footer file like Tomas Markauskas proposes.

Your example isn't working because you're replacing 'logo1.jpg' with 'logo2.jpg' in the string 'footer.php'. The result of the replacement is still 'footer.php' and then you're just including a file with the name that matches your string.
If you really need to replace a string in a php file and execute it afterwards, you could do something like this:
$file = file_get_contents('footer.php');
$file = str_replace('logo1.jpg', 'logo2.jpg', $file);
eval($file);
But there are better ways to achieve what you want (see answer from Jonathan Fingland for an example).

Related

Adding and styling external file

There is a file on another site that I do not own, with a URL in the following format:
http://example.com/path/with/some/variables
I want to include this file in one of my own pages. I could use iframe to do this, but I also want to change the CSS of something within the included file. To my knowledge, I can't do this with this method.
However, I can't seem to be able to successfully add this via PHP either, with something like:
<?php include 'http://example.com/path/with/some/variables'; ?>
I'm not sure what other methods exist that can do this, but surely this must be possible.
Also, I'm aware of the security implications of using include in a situation like this.
Use readfile:
<?php readfile('http://example.com/path/with/some/variables'); ?>
Yeah, security limitations won't allow you do do this directly in an iframe, by manipulating the DOM of the iframed file.
To do it in PHP, you could create a PHP script to read the contents of the URL and add an external CSS file that you've created, to override whatever you want. So:
myreader.php:
$contents = file_get_contents("http://example.com/path/with/some/variables");
$contents = preg_replace("/<head>/", "<head>\n<link rel='stylesheet' type='text/css' href='mystyle.css'>", $contents, 1);
echo $contents;
and then create mystyle.css:
body {
color : red !important;
}
Finally, either just point your browser to myreader.php, or if you still want it in an iframe, point the iframe src to myreader.php.
PS: Stealing is wrong :)
You can use file_get_contents
<?php $content = file_get_contents('http://example.com/path/with/some/variables'); ?>
Here is the documentation file_get_contents

PHP include absolute path

I have a variable on my site called $basePath which is set as:
$basePath = '/Systems/dgw/';
I am using it on all my css, js and images tags as so (shortened for better visibility):
<link href="<?php echo $basePath; ?>include/assets/css/bootstrap.min.css">
I have no problem with those includes and they work fine in wherever file and in whatever folder I am.
I have a certain included page which has the following line:
<img src="<?php echo $basePath; ?>images/new_logo.png" alt="logo"/>
And the image shows just fine. The line after it states:
<?php include($basePath.'include/assets/common/topMessages.php');?>
But the include doesn't happens. When I try it like this:
<?php include('../../include/assets/common/topMessages.php');?>
It works.
Anybody has any idea what could be wrong?
You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
?>
If your server doesn't populate the "document_root", you may need this
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");
I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.
For example, let's say i have this file tree:
domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php
I can include the functions.php file from wherever i am, just by copy pasting
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");
If you need to use this code many times, you may create a function that returns the "str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))" part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named "path_back"):
require(path_back()."/_resources/another_php_file.php");
You can add an include_path = ".:/home/myuser/mysite.com/" to your php.ini or you can add something like this into your script before the include or require:
set_include_path(get_include_path() . ":/home/myuser/mysite.com/");
The first one will work for all the scripts running in your website.
The second option will only work for the script which has the setincludepath on the code, for the rest of the application it will not work unless you have an object you call in every script that add the setincludepath.

str_replace (or another option) for replacing content located inside a php document

I'm attempting to make a template file for a CMS that I'm making where the template file can contain variables like {username} as regular text that get replaced when the page gets included on the index.php page.
Example:
Index Page:
<?php include('templates/123/index.php'); ?>
templates/123/index.php page
<?php include('header.php'); ?>
Welcome {username}
<?php include('footer.php'); ?>
I've tried several methods; however, always run into problems because the page I'm trying to change the content on includes PHP code. Every method I try either 1) messes up because the opening and closing of PHP tags within the document OR 2) just echoes out the PHP code in the document. Is there any way that I can still achieve this? Maybe even with a class of some kind? I just want to be able to achieve this safely.
I will also be using this to where custom variables like {content1} get replaces with a php code that will be ioncubed that retrieves the data from database for content located in column1, same with {column2} {column3} and {column4}. I'm just trying to make the creation of templates extremely easy. (so I'd like to make the code work for that as well)
My preferred method of doing stuff like this involves starting my code with:
ob_start(function($c) {
$replacements = array(
"username"=>"Kolink",
"rank"=>"Awesome"
);
return preg_replace_callback("/{(\w+)}/",function($m) use ($replacements) {
return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
},$c);
});
Two steps I suggest
Load the result of your file "templates/123/index.php" into a variable. see this link for how to do it assign output of execution of PHP script to a variable?
use strtr() function to replace your placeholder i.e {username} with actual values
I think this will server your needs.

Include a php file without displaying its contents

Is it possible to include a php file without including its contents? I just want to access the functions and variables in that file without displaying any content. I tried this
<?
ob_start();
include('$file');
ob_end_clean();
?>
But this will hide only contents in php tag. I want to know how to hide others as well.
How to hide? Redesign your solution and separate your concerns! Do not mix logic with UI and so on.
Maybe you should apply the MVC or similar pattern(s).
While I totally agree with Peter's answer
I just tried this because I've never tried it before..
File toinclude.php:
<p>Loads of text</p>
<?php
function my_test()
{
echo 'Hello';
}
?>
Ooh a link
File includer.php:
<?php
ob_start();
include('toinclude.php');
ob_end_clean();
my_test();
?>
And it does work!
Output:
Hello
No you can't.
Include is meant to execute everything inside the file, there are no ways to prevent execution of some part of the file.
The only way is to edit the included file.
If your file is not printing any output You may try eval($fileContent).

PHP file print its own content

Is it possible for PHP file to print itself, for example <?php some code; ?> that I get output in HTML as <?php some code; ?>(I know its possible in c++), if not is it possible to actually print html version of php code with nice formatting and colors such as from this url inside code container http://woork.blogspot.com/2009/07/twitter-api-how-to-create-stream-of.html. OR from this website when you press code, while posting your example your code gets wrapped or whatever term is for that, makes it distinguishable from other non-code text. tnx
Yes.
<?php readfile(__FILE__)
__FILE__ is a magic constant that contains the absolute filesystem path to the file it is used in. And readfile just reads and prints the contents. And if you want to have a syntax highlighted HTML output, try the highlight_file function or highlight_string function instead.
I'm not sure if this is exactly what you want but you can print a file using:
echo file_get_contents(__FILE__);
or syntax-highlighted:
highlight_file(__FILE__);

Categories