Load files in subdirectories in PHP - php

I have a basic semi-static website written in PHP. In the root folder I have a file called posts.php and also a folder called posts, in which there are post1.php, post2.php, and so forth and so on.
the posts.php file is in the root folder. When opened it creates a list from the files inside the posts folder and links to them.
In essence, what I want to do is to open php pages that I create statically and store in the posts/ folder in the browser.
The problem is that when I try to open these posts I am unable to. I can hard-link to them, and this "works", but if I do so my base templating will not work.
When I click links I go from one page to the next, and the URL shows ?p=index or ?p=posts. post1.php should be in something like ?p=posts/post1, but it doesn't work.
There may be a problem in naming, since there is a folder and a php file with the same name (posts), but I'm not sure if that's it, nor how to work around it.
edit: Below are parts of the code that I believe pertain to this problem:
my index.php
<?php
require_once('functions.php');
require_once('header.php');
load_page();
// require_once('init.php');
require_once('footer.php');
?>
My header.php
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta charset="utf8">
<title>Paulo RSS Alves</title>
</head>
<body>
<div>
<!-- these are working without any issue -->
<h1><a href='?p=index'>Paulo RSS Alves</a></h1>
<div class="bar">
<p>Posts</p>
</div>
posts.php:
<?php
$dir = scandir('./post');
foreach ($dir as $file)
{
$path_parts = pathinfo($file);
if ($path_parts['extension'] == 'php' and ctype_alpha($file[0])){
// the purpose of this code is to only consider files with
// the .php extension and to remove that extension from the url.
$file_f = str_replace('.'.$path_parts['extension'], "", $file);
echo '<li><a href='.'post/'.$file_f.'>'.$file_f.'</li>';
}
}
?>
and functions.php:
<?php
function load_page() {
(isset($_GET['p'])) ? $page = $_GET['p'] : $page = 'index';
if (file_exists($page) && $page != 'index'){
require_once($page);
} else{
require_once('init.php');
}
}
?>
init.php is merely a welcome screen.
and a schema of my filetree:
index.php
init.php
header.php
footer.php
functions.php
posts.php
posts/
post1.php
post2.php

You are not requiring from the posts folder
<?php
function load_page() {
$dir = './posts/';
(isset($_GET['p'])) ? $page = $_GET['p'] : $page = 'index';
if (file_exists($page) && $page != 'index'){
require_once($dir . $page);
// add directory ^^^^
} else{
require_once('init.php');
}
}
?>

Related

Print name of current page through included <head> file

So I would like to print name of the current page in the title tag of the head.
I include my head in every page like this:
include 'includes/head.php';
This is my head:
<head>
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?><title>
</head>
I thought this would work, but now it just shows "Head" on every page.
I know I can make it work by just putting the $page variable on every page but I would like to prevent this.
So is there any way to print the name of the current page through the included head.php file without adding anything to every page?
Thanks
EDIT
This is how I fixed it:
$page = pathinfo($_SERVER['SCRIPT_NAME'],PATHINFO_FILENAME);
If you were to create a file head.php with the following content
<?php
$xpage = pathinfo( $_SERVER['SCRIPT_NAME'],PATHINFO_BASENAME );
$ypage = pathinfo( $_SERVER['SCRIPT_NAME'],PATHINFO_FILENAME );
echo "
<!--
with extension
{$xpage}
without extension
{$ypage}
-->";
?>
and include in your regular php pages using include '/path/to/head.php' you should get the desired result ~ you will see two options - with or without file extension.
To add this to the document title simply echo whichever option is preferrable
<title><?php echo $ypage;?></title>
Try this enclosing the $page variable in php tags:
<head>
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?><title>
</head>
You have several problems, first one is curly bracket in front of the echo, the second one is that end title tag is missing forward slash and probably last one is that page variable is not inside php tags...
So your code should look like:
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?></title>
You could use a function like this:
head.php
<?php
function head($page) {
echo "<head>";
echo "<title>".ucfirst($page)."<title>";
echo "</head>"
}
index.php
<?php
include 'includes/head.php';
$page = basename(__FILE__, '.php');
head(page);

Import stylesheet with php if a certain page is requested

I would like to import a css stylesheet in a page depending on a php condition (or other), this condition is based upon the domain URL.
For example, if the page loaded is "mydomain.com/about-us" import a "css/about-us.css" file.
I have tried with this code, but it does not work.
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/")) {
include '/css/about-us.css';
}
?>
How can I import, or use a <style> tag conditionally?
solution correct:
the correct solution is use only the page name, so if you page is mydomain.com/about-us/
use " /about-us/" only.
now have other question, with the code posted you can import css for specific page , but I noticed that if the domain is mydomain.com/about-us/team.html example in the page team.html load also the css of "about-us" how load the css for about-us only in the page mydomain/about-us/ ??
How you can read here, strstr will return a string or FALSE. You can change it like this:
<!DOCTYPE html>
<head>
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
} ?>
</head>
...
</body>
</html>
Or:
<!DOCTYPE html>
<head>
<style type="text/css">
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo file_get_contents('/css/about-us.css');
} ?>
</style>
</head>
...
</body>
</html>
In the first example your CSS is included through the <link> tag, in the second, the PHP-script loads your CSS file into the script-tags. You can not use include because it will load another php file and execute where it was included. You should use my first example, because it is more server-friendly because the CSS file doesn't need to be read. Your page will be faster.
You can add a stylesheet to the page with PHP by including this in the <head> of your html document:
<?php
echo '<link rel="stylesheet" type="text/css" href="' . $file . '">';
?>
Where $file is the name of the css file. You're going to have to provide some more information as to what you're trying to do for a better answer.
Update
The variable $_SERVER[REQUEST_URI] only gives the requested page, not the whole domain. From the PHP manual,
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
So the code should look as follows:
<?php
$requested_page = $_SERVER['REQUEST_URI'];
if ($requested_page === "/about-us" || $requested_page === "/about-us/") {
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
}
?>
This will test if the requested page is "/about-us" (the client is requesting the "about-us" page) and if it does, the link to the stylesheet will be echoed.
use this:
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/"))
{
// output an HTML css link in the page
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css" />';
}
else
{
// output an HTML css link in the page
echo '<link rel="stylesheet" type="text/css" href="/css/another.css" />';
}
?>
you can also do this to import the css contents directly, but probably some media/images links can break:
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/"))
{
// output css directly in the page
echo '<style type="text/css">' .file_get_contents('./css/about-us.css').'</style>';
}
else
{
// output css directly in the page
echo '<style type="text/css">' .file_get_contents('./css/another.css').'</style>';
}
?>

Changing title based on included file in PHP

I have to make some changes on my old website where I'm not using any templating system. I'm loading the content for some pages from a database based on ?page parameter. So I have something like this:
<title>Page title</title>
...
...
...
$page_id = $_GET['page'];
include 'page.php'; //escaping is done in this file
Inside the page.php file I'm actually loading the information about the page. Based on this information I have to change the title of the main page.
I know that this design is not good at all and I wouldn't do this way these days, but to change everything on this website would be too complicated.
Thank you for your ideas.
Try to add php code before title
<html>
<?php
$page_id=$_GET["page"];
include('page.php');
echo "<title>".$page_title."</title>";
?>
<body></body></html>
Inside page.php:
echo '<script>
document.title = "This is the new page title.";
</script>';
How to dynamically change a web page's title?
Enjoy !
<?php
$page_id = $_GET['page'];
if ($page_id == 'first value') {
$title = 'first title';
} else {
$title = 'second title';
}
?>
<title><?php echo $title?></title>
...<?php
include 'page.php'; //escaping is done in this file

Include CSS/JS only when necessary

My menu system all comes from the index file. A simplified example:
#index.php
...
<div id="container">
include($inc_file) //index.php?site=news will show news.php
</div>
...
My question is: how can I only include some js-files and css-files when they are needed. For example, I have a file with a slider. I would like only to include the js/css-files related to the slider when visiting that page.
I know that I can make if/else clauses, but I find that a bit ineffective. Is it possible to place a session containing an array with all the files that should be included on the frontpage?
Here is what I would use:
<?php
$path_parts = pathinfo(__FILE__);
$filename = $path_parts['filename'];
if ($filename === "somepage") {
?>
<script src=""></script>
<link ...>
<?php } ?>
I would just have a preset array for each page with an array of css/js files it would need to include.
eg.
settings.php
<?php
$pages = array();
$pages['index'] = array(
"css" => array("main.css","index.css"),
"js" => array("jquery.min.js","someotherjs.js")
);
$pages["about"] = array(
...
);
index.php
<?php
include('settings.php');
?>
...
<head>
<?php
foreach($pages['index']['css'] as $css)
echo "<link rel='stylesheet' type='text/css' href='$css'>";
?>
...
<?php
foreach($pages['index']['js'] as $js)
echo "<script src='$js'></script>";
</body>
</head>
This may not be the answer you were expecting but did you know that the browser does not download css or js files that have not changed since the last time they were downloaded. They are cached on the client PC and only refreshed if the copy on the server has changed.
Theerfore you may not need to be so selective about what you load on each page as it probably wont cause a fresh download of a css or js file.
Prepare an object where you can add style or js files as you need, here a little example.
class head {
private styles = array();
private scripts = array();
public function __construct() {}
// add script in page
public function add_script(filepath){
array_push($this->scripts, filepath);
}
// add style in page
public function add_style(filepath){
array_push($this->styles, filepath);
}
// get html <link> for styles
public function get_styles(){
$html = '';
$len = count($this->styles);
for($i=0; $i < $len; $i++){
$html .='<link rel="stylesheet" type="text/css" href="'.$this->styles[$i].'">';
}
return $html;
}
// get html <script> for scripts
public function get_scripts(){
$html = '';
$len = count($this->scripts);
for($i=0; $i < $len; $i++){
$html .='<script type="text/javascript" src="'.$this->scripts[$i].'"></script>';
}
return $html;
}
}
// destruct ...
in your controller :
require('/class/head.php');
$head = new head();
$head->add_style('/css/myStyle.css');
$head->add_script('/js/myScript.js');
in head
<?php echo $head->get_styles(); ?>
<?php echo $head->get_scripts(); ?>

Dynamic Content....why isn't it working?

Okay I want to apologize in advance because I'm having trouble articulating what the root cause of the problem is with this site that I'm attempting to build. So if I'm way off in outer space...=/
Anyways, the first issue I'm having is that when I attempted to fix an issue with "include" function in php I'm getting this error (below) the reason why I was tampering with it at all was because my navs aren't working. I keep getting a 404 whenever I attempt to leave the index.php page.
Warning: include(/home/content/22/10350022/html/../Setup.php) [function.include]: failed to open stream: No such file or directory in /home/content/22/10350022/html/index.php on line 6
Warning: include() [function.include]: Failed opening '/home/content/22/10350022/html/../Setup.php' for inclusion (include_path='.:/usr/local/php5_3/lib/php') in /home/content/22/10350022/html/index.php on line 6
Here is the code from index.php, setup, and navs:
Index.php ---below
> > <?php
// Setup Document:
//include (1) - forces the site to load the file one time but we're not going to include set up file more than once
define('APP_PATH', dirname(__FILE__) . "/../");
include(APP_PATH . "Setup.php");
if (isset($_GET['page']) && $_GET['page'] ==! ''){
$pg =$_GET['page'];
} else {
$pg = 'Home';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="Css/styles.css">
<style type="text/css">
body {
background-color: #039;
}
</style>
</head>
<body>
<div class ="header">
<?php include('Template/header.php');?>
</div>
<div class ="main_Nav">
<?php include('Template/main_Nav.php');?>
</div>
<div class ="main_Content">
<?php include('Content/'.$pg.'.php');?>
<?php #$Home = "SELECT body FROM Pages WHERE Id=1";
#$d = '$Home, $conn';
#if ($d == false) {
#echo "FAILURE".mysql_error($conn);
#}
?>
<div class ="main_Footer">
<?php include('Template/footer.php');?>
</div>
</body>
</html>
Some stuff is commented out on purpose so I could work on this issue.
Navs below --
<?php
## Main Navigation Document
include('/Config/setup.php');
?>
<ul>
<li>Home</li>
<li>Services</li>
<li>Free Stuff</li>
<li>Blog</li>
<li>About Us</li>
</ul>
Finally - setup -- some info is blacked out obviously and some stuff is commented out on purpose
<?php
## Setup Document
//Host - location of database on server etc
//username
//pswd
//database name
//connection variables
$host = "";
$user = "test";
$pwd = "";
$db = "test";
//connection info
$conn = mysqli_connect ($host, $user, $pwd, $db);
if ($conn ==false) {
echo "connection has failed";
}
//fetching the title of pages
#$sql = "SELECT title FROM pages WHERE Id=2";
//da warnings
#$r = '$sql,$conn';
# echo $r;
# echo "sucess!";
// return
#if ($r == false) {
# echo "FAILURE".mysql_error($conn);
#}
?>
Originally I was just using include('/Config/setup.php'); which works. But whenever I attempt to navigate to content featured in my navs bar...i get a 404 error. Now this should only change the content box -- the rest of the page should remain static. <?php include('Content/'.$pg.'.php');?> Which is what I think I'm doing here. Or at least I hope it is lol. $pg is the string 4(Home) and unless page is otherwise defined it will be defaulted to home. At least that is what I THINK I wrote above.
my file structure just really fast is this:
...root folder on FTP
-content
-config
-images
-Css
-templates
-Stats
-Roodyinfo
Now this path it keeps asking for...does that have to do with my hosting service? Cause it seems like its saying I have to define an ABSOLUTE path???
All help is welcome and appreciated. Thanks!
Just put all the files you need in the same directory and use require('filename'); with no paths.

Categories