How to embed PHP inside a text file to include later? - php

I have a simple template created through my ClassPage. The class gets called and reads html code from a text file. Inside the navigation I want to echo a PHP variable but all I am getting is the embedded php commented out on the browser's console?
I'm thinking perhaps the file that gets read isn't being processed by the server and that is why the php isn't being processed? Or I'm missing something really simple?
Heres the code:
ClassPage -> getBody which gets the file called "superNav.txt". The string that gets returned is put together with the needed HTML head tags etc then outputted.
private function getBody() {
$text = "";
if ($this->specialUser) {
$text .= file_get_contents("Template/superNav.txt");
} else {
$text .= file_get_contents("Template/userNav.txt");
}
return $text;
}
This is the Text File:
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span id="glyph" class="glyphicon glyphicon-th-large"></span></button>
<a class="navbar-brand" href="#"><img alt="brand" id="brandLogo" src="Images/logo.png"></a>
<p id="navbarText" class="navbar-text">Webmin</p>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>Home</li>
<li>Rota</li>
<li>Rota Admin</li>
<li>User Admin</li>
<li>Archive</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span><?php echo $user->getName(); ?></li>
<li><span class="glyphicon glyphicon-log-out"></span> Log Out</li>
</ul>
</div>
</div>
</nav>
This is the line that is giving me an issue:
<li><span class="glyphicon glyphicon-user"></span><?php echo $user->getName(); ?></li>
The php does not get shown to screen, the browsers console shows that the code is commented.
Any help is welcomed. Thanks in advance!

For this first get the content from the .txt file and then do something like this :
$name = $user->getName();
$text = file_get_contents("Template/superNav.txt");
$text = str_replace('USERNAME', $name, $message);
$text$message = str_replace('logo_url', $base_url, $message);
and in your .txt file replace the php value with some Constants.
like this
<li><span class="glyphicon glyphicon-user"></span>USERNAME</li>
So here you can see we have replaced the value of USERNAME with dynamic value. Hope it helps!!!

file_get_contents does not execute php, as you have discovered.
Instead you can use output buffering and include.
You will also need to make sure $user is in scope for the getBody method as include inherets its scope from the calling block.
In this example i have used a made up method to illustrate that:
private function getBody()
{
//create local user variable somehow
$user = $this->getUser();
//start buffer
ob_start();
if ($this->specialUser) {
include "Template/superNav.txt";
} else {
include "Template/userNav.txt";
}
//return contents of buffer as string
return ob_get_clean();
}

Related

PHP Directory Scope

I'm facing a pretty particular problem, basically I'm tryng to create an header in my PHP project. I put my navbar into the "View" folder, and I'm including it with require in each page that I need to use it, I do the same thing with my head, that includes stylesheet and other stuff... Basically the problem is when I try to call the head/the navbar all the relative paths that I used in my 2 files get messed up, since when I call them I'm into another folder. I found three different solutions, and the one who seems to be the best doesn't work.
(I would rather not to use js, if there's any other good solution)
1 Solution that I tried:
I used absolute PATHS, it works, but it doesn't seem right to me, first of all, the file is not going to work in other computers, but only in mine, and it doesn't seem to be a correct approach to the problem. (But then I thought about creating a constant that contains the path of the folder which contains the project, but there's a problem, how do I make that constant to be accessible from every single file in the project? Since when I create it, it's not global.
2 Solution that I tried:
This one is kinda tricky, I basically tried to make a function that generates the entire navbar
<?php
include_once(PATH.'/functions/relpath.php');
function getNavbar($currentPage, $isInsert, $inserimenti){
$navbar = "
<nav class='navbar navbar-expand-md navbar-dark bg-dark fixed-top'>
<div class='container-fluid'>
<a class='navbar-brand' href='#'>Libreria</a>
<button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#navbarsExampleDefault' aria-controls='navbarsExampleDefault' aria-expanded='false' aria-label='Toggle navigation'>
<span class='navbar-toggler-icon'></span>
</button>
<div class='collapse navbar-collapse' id='navbarsExampleDefault'>
<ul class='navbar-nav me-auto mb-2 mb-md-0'> ";
if($isInsert){
//Nel caso in cui ci troviamo in una pagine di inserimento
$pathhome = getRelativePath($_SERVER['PHP_SELF'],PATH.'/index.php');
$pathtabella = getRelativePath($_SERVER['PHP_SELF'],PATH.'/src/tabelle.php');
$navbar.= "
<ul class='navbar-nav me-auto mb-2 mb-md-0'>
<li class='nav-item'>
<a class='nav-link' href='".$pathhome."'>Home</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='".$pathtabella."'>Tabelle</a>
</li>
<a class='nav-link dropdown-toggle active' href='#' id='dropdown01' data-bs-toggle='dropdown' aria-expanded='false'>Inserisci</a>
<ul class='dropdown-menu' aria-labelledby='dropdown01'>
";
foreach($inserimenti as $key => $value){
$relpath = getRelativePath($_SERVER['PHP_SELF'],PATH.'/'.$value);
$navbar.= "
<li><a class='dropdown-item' href='".$relpath."'>".$value."</a></li>
";
}
$navbar.="
</ul>
</li>
</ul>
</div>
</div>
</nav>
";
}else{
//Nel caso in cui ci troviamo in un altra pagina, non di inserimento
$pathhome = getRelativePath($_SERVER['PHP_SELF'],'/progetti/www/Informatica/Marzo2021/ProgettoLibreria/index.php');
echo("PHP SELF: ".$_SERVER['PHP_SELF']."\n PATH ABS: ".PATH.'/index.php'."\n Path Generata da Funzione ".$pathhome);
$pathtabella = getRelativePath($_SERVER['PHP_SELF'],PATH.'/src/tabelle.php');
if($currentPage=="index.php"){
$navbar.= "
<ul class='navbar-nav me-auto mb-2 mb-md-0'>
<li class='nav-item'>
<a class='nav-link active' aria-current='page' href='".$pathhome."'>Home</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='".$pathtabella."'>Tabelle</a>
</li>
<a class='nav-link dropdown-toggle' href='#' id='dropdown01' data-bs-toggle='dropdown' aria-expanded='false'>Inserisci</a>
<ul class='dropdown-menu' aria-labelledby='dropdown01'>
";
}else{
//Dovrebbe quindi essere la tabella
$navbar.= "
<ul class='navbar-nav me-auto mb-2 mb-md-0'>
<li class='nav-item'>
<a class='nav-link' href='".$pathhome."'>Home</a>
</li>
<li class='nav-item'>
<a class='nav-link active' aria-current='page' href='".$pathtabella."'>Tabelle</a>
</li>
<a class='nav-link dropdown-toggle' href='#' id='dropdown01' data-bs-toggle='dropdown' aria-expanded='false'>Inserisci</a>
<ul class='dropdown-menu' aria-labelledby='dropdown01'>
";
}
foreach($inserimenti as $key => $value){
$relpath = getRelativePath($_SERVER['PHP_SELF'],PATH.'/'.$value);
$navbar.= "
<li><a class='dropdown-item' href='".$relpath."'>".$value."</a></li>
";
}
$navbar.="
</ul>
</li>
</ul>
</div>
</div>
</nav>
";
}
return $navbar;
}
?>
In this function, I call another function that I copied from another guy that essentially, outputs the relative path if you give to it the absolute path of your current folder, and the absolute path of the folder that you want to go to. As follows
<?php
function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
?>
The third solution is the one that I thought to be the best pick, basically I wanted to use the function chdir(), to change the working folder. Essentialy, when I'm into a file that is inside a folder i use the command chdir('..') in order to get into the main folder, and then I could use the relative paths as if I was out of that folder. Put apparently it doesen't work as planned at all, since it still doesn't work!! The relative paths inside the head and the navbar act as if they where into a folder, even if the working folder changed... I'm desperate at this point.
This is the page inside a folder, don't minnd the paths that I wrote, it's for debug, but as you can see, it doesn't load the css that is inside the head
And when I click on a link of the navbar, it acts like I'm into a folder
when I click home, it should go into index.php, but out of the folder, not inside src
The last thing that I send is the folder structure that I have, It's not complete, but at least you can see the interested part. Consider that the navbar and the head is into the view file, while the pages of the website are into src
File structure
If you need more details about the problem, or anything else, ask me. Thanks in advance for the help, if you have other solutions apart from solving the ones that I tried, it would be very nice, I'm sorry if I made some grammar mistakes or anything else, since my spaghetti Italian English could be a bit rusty.

how do I split this php file into MVC format?

i'm learning to program in OOP MVC,
I have this code for a simple nav menu:
<?php
$directory = "views";
$scannedDirectory = glob("$directory/*.php");
function uppercaseSpace($str) {
$re = '/(?=[A-Z][a-z])(?<!^)|(?=[A-Z])(?<=[a-z])/m';
$subst = ' ';
$result = preg_replace($re, $subst, $str);
return $result;
}
?>
<div id="header2">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" href="http://<?php echo $HOST ?>">Home</a>
</li>
<?php foreach ($scannedDirectory as $key => $value) {
$articleName = substr($value,6,-4);
printf('
<li class="nav-item">
<a class="nav-link active" href="?page=%s">%s</a>
</li>
',$articleName, ucfirst(uppercaseSpace($articleName)));
} ?>
</ul>
</nav>
</div> <!-- /header -->
I have a function in the php file so I could make a class navmenu.class and make a method of this function and put the frist 2 lines in the class as a property and the last html part becomes a view right?
but is this class a model or is it a controler?
here is a screenshot of my current file structure:
Is it worth to split this small code into MVC?
This file is now put in the subfolder includes because I am including the nav menu in my script.
Models are for database, View to render html, Controllers to handle a request
Beside that you can have helper classes and core classes
Follow some tutorials on how to create a mvc.
https://www.youtube.com/watch?v=OsCTzGASImQ&list=PLfdtiltiRHWGXVHXX09fxXDi-DqInchFD
https://www.youtube.com/watch?v=rkaLJrYnpOM&list=PLFPkAJFH7I0keB1qpWk5qVVUYdNLTEUs3
I followed the one of Curtis Parham he explained everything very well. After completing his tutorial I modified his framework alot by including composer, twig and changed the routing on how to handle variables and multiple languageses.

Bootstrap dropdown stop working after php die

Hi i have a script in which there are bootstrap dropdowns. The code for it is as follows:-
<ul class="nav navbar-nav navbar-right">
<li class="dropdown dropdown-user" style="font-size:15px;">
<a class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-user"></i> <span><?php echo $name; ?></span> <i class="caret"></i></a>
<ul class="dropdown-menu dropdown-menu-right width-220">
<li><i class="icon-lock2"></i> Change Password</li>
<li><i class="icon-switch2"></i> Logout</li>
</ul>
</li>
</ul>
Now i run a php script after a form is submitted in which i am checking whether a table is there in the database or not. If it is there it fethces it and if it is not there php script dies. The code for it is below:-
<?php
if(isset($_POST['submit']))
{
$sql="SELECT * FROM table1";
$results = $con->query($sql);
if ($results === FALSE) {
echo "<script> noty({text: 'No Data Found',layout: 'topRight',timeout: 3500,closeWith: ['click', 'hover'],type: 'error'});</script>";
die();
} else {
........
}
Now whenever the php script dies the dropdowns stop working.
I am just starting to learn php so please let me know what I am doing wrong or if there is a better way of looking at this problem. Any help is highly appreciated.
Check if you included bootstrap js file at the end of your page.
So when PHP dies, The bootsrap will not be loaded to the page. If its the reason change die with something else or move bootstrap js file to header.
PS:Besides use die whenever something goes wrong is not the best idea to handle errors.

How do you pass a A HREF value from a php function?

So with this code we pull in some data from a mysql database with php. Then everything works, except the a href formatting (for bootstrap). This code is really long, so I tried to get the parts that pertain to the problem.
The drop down works great when it isn't part of this function and all the data pulls through like it should. The function somehow throws out the bootstrap class, id, role, etc. in a href.
function menu_element_builder($values) {
$links = '';
foreach($values as $value) {
if(is_array($value['args'])) {
$links .= (!empty($value['href']))?'
/* this a href part doesn't pull through the ID, Role, data-toggle, or class */
<a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" href="'.$value['href'].'">'.$value['name'].'<span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">':'
<li class="dropdown-submenu">
'.$value['name'].'
</li> //it has more than this, keeping it simple
</ul>
return $links;
}
(an array of $link values are listed)
//This is part of case break statements to know which icons to load
$themed_elements = menu_element_builder($link_values);
<html>
<body>
<div class="dropdown">
<?php echo $themed_elements; ?>
</div>
</body>
</html>
old code
function menu_element_builder($values) {
$links = '';
foreach($values as $value) {
if(is_array($value['args'])) {
$links .= (!empty($value['href']))?'<li><a class="dir" href="'.$value['href'].'">'.$value['name'].'</a><ul>':'<li><span class="dir">'.$value['name'].'</span></li></ul>';
<script type="text/javascript">
$(function(){
$(".dir").click(function(){
//this.addclass('ul.dropdown li:hover');
});
});

Session variable being written over by the next variable in the session array

Ok I have a navbar link which upon click goes to language.php.
My code for my navbar which is located in a seperate view folder views/header/header2.php.
<?php
$_SESSION['from'] = $_SERVER['REQUEST_URI'];
?>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" style="position:top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" class="sr-only"><img src="images/dp.png"></button>
<a class="navbar-brand" href="index.php">
<img src="views/images/cp.png" title="###.###" alt="logo" width="90px" height="48px" style="padding-top:2px"></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user" ></span> <?php echo HEADER_PAGE; ?></li>
<li><span class="glyphicon glyphicon-search"></span> <?php echo HEADER_SEARCH; ?></li>
<li><span class="glyphicon glyphicon-plus"></span> <?php echo HEADER_POST; ?></li>
<li><span class="glyphicon glyphicon-edit"></span> <?php echo HEADER_COMMUNITY; ?></li>
<li><span class="glyphicon glyphicon-cog"></span> <?php echo HEADER_EDIT; ?></li>
<li><span class="glyphicon glyphicon-flag"></span> <?php echo HEADER_LANGUAGE; ?></li>
<li style="background-color:white"><a style="color:black" href="index.php?logout"><?php echo WORDING_LOGOUT; ?></a></li>
</ul>
</div>
<!-- Collapse -->
</div>
</nav>
Code for my language.php which is located in the main directory.
<?php
session_start();
if(isset($_SESSION['lang'])){
$from = $_SESSION['from'];
$langSession = $_SESSION['lang'];
if($langSession == "th"){
$_SESSION['lang'] = "en";
//header('Location:http://www.###.###'.$from);
echo $from;
} elseif ($langSession == "en"){
$_SESSION['lang'] = "th";
//header('Location:http://www.###.###'.$from);
echo $from;
}
if(!(isset($langSession))){
$_SESSION['lang'] = "en";
//header('Location:http://www.###.###'.$from);
echo $from;
}
}
?>
The problem is in my language.php file:
I commented out the header(Locations:"www.###.###".$from) and used echo $from ($from = $_SESSION['from'] (in order to find what the variable is reading) once I'm on location.php before the redirect. $from reads as 3. When I checked prior to the location.php execution, index.php showed $from to be /index.php which is correct.
Issue: Once I click on the link for language.php, $from changes to the integer 3.
With using the header() it sends me to http://www.###.###3 (The number 3 is coming from another session variable user ID $_SESSION['id'], which is from the next index in the array of $_SESSION variables).
I tried logging in with a different user and it changed the number according to that user's ID so that's confirmed that the following $_SESSION variable is overwriting the prior one. I just have no clue why it is doing that and changing the $_SESSION['from'] variable.
Now it's working with ALL of the other pages except index.php.
My code for index.php
<?php
ob_start();
// check for minimum PHP version
if (version_compare(PHP_VERSION, '5.3.7', '<')) {
exit('Sorry, this script does not run on a PHP version smaller than 5.3.7 !');
} else if (version_compare(PHP_VERSION, '5.5.0', '<')) {
// if you are using PHP 5.3 or PHP 5.4 you have to include the password_api_compatibility_library.php
// (this library adds the PHP 5.5 password hashing functions to older versions of PHP)
require_once('libraries/password_compatibility_library.php');
}
// include the config
require_once('config/db/config.php');
// include translation
session_start();
if(isset($_SESSION['lang'])){
$lang = $_SESSION['lang'];
} elseif(!(isset($_SESSION['lang']))) {
$_SESSION['lang'] = "en";
$lang = $_SESSION['lang'];
}
$_SESSION['from'] = $_SERVER['REQUEST_URI'];
require_once("translations/$lang.php");
// include the PHPMailer library
require_once('libraries/PHPMailer.php');
// load the login class
require_once('classes/Login.php');
// create a login object. when this object is created, it will do all login/logout stuff automatically
// so this single line handles the entire login process.
$login = new Login();
// ... ask if we are logged in here:
if ($login->isUserLoggedIn() == true){
// the user is logged in. you can do whatever you want here.
// for demonstration purposes, we simply show the "you are logged in" view.
include("views/logged_in.php");
} else {
// the user is not logged in. you can do whatever you want here.
// for demonstration purposes, we simply show the "you are not logged in" view.
include("views/landing.php");
}
PS. I've turned off registered globals via .htaccess
Any help would be much appreciated thank you.
I fixed this by renaming $_SESSION['from'] to $_SESSION['link'] and it is working correctly again. I'm assuming $_SESSION['from'] is trying to be set by something else. I've browsed through all of my code that is involved in these actions and there is nothing. Anyone have an explanation for why it changed the value of $_SESSION['from'] to the value of $_SESSION['user_id']?
As in $from = $_SESSION['from'] then it is assigned the value of $_SESSION['user_id']...

Categories