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);
Related
I downloaded this code:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
// ADD SPECIFIC FILES YOU WANT TO IGNORE HERE
$ignore_file_list = array( ".htaccess", "Thumbs.db", ".DS_Store", "index.php", "flat.png", "error_log" );
// ADD SPECIFIC FILE EXTENSIONS YOU WANT TO IGNORE HERE, EXAMPLE: array('psd','jpg','jpeg')
$ignore_ext_list = array( );
// SORT BY
$sort_by = "name_asc"; // options: name_asc, name_desc, date_asc, date_desc
// ICON URL
//$icon_url = "https://www.dropbox.com/s/lzxi5abx2gaj84q/flat.png?dl=0"; // DIRECT LINK
$icon_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAAyCAYAAADP7vEwAAAgAElEQVR4nOy9d5hdV3nv";
// TOGGLE SUB FOLDERS, SET TO false IF YOU WANT OFF
$toggle_sub_folders = true;
// FORCE DOWNLOAD ATTRIBUTE
$force_download = true;
// IGNORE EMPTY FOLDERS
$ignore_empty_folders = false;
// SET TITLE BASED ON FOLDER NAME, IF NOT SET ABOVE
if( !$title ) { $title = clean_title(basename(dirname(__FILE__))); }
?>
Th full code can be download here: https://github.com/halgatewood/file-directory-list/blob/master/index.php
I'm having problem with the start:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
I want to put a picture as background, but it isn't happening. What's wrong?
Changed with the answer:
<?php
echo "<div style='background-image: url('/bg.jpeg');' ></div>";
?>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
etc..
No need for all that,
What you desire to achieve is much simpler.
Assuming this code is inside index.php and your server's directory structure:
/some-folder/
/index.php
/bg.jpeg
Simply link it as its done in plain html —
<?php
echo "<div style=\"background-image: url('/bg.jpeg');\" ></div>";
?>
If you wan't it do be dynamic, i.e, image files's name is inside a variable then,
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
Update:
Important Tip: All programming languages are executed line-by-line, this tip applies not only to PHP, but also HTML Learn More
Assume for example, your page's html structure returned to the browser is as provide below and you want to apply background to body tag
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Simply copying and pasting my code to the top of page will result in
<div style="background-image: url('bg.jpeg');" ></div>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
But that created a empty div tag at the top of html output, i wanted it to apply background to by body tag instead !!!?
— This happened because echo is used to send output to the browser as soon as it is executed. So since you copied my code to the top of your script the html output is also at the top.
But why did it echo <div style="background-image: url('bg.jpeg');" ></div> when i wanted it to apply to my page's body?
— Because the echo statements reads "<div style=\"background-image: url('bg.jpeg');\" ></div>"; as its output.
Ok, but how to apply the background-image to body then??
As mentioned earlier code is executed line-by-line, so in order to apply the style to pages's body tag you'll need to call it near your body tag and also modify it to not output the div it currently does.
So assuming your index.php is:
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
You'll need to change it to —
<?php
$my_image = 'bg.jpeg';
// don't echo any thing here
?>
<html>
<head><head>
<body style="background-image: url('<?php echo $my_image; ?>')">
<!-- apply the style to body -->
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Hopefully i explained it well :)
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');
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In my web application there are 4 pages (About.html, Register.html,Quiz.html,Topic.html ) in each page navigation, header and footer sections are same. Now I want to put all these sections into single php include() functions(not multiple php files )
Then you may create a file perhaps named template.php which contains:
function printHeader($arg=null) {
echo "<div class='header'>Here is your header contents!</div>";
}
function printFooter($arg=null) {
echo "<div class='footer'>Here is your footer contents!</div>";
}
and just call them appropriately in each page having the same template, for example in the "about" page:
include_once "template.php";
// ...
printHeader();
// ...
printFooter();
// ...
1) About.html, Register.html,Quiz.html,Topic.html rename them to .php.
2) add 'sections.php'
function addHeader(){
echo "THIS IS HEADER!!!";
}
function addFooter(){
echo "THIS IS FOOTER!!!";
}
function addSparta(){
echo "THIS IS SPARTA!!!";
}
3) in Topic.php(and other files) add
include_once 'sections.php';
4) use those functions to print out what you need.
But still its not very good way to compose your pages.
let's consider an index.php file
in that file:
<html>
<head>
<title><?php echo !empty( $_GET['page'] ) ? $_GET['page'] : 'Home'; ?></title>
<!-- head info -->
</head>
<body>
<ul id="menu">
<?php foreach( array( 'About', 'Register', 'Quiz', 'Topic' ) as $page ) : ?>
<li><?php echo $page; ?></li>
<?php endforeach; ?>
</ul>
<div id="content">
<?php if ( !empty( $_GET['page'] ) ) : ?>
<h2><?php echo $_GET['page']; ?></h2>
<?php
$content = file_get_contents( dirname( __FILE__ ) . '/' . $_GET['page'] . '.html' );
echo reset( explode( '</body>', end( explode( '<body>', $content ) ) ) );
else : ?>
*** home page (default) content goes here (or include it from a separate file too) ***
<?php endif; ?>
</div>
<div id="footer">
<hr />
This is the footer
</div>
</body>
</html>
you must understand that given the broad scope of your question, and the fact you are using HTML files, this solution is incredibly basic. but it answers your question and/or plants the seed for learning from here.
for example, using is_file() to check that the page actually exists.
I have a web in different languages. I make an include for the footer. The easiest way could be to have a different footer for each language. But is it possible to have just one footer and change the few sentences that are different in each language?
In all pages put the same include:
<?php include('footer.php'); ?>
Then, in the includes just change what is different. Something like:
<footer>
<?php echo $text; ?> <br><br>
</footer>
</body>
</html>
<?php
if ('<html lang="en">')
$text = 'Some text in English';
elseif ('<html lang="fr">')
$text = 'Français';
?>
(In each page I have the html lang= )
What is the better way to have a footer in different languages?
(I am just learning php, so please, just help me with the basics, where to begin)
Okay so first you need to create translation files for all languages you wish to support. Store them in "/lang/en.php" and "/lang/fr.php".
"lang/en.php"
<?php
return [
"title" => "My site",
"welcome" => "Welcome",
"goodbye" => "Goodbye"
]
?>
"lang/fr.php"
<?php
return [
"title" => "Mon site",
"welcome" => "Bienvenue",
"goodbye" => "Au revoir"
]
?>
Next, you include the appropriate language file in your php page:
"index.php"
<?php
$locale = $_SESSION['locale']; // this is "en" or "fr", depending on a choice the user made earlier
$lang = require("/lang/$locale.php"); // load "/lang/en.php" or "/lang/fr.php"
$user = $_SESSION['username']; // e.g. "Bart"
?>
<html>
<head>
<title><?php echo $lang['title']; ?></title>
</head>
<body>
<?php include('header.php'); ?>
<main>content</main>
<?php include('footer.php'); ?>
</body>
</html>
And in your header/footer you can just use $lang as well:
"header.php"
<header>
<p><?php echo $lang['welcome'] . ', ' . $user; ?></p>
</header>
It's important to know that you should include your language file only in pages that a user will view directly (i.e. don't include it in partial views like header.php)
You can create a poor man's translation function:
function translate($sentence, array $vars = null, $lang = 'en') {
static $table = array();
if ( ! isset($table[$lang])) {
$table[$lang] = require(ROOT."/lang/{$lang}.php");
}
$trans = isset($table[$lang][$sentence]) ? $table[$lang][$sentence] : $sentence;
if ( ! empty($vars)) {
$trans = strtr($trans, $vars);
}
return $trans;
}
You can then create some language files, such as:
<?php
// ROOT/lang/de.php
return [
'Welcome :name' => 'Willkommen :name',
'Thank you' => 'Danke',
];
And then in your scripts you can translate stuff:
<header>
<?php echo translate('Welcome :name', [':name' => 'Bob'], 'de') ?>
</header>
Instead of using a function you could also just include the language file and then use that.
<?php
// some-page.php
$lang = require(ROOT."/lang/{$_SESSION['user.lang']}.php");
$name = $_SESSION['user.name'];
?>
<header>
<?php echo str_replace(':name', $name, $lang['Welcome :name']) ?>
</header>
It will require you to do some more work, but if you find it to be more to your liking then okay.
You could set a session that contains the language such as:
<?php
session_start();
$_SESSION['language'] = "EN";
?>
Then in the footer:
<?php
switch($_SESSION['language']) {
case 'EN':
$sentences['site_slogan'] = "This is your site slogan";
$sentences['site_messag'] = "This is your site message";
break;
case 'FA':
$sentences['site_slogan'] = "This is your site slogan in FA";
$sentences['site_messag'] = "This is your site message in FA";
break;
}
echo $sentences['site_slogan'];
echo $sentences['site_messag'];
I have a .tpl file which contains the HTML code of my webpage and a .php file that I want to use the HTML code in it and replace some variables.
For example imagine this is my file.tpl:
<html>
<head>
<title>{page_title}</title>
</head>
<body>
Welcome to {site_name}!
</body>
</html>
and I want to define {page_title} and {site_name} in my php file and display them.
One way we can do this is to load the page code in a variable and then replace {page_title} and {site_name} and then echo them.
But I don't know that it's the best way or not because I think there will be some problem if the .tpl file is large.
Please help me to find the best way. Thanks :-)
One way you could do it:
$replace = array('{page_title}', '{site_name}');
$with = array('Title', 'My Website');
$contents = file_get_contents('my_template.tpl');
echo str_replace($replace, $with, $contents);
Update: removed include, used file_get_contents()
Cause I searched for this and found this article I will provide my solution:
$replacers = [
'page_title'=> 'Title',
'site_name' => 'My Website',
];
echo preg_replace("|{(\w*)}|e", '$replacers["$1"]', $your_template_string);
You have to get your Template to a String.
For example with
file_get_contents(),
ob_start();
include('my_template.tpl');
$ob = ob_get_clean();
or anything like this.
Hope this will help!?
Here is simple example hope this will work
Your HTML :
<?php
$html= '
<div class="col-md-3">
<img src="{$img}" alt="">
<h2>{$title}</h2>
<p>{$address}</p>
<h3>{$price}</h3>
Read More
</div>
';
?>
Your Array with you want to replace
<?php
$content_replace = array(
'{$img}' => 'Image Link',
'{$title}' => 'Title',
'{$address}'=> 'Your address',
'{$price}' => 'Price Goes here',
'{$link}' => 'Link',
);
$content = strtr($html, $content_replace );
echo $content;
?>
As you mention you can read the file into a string and replace your markers, alternatively you can include the file but in such case rather than use markers insert php fragments to echo the variables like:
<html>
<head>
<title><?php echo $page_title ?></title>
</head>
<body>
Welcome to <?php echo $site_name ?>!
</body>
</html>
In such case you don't need to run str_replace on the whole template. It also alows you to easily insert conditions or loops in your template. This is the way I prefer to handle things.
I use something similar to the above but I am looking for a better way of doing it as well.
I use this:
$templatefile = 'test.tpl';
$page = file_get_contents($templatefile);
$page = str_replace('{Page_Title}', $pagetitle, $page);
$page = str_replace('{Site_Name}', $sitename, $page);
echo $page;
sorry to bring up an answered thread but I am looking at finding better ways to do this.
I am currently playing with jQuery to do this too so I can have dynamic pages without the full reload. For example:
<div id="site_name"></div>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'data.php',
data: {
info: 'sitename'
}
success: function(data){
$('#site_name').html(data);
//the data variable is parsed by whatever is echoed from the php file
}
});
</script>
sample data.php file:
<?php
echo "My site";
?>
Hope this might help others too.