PHP - Only the path is output instead of the page - php

I have a small problem with my function, which is supposed to do nothing but output the web page more dynamically via domain.com/index.php?page=start.
My problem is that only the path is displayed, but not the content of the start.html.
My index.php:
<?php
require_once './ext/config.php';
require_once './ext/functions.php';
$page = isset($_GET["page"]) ? $_GET["page"] : "default";
$pc = "$website_pages/$page" .".html";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $website_title; ?></title>
</head>
<body>
<?php echo $pc; ?>
</body>
</html>
My function.php:
<?php
function getPage($pagename) {
global $website_pages;
$path = "$website_pages/$pagename";
if (file_exists($path)) {
return openPage($path);
} else {
echo "Error";
return openPage("$website_pages/includes/default.html");
}
}
function openPage($pageurl) {
$fh = fopen($pageurl, "r");
$fc = fread($fh, filesize($pageurl));
fclose($fh);
return $fc;
}
?>
My config.php:
<?php
$website_title = "Title";
$website_charset = "UTF-8";
$website_pages = "includes";
?>
Output in browser:
includes/start.html
Maybe you can help me?
regards

Related

How to include file in PHP with user defined variable

I am trying to include file in string replace but in output i am getting string not the final output.
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output i am getting :
<head><?php include "analytic.php"; ?> </head>
Output i need :
<head><title> Hello world </title> </head>
Note : Please do not recommend using analytic.php directly in index.php because head.php have some important code and it has to be merged analytic.php with head.php and then index.php
To get the desired output :
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
string = " <head> </head>";
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output will be output string not file string :
<head><title> Hello world </title> </head>
I think your approach is pretty basic (you try to hardcore modify - programmerly edit - the template script, right?) but anyway:
$file = file('absolut/path/to/file.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('absolut/path/to/file.php', $file);

Add array value after echoed

I'm creating a web app where I want to include JavaScript files with all file sources in an array, but I can't do that.
Header.php
<head>
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
Index.php
<?php
include('header.php');
array_push($import_scripts,'file03.js')
?>
But this only includes file01.js and file02.js, JavaScript files.
Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):
header.php
<?php
$import_scripts = array_merge(array(
'file01.js',
'file02.js'
), $extra_scripts ?? []);
?>
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>' . PHP_EOL;
}
?><title>Demo</title>
</head>
<body>
<p>Blog</p>
index.php
<?php
$extra_scripts = ['file03.js'];
include 'header.php';
?>
Output (demo on 3v4l.org)
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
header.php
<?php
function scripts()
{
return [
'file01.js',
'file02.js'
];
}
function render($scripts)
{
foreach ($scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
}
?>
<head>
index.php:
<?php
include 'header.php';
$extra_scripts = scripts();
$extra_scripts[] = 'script3.js';
render($extra_scripts);
?>
</head>
<body>
PHP is processed top down so it will currently be adding file03.js to the array after the foreach has been run.
This means you have two options:
Run the scripts after the header (Not reccomended)
Like Nick suggested, in index.php, specify additional scripts before the header is called
Other answers have answered why (you output content before adding the item to the array).
The best solution is to do all your processing before your output. Also helps with error trapping, error reporting, debugging, access control, redirect control, handling posts... as well as changes like this.
Solution 1: Use a template engine.
This may be more complex than you need, and/or add bloat. I use Twig, have used Smarty (but their site is now filled with Casino ads, so that's a concern), or others built into frameworks. Google "PHP Template engine" for examples.
Solution 2: Create yourself a quick class that does the output. Here's a rough, (untested - you will need to debug it and expand it) example.
class Page
{
private string $title = 'PageTitle';
private array $importScripts = [];
private string $bodyContent = '';
public setTitle(string $title): void
{
$this->title = $title;
}
public addImportScript(string $importScript): void
{
$this->importScripts[] = $importScript;
}
public addContent(string $htmlSafeBodyContent): void
{
$this->bodyContent .= $bodyContent;
}
public out(): void
{
echo '<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
';
foreach ($this->importScripts as $script) {
echo '<script src="' . htmlspecialchars($script) . '"></script>' . PHP_EOL;
}
echo '
<!-- End Scripts Section -->
<title>' . htmlspecialchars($this->title) . '</title>
</head>
<body> . $this->bodyContent . '
</body>
</html>';
exit();
}
}
// Usage
$page = new page();
$page->setTitle('My Page Title'); // Optional
$page->addImportScript('script1');
$page->addImportScript('script2');
$page->addContent('<h1>Welcome</h1>');
// Do your processing here
$page->addContent('<div>Here are the results</div>');
$page->addImportScript('script3');
// Output
$page->out();
I'd create a new php file, say functions.php and add the following code into it.
<?php
// script common for all pages.
$pageScripts = [
'common_1.js',
'common_2.js',
];
function addScripts(array $scripts = []) {
global $pageScripts;
if (!empty ($scripts)) { // if there are new scripts to be added, add it to the array.
$pageScripts = array_merge($pageScripts, $scripts);
}
return;
}
function jsScripts() {
global $pageScripts;
$scriptPath = './scripts/'; // assume all scripts are saved in the `scripts` directory.
foreach ($pageScripts as $script) {
// to make sure correct path is used
if (stripos($script, $scriptPath) !== 0) {
$script = $scriptPath . ltrim($script, '/');
}
echo '<script src="' . $script .'" type="text/javascript">' . PHP_EOL;
}
return;
}
Then change your header.php as
<?php
include_once './functions.php';
// REST of your `header.php`
// insert your script files where you needed.
jsScripts();
// REST of your `header.php`
Now, you can use this in different pages like
E.g. page_1.php
<?php
include_once './functions.php';
addScripts([
'page_1_custom.js',
'page_1_custom_2.js',
]);
// include the header
include_once('./header.php');
page_2.php
<?php
include_once './functions.php';
addScripts([
'./scripts/page_2_custom.js',
'./scripts/page_2_custom_2.js',
]);
// include the header
include_once('./header.php');
You are adding 'file03.js' to $import_scripts after including 'header.php', so echoing scripts it have been done yet. That's why 'file03.js' is not invoked.
So, you need to add 'file03.js' to $import_scripts before echoing scripts, this means before include 'header.php'.
A nice way is to move $import_scripts definition to index.php, and add 'file03.js' before including 'header.php'.
But it seems that you want to invoke certain JS scripts always, and add some more in some pages. In this case, a good idea is to define $import_scripts in a PHP file we can call init.php.
This solution will be as shown:
header.php
<head>
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
init.php
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
index.php
<?php
require 'init.php';
array_push($import_scripts,'file03.js');
include 'header.php';
header.php
<?php
echo "<head>";
$importScripts = ['file01.js','file02.js'];
foreach ($importScripts as $script) {
echo '<script src="' . $script . '"></script>';
}
echo "</head>";
echo "<body>";
index.php
<?php
include 'header.php';
array_push($importScripts, 'file03.js');
print_r($importScripts);
Output
Array ( [0] => file01.js [1] => file02.js [2] => file03.js )

How do I point to a .php file that is in another folder?

My file "index.php" has the script below:
<?php
$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];
switch ($pagina):
case 'contato':
$titulo = 'Contato ';
$keywords = '';
$descricao = '';
break;
case 'privacidade':
$titulo = 'Privacidade ';
$keywords = '';
$descricao = '';
break;
case 'ultimasnoticias':
$titulo = 'Ultimas Noticias';
$keywords = '';
$descricao = '';
break;
default:
$titulo = 'Home';
$keywords = '';
$descricao = '';
$pagina = 'home';
endswitch;
?>
<html>
<head>
<title><?php echo $titulo; ?></title>
<meta name="keywords" content="<?php echo $keywords; ?>">
<meta name="description" content="<?php echo $descricao; ?>">
</head>
<body>
<?php require_once 'page_' . $pagina . '.php'; ?>
<footer>Rodapé</footer>
</body>
</header>
I had some problems trying to explain my problem, my English is really bad, so I will try to explain what I need with the image below.
You can refer to a file in sub-directories from a PHP file in the parent ones by using
dirname(__FILE__)
This function gives you the current working directory i.e where the current running PHP file is in, now relative to this directory you can access a PHP file like:
include dirname(__FILE__) . "/subdirectory/myphpfile.php"
If you want to go in parent folder use "../"
For include:
include 'posts/your_page.php';
I edit but not sure it's what you want:
Your page is me.php, you can do:
include_once 'views/inc/header.php';
include_once 'views/me.php';
include_once 'views/inc/footer.php';
The header start with <!DOCTYPE html> end with <body>
Your footer is like : </body></html>

creating a textbox from a non-txt fopen file

I have the following code that opens a non-txt file and runs through it so it can read the file line by line, i want to create a textbox (using html probably) so i can put my readed text into that but i have no idea how to do it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h2>testing</h2>
<?php
$currentFile = "pathtest.RET";
$fp = fopen($currentFile , 'r');
if (!$fp)
{
echo '<p> FILE NOT FOUND </p>';
exit;
}
else
{
echo '<p><strong> Arquivo:</strong> ['. $currentFile. '] </p>';
}
$numLinha = 0;
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
}
fclose($fp);
$numLinha = $numLinha -1;
echo '<hr>linhas processadas: ' . $numLinha;
?>
</body>
</html>
i need the textbox area to be in a form so i can define the cols and rows, or there is an way to do it in php ? is there any way to send the readed content to another .php so i can edit the php to an html interface style freely ?
Try echoing the lines between a textarea:
echo "<textarea>";
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
};
echo "</textarea>";
You may use \n in order to break lines on the textarea:
echo $linha . "\n";

Dynamic Title Tag in PHP

I am trying to dynamically populate the title tag on a website. I have the following code in my index.php page
<?php $title = 'myTitle'; include("header.php"); ?>
And the following on my header page
<title><?php if (isset($title)) {echo $title;}
else {echo "My Website";} ?></title>
But no matter what I do, I cannot get this code to work. Does anyone have any suggestions?
thanks
This works (tested it - create a new folder, put your first line of code in a file called index.php and the second one in header.php, run it, check the title bar).
You should double check if those two files are in the same folder, and that you're including the right header.php from the right index.php. And ensure that $title is not being set back to null somewhere in your code.
Learn more about Variable Scope here.
Edit: Examples of visible changes would be:
TEST1<?php $title = 'myTitle'; include("header.php"); ?>
<title>TEST2<?php if ...
Are you including the header file before or after you set the title variable? If you're including it before, then of course it won't be set.
if you're doing something like this in your index.php:
<?php
include('header.php');
$title = "blah blah blah";
?>
then it won't work - you include the header file and output the title text before the $title variable is ever set.
try to declare the variable before using it
$title = '123';
require 'includes/header.php';
Hi Try this old school method ..
In your Header file (for e.g. header.php)
<?php
error_reporting(E_ALL);
echo '<!DOCTYPE html>
<!--[if IE 7 ]><html class="ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie8" lang="en"><![endif]-->
<!--[if IE 9 ]><html class="ie9" lang="en"><![endif]-->
<!--[if (gte IE 10)|!(IE)]><!-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<!--<![endif]-->
<head>';
?>
<?php
if($GLOBALS['title']) {
$title = $GLOBALS['title'];
} else {
$GLOBALS['title'] = "Welcome to My Website";
}
if($GLOBALS['desc']) {
$desc = $GLOBALS['desc'];
} else {
$desc = "This is a default description of my website";
}
if($GLOBALS['keywords']) {
$keywords = $GLOBALS['keywords'];
} else {
$keywords = "my, site, key, words";
}
echo "\r\n";
echo "<title> ". $title ." | MyWebsite.com </title>";
echo "\r\n";
echo "<meta name=\"description\" content='". $GLOBALS['title']."'>";
echo "\r\n";
echo "<meta name=\"keywords\" content='".$GLOBALS['title']."'>";
echo "\r\n";
?>
In you PHP Page file do like this (for example about.php)
<?php
$GLOBALS['title'] = 'About MyWebsite -This is a Full SEO Title';
$GLOBALS['desc'] = 'This is a description';
$GLOBALS['keywords'] ='keyword, keywords, keys';
include("header.php");
?>
I assume your header is stored in a different file (could be outside the root directory) then all the above solutions will not work for you because $title is set before it is defined.
Here is my solution:
in your header.php file you need to set the $title to be global by: global $title; then echo it in your title so:
<?php global $title; ?>
<title><?php echo isset($title) ? $title : "{YOUR SITE NAME}"; ?></title>
Then in every page now you can define your title after you have included your header file so for example in your index.php file:
include_once("header.php");
$title = "Your title for better SEO"
This is tested and it is working.
We can also use functions and its a good way to work on real time web sites.
Do simple:
create an index.php file and paste these lines:
<?php include("title.php");?>
<!doctype html>
<html>
<head>
<title><?php index_Title(); ?></title>
<head>
</html>
-- Then
Create a title.php file and paste these lines:
<?php
function index_Title(){
$title = '.:: itsmeShubham ::.';
if (isset($title)){
echo $title;
}else{
echo "My Website";
};
}
?>
It will work perfectly as you want and we can also update any title by touching only one title.php file.
<?php
echo basename(pathinfo($_SERVER['PHP_SELF'])['basename'],".php");
?>
This works. Since I'm using PHP I don't check for other extensions; use pathinfo['extension'] in case that's required.
You can achieve that by using define(); function.
In your header.php file add following line :
<title><?php echo TITLE; ?></title>
And on that page where you want to set dynamic title, Add following lines:
EX : my page name is user-profile.php where I want to set dynamic title
so I will add those lines that page.
<?php
define('TITLE','User Profile'); //variable which is used in header.php
include('header.php');
include('dbConnection.php');
?>
So my user-profile/.php file will be having title: User Profile
As like this you can add title on any page on your site
Example Template.php
<?php
if (!isset($rel)) {$rel = './';}
if (!isset($header)) {
$header = true;
?><html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<?php } else { ?>
</body>
</html><?php } ?>
Pages Your Content
<?php
$rel = './'; // location of page relative to template.php
$pageTitle = 'This is my page title!';
include $rel . 'template.php';
?>
Page content here
<?php include $rel . 'template.php'; ?>
I'm using your code in my project and it works properly
My code in header:
<title>
<?php
if (isset($title)) {echo $title;}
else {echo "عنوانی پیدا نشد!";}
?>
</title>
and my code in index.php:
<?php
$title = "سرنا صفحه اصلی";
include("./include/header-menu.php");
?>

Categories