Firefox and IE aren't displaying "<script ... > ... </script>" provided from PHP - php

Hey everyone, I am having a problem with a website I'm trying to build; basically I have a class that I call from my header file that loads all of the link and script tags. The link tags show up across all browsers, but the script tags only show up in safari and chrome, they do no show up in firefox or IE.
<script type='text/javascript' src='...'>
now I have tried removing the "<" at the front of the tag just to see what happens, and it will show up as plain text then, but as soon as I put the "<" back it is again MIA.
So here is what's going on in the php. My header.php file calls the cms object function, located in cms.php, and those functions call other functions in my system.php file.
Now, again the link tags work w/out a hitch and I call them the exact same way ... it is just the dumb script tags. When I call the load_js("config"); function in my header.php it will load multiple tags as well. If it was just 1 tag I would put the script tags in the html rather than in the php, but I don't think I can do that when I'm producing multiple tags.
Any help would be great! Thanks in advance as well!
header.php
<?php echo $this->load_css("config"); ?>
<?php echo $this->load_js("config"); ?>
cms.php
function load_js($name){
// ...
return header_script($name.".js");
// ...
}
function load_css($name){
// ...
return header_link($name.".css");
// ...
}
system.php
function header_script(){
// 0 = src
$num = func_num_args();
if($num == 0){
return;// if no arguments, can't successfully build header_script.
}
if($num == 1){
return "<script type='application/javascript' src='".func_get_arg(0)."'></script>\n";
}
}
function header_link(){
$num = func_num_args();
// 0 = rel
// 1 = type
// 2 = href
if($num < 3){
return; // can't successfully build link.
}
if($num == 3){
return "<link rel='".func_get_arg(0)."' type ='".func_get_arg(1)."' href='".func_get_arg(2)."' />\n";
}
}

Firstly, application/javascript is not recognized by some browsers. You should change that to text/javascript
Secondly, as mentioned in comments (Justin Johnson), you should use parameters in your function definition with default values:
function header_script($name = '')
{
if ($name != '') {
return '<script type="text/javascript" src="'.$name.'"</script>';
}
}

Related

Display static items according to page accessed, in PHP

I need to include some js, css type items in specific pages.
So far I've done the following:
define("DIR_ADMIN", "admin");
function fusion($location, $page, $type) {
$dirAdmin = DIRECTORY_SEPARATOR.DIR_ADMIN;
$change = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $location);
$changed = ucfirst($change);
$result = $dirAdmin.$changed;
if($type=='js'){
echo "<script src='$result'></script>\n";
} elseif($type=='css'){
echo "<link rel='stylesheet' href='$result' />";
} elseif($type=='favicon'){
echo "<link rel='shortcut icon' href='$result' />";
} elseif($type=='logo'){
echo "<img src='$result' alt='logo'>";
} else {
echo $result;
}
}
In HTML I called the function like this:
<?php fusion("/assets/vendors/js/vendor.bundle.base.js", "clients", "js"); ?>
First is the file URL, then the page, and finally the file type.
What I'm not able to come up with is the part that receives the value $page.
I created a routing system in php, so all files are accessed like this: index.php?page=clients, except in the case of the homepage which is just index.php.
I need that when the value of $page is set for example with clients it should load all items that have this same when the clients route is accessed.
In some cases the route may have another word attached, for example: index.php?page=clients-add, in which case it should check if there is only the word clients in $_GET.
And if I set the value of $page to all, it should display on all pages. How can I do this?
Within your fusion function you need to pick up which page you're on and then including the displaying of content after that.
Use this snippet to help dictate the page you're on.
$curr_page = "home";
if ( isset( $_GET["page"] ) ) {
$curr_page = $_GET["page"];
}
if ( $page == "all" || $page == $curr_page ) {
//echo items here
}

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 include() wiping rest of HTML document?

So I have a simple html page that looks like this.
<html>
<head>
<?php include("scripts/header.php"); ?>
<title>Directory</title>
</head>
<body>
<?php include("scripts/navbar.php"); ?>
<div id="phd">
<span id="ph">DIRECTORY</span>
<div id="dir">
<?php include("scripts/autodir.php"); ?>
</div>
</div>
<!--Footer Below-->
<?php include("scripts/footer.php"); ?>
<!--End Footer-->
</body>
</html>
Now, the problem is, when I load the page, it's all sorts of messed up. Viewing the page source code reveals that everything after <div id="dir"> is COMPLETELY GONE. The file ends there. There is no included script, no </div>'s, footer, or even </body>, </html>. But it's not spitting out any errors whatsoever. Just erasing the document from the include onward without any reason myself or my buddies can figure out. None of us have ever experienced this kind of strange behavior.
The script being called in question is a script that will fetch picture files from the server (that I've uploaded, not users) and spit out links to the appropriate page in the archive automatically upon page load because having to edit the Directory page every time I upload a new image is a real hassle.
The code in question is below:
<?php
//Define how many pages in each chapter.
//And define all the chapters like this.
//const CHAPTER_1 = 13; etc.
const CHAPTER_1 = 2; //2 for test purposes only.
//+-------------------------------------------------------+//
//| DON'T EDIT BELOW THIS LINE!!! |//
//+-------------------------------------------------------+//
//Defining this function for later. Thanks to an anon on php.net for this!
//This will allow me to get the constants with the $prefix prefix. In this
//case all the chapters will be defined with "CHAPTER_x" so using the prefix
//'CHAPTER' in the function will return all the chapter constants ONLY.
function returnConstants ($prefix) {
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$dump[$key] = $value;
}
}
if(empty($dump)) {
return "Error: No Constants found with prefix '" . $prefix . "'";
}
else {
return $dump;
}
}
//---------------------------------------------------------//
$archiveDir = "public_html/archive";
$files = array_diff(scandir($archiveDir), array("..", "."));
//This SHOULD populate the array in order, for example:
//$files[0]='20131125.png', $files[1]='20131126.png', etc.
//---------------------------------------------------------//
$pages = array();
foreach ($files as $file) {
//This parses through the files and takes only .png files to put in $pages.
$parts = pathinfo($file);
if ($parts['extension'] == "png") {
$pages[] = $file;
}
unset($parts);
}
//Now that we have our pages, let's assign the links to them.
$totalPages = count($pages);
$pageNums = array();
foreach ($pages as $page) {
//This will be used to populate the page numbers for the links.
//e.g. "<a href='archive.php?p=$pageNum'></a>"
for($i=1; $i<=$totalPages; $i++) {
$pageNums[] = $i;
}
//This SHOULD set the $pageNum array to be something like:
//$pageNum[0] = 1, $pageNum[1] = 2, etc.
}
$linkText = array();
$archiveLinks = array();
foreach ($pageNums as $pageNum) {
//This is going to cycle through each page number and
//check how to display them.
if ($totalPages < 10) {
$linkText[] = $pageNum;
}
elseif ($totalPages < 100) {
$linkText[] = "0" . $pageNum;
}
else {
$linkText[] = "00" . $pageNum;
}
}
//So, now we have the page numbers and the link text.
//Let's plug everything into a link array.
for ($i=0; $i<$totalPages; $i++) {
$archiveLinks[] = "<a href='archive.php?p=" . $pageNums[$i] . "'>" . $linkText[$i] . " " . "</a>";
//Should output: <a href= 'archive.php?p=1'>01 </a>
//as an example, of course.
}
//And now for the fun part. Let's take the links and display them.
//Making sure to automatically assign the pages to their respective chapters!
//I've tested the below using given values (instead of fetching stuff)
//and it worked fine. So I doubt this is causing it, but I kept it just in case.
$rawChapters = returnConstants('CHAPTER');
$chapters = array_values($rawChapters);
$totalChapters = count($chapters);
$chapterTitles = array();
for ($i=1; $i<=$totalChapters; $i++) {
$chapterTitles[] = "<h4>Chapter " . $i . ":</h4><p>";
echo $chapterTitles[($i-1)];
for ($j=1; $j<=$chapters[($i-1)]; $j++) {
echo array_shift($archiveLinks[($j-1)]);
}
echo "</p>"; //added to test if this was causing the deletion
}
?>
What is causing the remainder of the document to vanish like that? EDIT: Two silly syntax errors were causing this, and have been fixed in the above code! However, the links aren't being displayed at all? Please note that I am pretty new to php and I do not expect my code to be the most efficient (I just want the darn thing to work!).
Addendum: if you deem to rewrite the code (instead of simply fixing error(s)) to be the preferred course of action, please do explain what the code is doing, as I do not like using code I do not understand. Thanks!
Without having access to any of the rest of the code or data-structures I can see 2 syntax errors...
Line 45:
foreach ($pages = $page) {
Should be:
foreach ($pages as $page) {
Line 88:
echo array_shift($archiveLinks[($j-1)];
Is missing a bracket:
echo array_shift($archiveLinks[($j-1)]);
Important...
In order to ensure that you can find these kinds of errors yourself, you need to ensure that the error reporting is switched on to a level that means these get shown to you, or learn where your logs are and how to read them.
See the documentation on php.net here:
http://php.net/manual/en/function.error-reporting.php
IMO all development servers should have the highest level of error reporting switched on by default so that you never miss an error, warning or notice. It just makes your job a whole lot easier.
Documentation on setting up at runtime can be found here:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
There is an error in scripts/autodir.php this file. Everything up to that point works fine, so this is where the problem starts.
Also you mostlikely have errors hidden as Chen Asraf mentioned, so turn on the errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Just put that at the top of the php file.

How to dynamically update a sitemap with php?

I have a dynamic site where posts are constantly being generated i have it coded so each time a new post is added it appends the site map url entry to the bottom of the sitemap.xml file.
$lastID = $db->lastInsertId();
$file = 'sitemap.xml';
$current = file_get_contents($file);
$current .= "<url>
<loc>http://website.net/viewpost.php?ID=".$lastID."</loc>
<changefreq>monthly</changefreq>
</url>";
file_put_contents($file, $current);
this works but the closing tag in the xml file urlset needs to be at the end of the file. So when i append this data it goes after the urlset and even if i added this to the string there would be multiple closing tags for this. How do i update the file so it doesnt go after the closing tag.
Regenerating the entire site map every time would work but it seems like a lot of work as there are almost 100 pages as of right now and it will need to query multiple tables to get the data
This is a simple function for inserting an element before,after or inside another element.
<?php
public function myInsertNode($newNode, $refNode, $insertMode=null) {
if(!$insertMode || $insertMode == "inside") {
$refNode->appendChild($newNode);
} else if($insertMode == "before") {
$refNode->parentNode->insertBefore($newNode, $refNode);
} else if($insertMode == "after") {
if($refNode->nextSibling) {
$refNode->parentNode->insertBefore($newNode, $refNode->nextSibling);
} else {
$refNode->parentNode->appendChild($newNode);
}
}
}
?>

how to make a php function wait to execute until the end of the script

I'm trying to create a queue function for javascript files. Basically, this is the way I want it to work:
I want to create a function that will take all of the javascripts sent to it and put them in the appropriate place on the page (i.e. header or footer, and above dependent scripts).
I want to be able to say:
Here's a script. Add it to the queue in the order that it should be in. Then, after all the scripts have been queued up, run the function to write them to the page.
So far my code looks like this:
$scripts = array();
function enqueue_script($src="", $script_name="", $script_data="",
$script_dependencies=array(), $force_header=false, $additional_atts=array()){
global $scripts;
//run check for duplicates
//run check for dependencies already in the variable
//run checks to see if this script depends on other scripts
//$scripts array is saved in increments of 10 to allow for up to
//9 dependants
$i = count($scripts);
$i = ($i*10)+10;
$scripts[$i]['src'] = $src;
$scripts[$i]['script_name'] = $script_name;
$scripts[$i]['script_data'] = $script_data;
$scripts[$i]['dependencies'] = $script_dependencies;
$scripts[$i]['force_header'] = $force_header;
$scripts[$i]['atts'] = $additional_atts;
}
function write_scripts_header() {
global $scripts;
$echo = "";
$atts = "";
//create script tag for insertion in header
foreach($scripts as $s){
if($s['force_header']){
foreach($s['atts'] as $a => $v){
$atts .= " {$a}='{$v}'";
}
if($s['src']!=""){
$echo .= "<script src='{$s['src']}'{$atts}></script>\n";
} else {
$echo .= "<script{$atts}>{$s['script_data']}</script>\n";
}
}
}
echo $echo;
}
function write_scripts_footer() {
global $scripts;
$echo = "";
$atts = "";
//create script tag for insertion in footer
foreach($scripts as $s){
if(!$s['force_header']){
foreach($s['atts'] as $a => $v){
$atts .= " {$a}='{$v}'";
}
if($s['src']!=""){
$echo .= "<script src='{$s['src']}'{$atts}></script>\n";
} else {
$echo .= "<script{$atts}>{$s['script_data']}</script>\n";
}
}
}
echo $echo;
}
Then, in the HTML file part:
<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>
This works fine if the HTML section is loaded last. However if I have an include that happens in the middle of the body tag, and that include needs to enqueue_script() in the header, then the $scripts variable isn't ready yet when the write_scripts_header() function runs.
How can I make write_scripts_header() and write_scripts_footer() wait until all the scripts have been queued up before running? Or....is there a better way to allow for a scripts queue so that I can write all the scripts to the document at the end?
If it's all running in the same file, Can you make the body content be a variable, $body, and load it first, then echo it into the <body> section?
change
<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>
to
print "<html><head>".write_scripts_header()."</head><body>".write_scripts_footer()."</body></html>";
Try using a template engine, such as Twig, and you'll be able to output your html after you're done preparing your scripts-array.

Categories