PHP file_get_contents(file.php); execute PHP code in file - php

I'm currently having an issue, where I have some php code in a file and calling that file from another file.
so:
index.php is calling file.php and file.php has some php code in it.
The reason I'm using file_get_contents, is that I have code in index.php that only needs to read some of the content in file.php, designated by tags. Based on teh section tag trigged by the ($_GET['identifier']); that section within the file.php is the only section displayed
Example code in file.php:
<?php
//simplified php code
var $item = "hello";
var $item2 = "Hola";
var $item3 = "おはよ";
?>
<section id="content">
<?php echo $item1; ?>
</section>
<section id="content2">
<?php echo $item2; ?>
</section>
<section id="content3">
<?php echo $item3; ?>
</section>
?>
code in index.php:
$content = file_get_contents('file.php');
if (isset($_GET['item'])) {
$section = $_GET['item'];
} else {
$section = 'content';
}
$delimiter = '<section id="' . $section . '">';
$start = explode($delimiter, $content);
$end = explode("</section>", $start[ 1 ] );
echo $end[0];
so if the browser url shows index.php?item=content2 , it should show the content from section ID named content2, along with the PHP code in that file, executed.
currently, if I do this, nothing is displayed, and a view source, show the php code

To execute the code before you get the contents, you either need to include and capture the output:
ob_start();
include('file.php');
$content = ob_get_clean();
Or get the file by URL (probably not the best idea and not portable):
$content = file_get_contents('http://example.com/file.php');

Related

Recieve Variable From php file Using fopen?

I've been working on a blogging system and I wish to receive information from external php files for a post's Title and Content, here is my code:
External (Blog Post's Content) File: 03-20-2018-This-Is-A-Test.php
<?php
$Title = 'This is a test!';
$Date = '03-20-2018';
$Content = 'Blog Post's content!';
?>
Client Side Page For Viewing Blog Posts: Post Home.php
<?php
$Title = '';
$Date = '';
$Content = '';
$GetDate = $_GET['d'];
$GetTitle = $_GET['t'];
$postPath = "Posts/$GetDate"."-"."$GetTitle.php";
$postFile = fopen($postPath,"rt");
$postContent = fgets($postFile,filesize($postPath));
?>
<!--Some HTML-->
<h2><? echo $Title; ?></2>
<b><? echo $Date; ?></b>
<p><? echo $Content; ?></p>
<!--Some More HTML-->
<? fclose($postFile); ?>
Client's Page URL: example.com/Post%20Home.php?d=03-20-2018&t=This-Is-A-Test
Reformatted as: example.com/03-20-2018/This-Is-A-Test
As you can see, I am using GET parameters to call the file that I wish to collect the information from.
I have tried using fopen which I wasn't able to get to work. Also include is forbidden with the particular server hosts I am using.
I am open to using file_get_contents if someone is able to help me get it to work.
Note: I have confirmed that my calling URL is correct and I get no errors from my php
So, I am trying to use fopen to collect the data of $Title $Date $Content from the file; 03-20-2018-This-Is-A-Test.php and use that information in the Client Side file; Post Home.php
I was able to find the answer using require().

PHP Read Variables from a second page (NOT get / post)

I am sure this is answered on this forum but I can't find the answer so here goes:
I have a webpage template.php. It has lot of code but in between there is:
<!-- Hero Content -->
<div class="home-content">
<div class="home-text">
<h1 class="hs-line-8 no-transp font-alt mb-50 mb-xs-30"> DISCOVER </h1>
<h2 class="hs-line-12 font-alt mb-50 mb-xs-30"> <?php echo $saved_data['title']; ?> </h2> <?php echo "<img src='$saved_data['builderimagepath']'>"; ?>
<div class="local-scroll"> Register <span class="hidden-xs"> </span> Learn More </div>
</div>
</div>
<!-- End Hero Content -->
Key lines are:
<?php echo $saved_data['title']; ?>
<?php echo "<img src='$saved_data['builderimagepath']'>"; ?>
Now the second web page read.php wants to read the variable names being used. Hence I want to know how to get "title" and "builderimagepath" in an array in read.php.
( I can rename the variables as a key or as a multi-dimensional array in template.php )
In read.php, this is what I have so far:
<?php
$url = 'index.php';
$content = file_get_contents($url);
$first_step = explode( '<?php echo $saved_data' , $content );
$second_step = explode("']; ?>" , $first_step[1] );
echo $second_step[0]; // Will Add to array to process
?>
We are NOT passing variables through GET / POST from template.php to read.php , but read.php wants to get it in an array. What I want to know:
1) Is there a better approach?
2) What is the best way to name variables in template.php , so its easier to access and process in read.php?
I don't think its relevant but $saved_data is an array coming from a file:
<!DOCTYPE html>
<?php
// Read from file
if (empty($_GET['file'])) {
// Use default file:
$filename = 'mydata.txt';
$saved_raw_data = file_get_contents($filename);
$saved_data = unserialize($saved_raw_data);
} else {
$saved_raw_data = file_get_contents($_GET['file']);
$saved_data = unserialize($saved_raw_data);
}
?>
In the file that you want to store the variables, return the values as an array and you can catch them in another file when including into a variable.
template.php
return [
'var1' => 'value',
'var2' => 'value2
];
read.php
$variable = include('template.php');
print_r($variable);

open file and load text using php

I'm writing code and found a problem in taking data from file using php. So the goal is to take information from txt file and create div blocs. SO here I have on problem and one question, I hope that you can help me with that.
So here is a problem - I open a file and start reading but some how it is continue reading file even if it is empty. It is can not stop.
here is a code -
<?php
$flis = fopen ("users/".$IDN."/list.txt",'r');
$f= 1;
while (!feof($flis))
{
$CID = fgets ($flis, 99);
echo $f;
$f++;
}
fclose($flis);
?>
So I planing have a file with a lot of strings but it can not stop reading even an empty file, Please help me to find a mistake.
Also in while I planing to create a new block div . so here is a new question- how is better to create a div block? I use printf like that -
printf ("
<div id=\"message_contact\">
<a>
<div id=\"conto\">
</div>
</a>
</div>
");
But the problem is that the block will be a complex and plus it suppose to be a php function inside the block to put the information inside from database to that block. So can u recommend other methods to realize it?
Use foreach, Luke! And also file_get_contents and explode.
<?php
$path = 'users/' . $IDN . '/list.txt';
$contents = file_get_contents($path);
$lines = explode("\n", $contents);
?>
<div id="message_contact">
<?php
foreach ($lines as $line)
{
?>
<a>
<!-- DIV inside A? Okay! -->
<div id="conto">
<?php echo trim($line); ?>
</div>
</a>
<?php
}
?>
</div>
Note how I called trim() inside <div>. Poof, PHP inside HTML!
Edit, line by line
<?php
$flis = "users/".$IDN."/list.txt";
$fc = file_get_contents($fils);
$fca = explode("\n", $fc);
foreach ($fca as $line) {
echo $line;
// OR
include('template.php');
}
?>
template.php:
<div id="message_contact">
<a>
<div id="conto">
<?php echo $line; ?>
</div>
</a>
</div>
How's that?

basic variable scope in php

Using MVC I have a model directory inside of which are two files; menu.xml and the following model.php.
<?php
$xml = simplexml_load_file('menu.xml');
print_r ($xml);
?>
In my views directory I have an index.php files as follows:
<?php
include '../model/model.php';
print_r($xml);
foreach ($xml->children() as $option)
{
?>
<li><a href='<?= $option->getName() ?>'><?= $option['name'] ?></li>
<?php
}
?>
</ul>
In another directory - this time html - i have the following:
<!-- This is the controller -->
<?php
require_once('../includes/helpers.php');
// determine which page to render
if (isset($_GET['page']))
$page = $_GET['page'];
else
$page = 'index';
// show page
switch ($page)
{
case 'index';
render('templates/header', array('title' => 'Main Menu'));
render('index');
render('templates/footer');
break;
}
?>
This is supposed to show a list of the children of the menu.xml file. If I access model.php directly:
<pre>
<?php
$xml = simplexml_load_file('menu.xml');
print_r ($xml);
?>
</pre>
I can see the contents of the $xml object.
So why doesn't the include '../model/model.php command work?
Any tips appreciated!
Thanks
$xml = simplexml_load_file('menu.xml');
This path is relative to the current executed script. That’s why it works when your accessing model/model.php directly, but not when including it from ./index.php. Use absolute path instead:
$xml = simplexml_load_file(__DIR__ . '/menu.xml');
Edit by IMSoP:
For PHP versions older than 5.3:
$xml = simplexml_load_file(dirname(__FILE__) . '/menu.xml');

How to change title of the page after including header.php?

page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
<title><?php echo $title; ?></title>
I want my title to be set after including the header file. Is it possible to do this?
expanding on Dainis Abols answer, and your question on output handling,
consider the following:
your header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
and that should do it.
EDIT
I believe Guy's idea works better since it gives you a default if you need it, IE:
The title is now <title>Backup Title</title>
Code is now:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
1. Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
2. Add following code into header.php
<title><?php echo $title; ?></title>
What you can do is, you store the output in a variable like:
header.php
<?php
$output = '<html><title>%TITLE%</title><body>';
?>
PS: You need to remove all echos/prints etc so that all possible output is stored in the $output variable.
This can be easely done, by defining $output = ''; at the start of the file and then find/replace echo to $output .=.
And then replace the %TITLE% to what you need:
<?php
include("header.php");
$title = "TITLE";
$output = str_replace('%TITLE%', $title, $output);
echo $output;
?>
Another way is using javascript in your code, instead of:
<title><?php echo $title; ?></title>
Put this in there:
<script type="text/javascript">
document.title = "<?=$title;?>"
</script>
Or jQuery, if you prefer:
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "<?=$title;?>");
});
</script>
Expanding a little on we.mamat's answer,
you could use a preg_replace instead of the simple replace and remove the need for a %title% altogether. Something like this:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
you can set using JavaScript
<script language="javascript">
document.title = "The new title goes here.";
</script>
Add this code on top your page
<?php
$title="This is the new page title";
?>
Add this code on your Template header file (include)
<title><?php echo $title; ?></title>
It's very easy.
Put this code in header.php
<?
$sitename = 'Your Site Name'
$pagetitle;
if(isset($pagetitle)){
echo "<title>$pagetitle." | ". $sitename</title>";
}
else {
echo "<title>$sitename</title>";
}
?>
Then in the page put there :
<?
$pagetitle = 'Sign up'
include "header.php";
?>
So if you are on Index.php , The title is Your Site Name.
And for example if you are on sign up page , The title is Sign up | Your Site Name
Every Simple just using a function , I created it .
<?
function change_meta_tags($title,$description,$keywords){
// This function made by Jamil Hammash
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/","<meta name='description' content='(.*)'>","<meta name='keywords' content='(.*)'>");
$replacements = array("<title>$title</title>","meta name='description' content='$description'","meta name='keywords' content='$keywords'");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
First of all you must create function.php file and put this function inside ,then make require under the MetaTags in Header.php .
To use this function change_meta_tags("NEW TITLE","NEW DESCRIPTION",NEW KEYWORDS); .
Don't use this function in Header.php !! just with another pages .
Use a jQuery function like this:
$("title").html('your title');

Categories