PHP: Show HTML Only On Homepage - php

I'm having trouble getting a PHP script to work. It doesn't seem to be working accurately. I'm trying to make a script to only show HTML or Javascript on the homepage only. This script will be used for multiple things. I did google this, but most answers are for WP. This is vanilla PHP.
Here's what I used:
<!-- Add Only On The Homepage Or Else -->
<?php
$currentpage = $_SERVER['REQUEST_URI'];
if($currentpage=="/" || $currentpage=="/index.php" || $currentpage=="" ) {
echo '
<header id="main-header" class="home">
';
}
else {
echo '
<header id="main-header">
';
}
?>
The results are that it shows the content of else, even though it's the homepage. I tested it on "/" and "/index.php".

I commonly use this snippet:
index.php
if (preg_match('/^m\.[^\/]+(\/(\?.*|index\.html(\?.*)?)?)?$/i', $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])) {
readfile('index.html');
} else {
// Your framework bootstrapper or your own logic
}

Related

Dynamic load of page content

I am trying to load my content dynamically via PHP. Here is my code, which for some reason doesnt work. Can you give me some hint, what am I doing wrong?
The goal is :
Click on Hypertext in nav
Get dynamically content from file page-statistiky in folder /podstranky
Code:
<nav>
<ul>
<li>statistiky</li>
</ul>
</nav>
<?php
if (isset($_GET['stranka']))
$stranka = $_GET['stranka'];
else
$stranka = 'page-statistiky';
if (preg_match('/^[a-z0-9]+$/', $stranka)) {
$vlozeno = include('podstranky/' . $stranka . '.php');
if (!$vlozeno)
echo('Podstránka nenalezena');
} else
echo('Neplatný parametr.');?>
You regex doesn't include provision for the dash i.e. -'
Change this:
if (preg_match('/^[a-z0-9]+$/', $stranka))`
to
if (preg_match('/^[a-z0-9\-]+$/', $stranka))

Best way to have a variable template in php

I'm coding a menu bar for a website in php. Because I don't want to have to edit it multiple times on the half a dozen or so pages I'll have I've decided to put it in it's own separate header.php file and just include_once(header.php) in the various pages.
My problem is that the menu is going to be slightly different depending on which page it's included in. Right now I'm dealing with it by having the following in my header.php file with $PageTitle being defined in the individual pages:
if ($PageTitle == "Home"){
echo '<li class="active">Home</li>';
}
else{
echo '<li>Home</li>';
}
if ($PageTitle == "About"){
echo '<li class="active">About</li>';
}
else{
echo '<li>About</li>';
}
...
The active class simply highlights the menu of the current page (Like the menu bar on the top of StackOverflow). It works fine but I'm curious if there is a better perhaps more efficient way to doing this. Thanks guys.
Try this:
//list of menu headers
$headers = new array();
//populate the array with your headers here ...
foreach($headers as $val)
{
if( $PageTitle == $val )
echo '<li class="active">'.$val.'</li>';
else
echo '<li>'.$val.'</li>';
}
for current class you can also use jquery if you want to:
$(function(){
var path = location.href;
if ( path )
$('.side_menu a[href="' + path + '"]').attr('class', 'current');
});

PHP script tags

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>
Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)
Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.
Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}
Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }
That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

PHP $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Google Analytic on a php site?

I have some problem to get the Google Analytics to work. I have got a analyticsTracking.php file and this is included on my index.php page like this :
<?php
include("begin.php");
include($subroot . "templateconfig.php");
include($cms['tngpath'] . "genlib.php");
include($cms['tngpath'] . "getlang.php");
include($cms['tngpath'] . "$mylanguage/text.php");
tng_db_connect($database_host,$database_name,$database_username,$database_password) or exit;
include($cms['tngpath'] . "checklogin.php");
//Insert the following lines in your index.php to take advantage of template switching
if($templateswitching && $templatenum) {
include($cms['tngpath'] . "templates/template$templatenum/index.php");
exit;
}
//end of lines to be inserted for template switching
$flags['noicons'] = true;
$flags['noheader'] = true;
tng_header( $text['mnuheader'], $flags );
?>
<!-- "Home Page" (the text for these messages can be found at near the bottom of text.php -->
<h1><?php echo $text['mnuheader']; ?></h1>
<p><strong>Please customize this page!</strong></p>
<?php include ("analyticsTracking.php"); ?>
</body>
</html>
When looking on the genereted index.html there is no data from the analyticsTracking.php at all? Why?
Pleas note, I am not working with PHP so all this is new to me.
Edit1: Sorry, I am using index.php and not index.html.
Edit2: analyticsTracking.php contains somthing like this :
<script type="text/javascript">
var gaJsHost = ((" https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script> <?php
// End Analytics tracking code
?>
So if I'm understanding correctly, your index.php script includes analyticsTracking.php, yet when you view index.php in a browser, you don't see any of the HTML from analyticsTracking.php.
<?php include ("analyticsTracking.php"); ?>
Is that the correct path? Is analyticsTracking.php in the same directory as index.php? Try changing the include to a require and see if it prints an error when the webpage is refreshed.
Sorry, the problem was that I used the wrong php file. It is working as it should.

Categories