The script below echos the array and its individual elements fine but when the array elements are used to set the page title by running the script after the opening head tag, I still get "untitled document" as the page title.
Further if I try echoing $title alone and placing the title tags <> before and after the php tags, the title is set as the document type definition..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
It seems that echo sets the relevant HTML tags required before if not already set. Whats the work around ??
<?php
include 'contentStream.php' ;
$upc = $_GET['upc'];
if (isset($upc))
{
global $upc ;
$query = "SELECT * FROM tracks WHERE album_upc='$upc'";
connect();
$db = mysql_select_db("XXXXX");
$results = mysql_query($query, $connection) ;
$result = mysql_fetch_assoc($results);
$title = $result['title']." by ".$result['author'] ;
echo "<title>".$title."</title>";
unset($results);
unset($query);
mysql_close($connection) ;
}
else
{
echo "<title> MYsUPERsITe </title> " ;
}
?>
Is this being executed within the <head> element? If not it needs to be.
I am not sure what contentstream.php is but it looks like you might be running this at the wrong location in the page.
Also try changing $title to $myTitle to see if $title has been set somewhere else.
Your problem seems to be that you are trying to change the contents of the <title> tag after it has already been produced by the non-PHP section of your page. That approach does not work in a server-side environment like PHP.
One solution is to use PHP to generate the entire HTML page, store it in a variable, and just echo() it out when you're all done.
At the top of your page, I would run and parse a database query and build a $html string to echo out later. Multiple echo() statements like you have above can get ugly, and can give you issues with headers and such if you later end up adding cookies or session variables to your site:
<?php
include ("my_cool_lib.php");
$html = "<!DOCTYPE html>";
$html .= "<html><head>";
$db = connect_to_db();
$resultset = run_a_query($db);
$title = get_title($resultset);
$html .= "<title>$title</title>";
$html .= "</head><body>";
$html .= "<h1>Results</h1>";
// loop through $resultset
// $html .= track info
// end loop
$html .= "</body></html>";
echo $html;
?>
You need to set the relevent HTML tags that you're currently missing.
<html>
<head>
<title>Your title</title>
</head>
<body>
body stuff
</body>
</html>
Related
Is there a way I can insert < or > in HTML file using PHP. Here is a a part of code
<?php
$custom_tag = $searchNode->nodeValue = "<";
$custom_tag = $searchNode->setAttribute("data-mark", $theme_name);
$custom_tag = $dom->saveHTML($searchNode);
$root = $searchNode->parentNode;
$root->removeChild($searchNode);
$test = $dom->createTextNode("<?php echo '$custom_tag'; ?>");
$root->appendChild($test);
$saved_file_in_HTML = $dom->saveHTML();
$saved_file = htmlspecialchars_decode($saved_file_in_HTML);
file_put_contents("test.html", $saved_file);
The problem is that I get < using above method and I would like to have <.
EDIT:
Full code:
if($searchNode->hasAttribute('data-put_page_content')) {
$custom_tag = $searchNode->nodeValue = "'; \$up_level = null; \$path_to_file = 'DATABASE/PAGES/' . basename(\$_SERVER['PHP_SELF'], '.php') . '.txt'; for(\$x = 0; \$x < 1; ) { if(is_file(\$up_level.\$path_to_file)) { \$x = 1; include(\$up_level.\$path_to_file); } else if(!is_file(\$up_level.\$path_to_file)) { \$up_level .= '../'; } }; echo '";
$custom_tag = $searchNode->setAttribute("data-mark", $theme_name);
$custom_tag = $dom->saveHTML($searchNode);
$root = $searchNode->parentNode;
$root->removeChild($searchNode);
$test = $dom->createTextNode("<?php echo '$custom_tag'; ?>");
$root->appendChild($test);
$saved_file_in_HTML = $dom->saveHTML();
$saved_file = htmlspecialchars_decode($saved_file_in_HTML);
file_put_contents("../THEMES/ACTIVE/". $theme_name ."/" . $trimed_file, $saved_file);
copy("../THEMES/ACTIVE/" . $theme_name . "/structure/index.php", "../THEMES/ACTIVE/" . $theme_name ."/index.php");
header("Location: editor.php");
}
FINAL EDIT:
If you want to have > or < using PHP DOMs methods, it is working using createTextNode() method.
The original question appears to concern how to use PHP to manufacture an HTML tag, so I'll address that question. While it is a good idea to use htmlentities(), you also need to be aware that it's primary purpose is to protect your code so that a malicious user doesn't inject it with javascript or other tags that could create security problems. In this case, the only way to generate HTML is to create HTML and PHP provides at least three ways to accomplish this feat.
You may write code such as the following:
<?php
define("LF_AB","<");
define("RT_AB",">");
echo LF_AB,"div",RT_AB,"\n";
echo "content\n";
echo LF_AB,"/div",RT_AB,"\n";
The code produces start and end div tags with some minimal content. Note, the defines are optional, i.e. one could code in a more straightforward fashion <?php echo "<"; ?> instead of resorting to using a define() to generate the left-angle tag character.
However, if one is wary of generating HTML in this manner, then you may also use html_entity_decode:
<?php
define("LF_AB",html_entity_decode("<"));
define("RT_AB",html_entity_decode(">"));
echo LF_AB,"div",RT_AB,"\n";
echo "content\n";
echo LF_AB,"/div",RT_AB,"\n";
This example treats the arguments to html_entity_decode as harmless HTML entities and then converts them into HTML left and right angle characters respectively.
Alternately, you could also take advantage of the DOM with PHP, even with an existing HTML page, as follows:
<?php
function displayContent()
{
$dom = new DOMDocument();
$element = $dom->createElement('div', 'My great content');
$dom->appendChild($element);
echo $dom->saveHTML();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<style>
div {
background:#ccbbcc;
color:#009;
font-weight:bold;
}
</style>
</head>
<body>
<?php displayContent(); ?>
</body>
</html>
Note: the Dom method createTextNode true to its name creates text and not HTML, i.e. the browser will only interpret the right and left angle characters as text without any additional meaning.
If I understand you correctly, I think you could use < and > in the first place. They should be rendered as HTML. Might save you some coding. Let me know if it works.
I'm currently working with Wordpress. I have a hook that runs before a <title> attribute is populated with text that a user enters in the dashboard.
Now I want to set a default title of each page to equal an <h1> attribute text value on a current page. A fragment of the callback function for the hook I'm working with would look like:
if (!$seoTitle) {
$seoTitle = '<....>';
}
return $seoTitle;
I want seoTitle to default to an <h1> element text on the current page. Is it doable? How can I achieve this?
I'm not totally sure how you get your HTML but you could parse it with the built in DOM parser.
<?php
$html = "<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading one</h1>
<p>This is a paragraph.</p>
<h1>This is a Heading two</h1>
<p>This is a paragraph.</p>
<h1>This is a Heading three</h1>
<p><a href='testwww'> This is a paragraph.</a></p>
</body>
</html>";
$dom = new DOMDocument();
$dom->loadHTML($html);
//If you want to get it from a website you could do the following:
//$dom->loadHTML(file_get_contents('http://www.w3schools.com/'));
// iterate through the html to get all h1 text
foreach($dom->getElementsByTagName('h1') as $heading) {
$h1 = $heading->nodeValue;
echo $h1 . "<br>";
}
?>
Assuming you have your HTML content within a variable and doing this after the page has fully loaded please take a look at the below example:
<?php
$htmlContent = '<html><body><h1>HELLO</h1></body></html>'; // change this to what you need
$seoTitle = preg_replace('/(.*)<h1>([^>]*)<\/h1>(.*)/is', '$2', $htmlContent);
echo $seoTitle; // will output: HELLO
?>
echo "<h1>".(string)$seoTitle."</h1>";
Should work. You can also break out of the php ?> and then type regular html and then break in when you wanna echo the variable.
I am new to PHP. I am trying to create a simple personal project where several coins move around the page when users refresh it from their browser. I keep on getting a weird error ().
This is what my file looks like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Treasure Map</title>
</head>
<body style="background-image:url(Bluemap.jpg); background-repeat: no-repeat">
<?php
$numberOfCoins = rand(3, 10);
while ($numberOfCoins) {
$xPosition = rand("10", "650");
$yPosition = rand("10", "400");
print '<div style="position: absolute;';
print 'left:' . $xPosition . 'px;';
print 'top:' . $yPosition . 'px">';
print '<img src="goldCoin.png" height="50px"/>';
print '</div>';
$numberOfCoins--;
}
?>
</body>
</html>
what am I doing wrong?
The file is an HTML document, therefore it cannot run PHP code.
You need to rename it from index3.html to index3.php and also make sure you are running it on a server that runs PHP
You should save the file as .php. This just shows the code itself, which means that it is not parsed.
Apart from that, your code is slightly off too.
The variable $numberOfCoins now contains a random number between 3 and 10. If you want to iterate a random number of times, an if loop might be more convenient:
$numberOfCoins = rand(3,10);
for($i = 0; $i < $numberOfCoins; $i++)
{
}
this is the first time that I need to work with smarty and it seems quite straight forward.
however, there is twist in my PHP code and that is causing an issue.
here is what I am trying to do:
Before you start beating me for not using mysqli functions etc, please note that this code is just a simple test for me to understand the smarty first. so i won't be using mysql in my project and I do not recommend anyone to do so...
any way, here is what I am trying to do:
I am using the following code in my index.php page:
<?php
header("Content-type: text/html; charset=utf-8");
function isSubdomain()
{
$host = $_SERVER['HTTP_HOST'];
$host = explode('.',$host);
$host = (is_array($host)?$host[0]:$host);
return $host;
}
?>
<?php
// These are the smarty files
require 'libs/Smarty.class.php';
// This is a file which abstracts the DB connecting functionality (Check out PEAR)
include "config/connect_to_mysql.php";
$smarty = new Smarty;
$smarty->compile_check = true;
$smarty->debugging = false;
$smarty->use_sub_dirs = false;
$smarty->caching = true;
// This SQL statement will get the 5 most recently added new items from the database
$storeShop = isSubdomain();
echo $storeShop;
$sql = 'SELECT * ';
$sql .= 'FROM $storeShop ';
$sql .= 'ORDER BY `id` ';
$result = mysql_query($sql) or die("Query failed : " . mysql_error());
// For each result that we got from the Database
while ($line = mysql_fetch_assoc($result))
{
$value[] = $line;
}
// Assign this array to smarty...
$smarty->assign('storeShop', $value);
// Assign this array to smarty...
$smarty->assign('$storeShop', $value);
// Display the news page through the news template
$smarty->display('index.tpl');
// Thanks to David C James for a code improvement :)
?>
and this is the index.tpl file:
<!-- This is the DOC type declaration and links in the CSS stylesheet etc -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<meta name="author" content="Steve Rendell" />
<meta name="generator" content="EditPlus" />
<link rel="stylesheet" type="text/css" href="style.css" title="Default CSS Sheet" />
<title>News Page</title>
</head>
<body id="top">
<!-- OK display the page header to keep it nice-->
<div id="header">
<span>Steve's News Page</span>
</div>
<!-- This is where the news article will be going -->
<div id="bodyText">
<!-- Have a title -->
<h1 id="welcome">Read All About It</h1>
<!-- OK this is a section which will loop round for every item in $news (passed in through from PHP) -->
{section name=storeShop loop=$storeShop}
<!-- For every item, display the Title -->
<h2 id="{$storeShop[$storeShop].id}">{$storeShop[storeShop].product_name}</h2>
<!-- Write out the Author information and the date -->
<h3>{$storeShop[storeShop].price}, {$storeShop[storeShop].details}</h3>
<!-- Now show the news article -->
{$storeShop[storeShop].details}
{/section}
</div>
<!-- Show copyright information etc -->
<div id="footer">All Contents Copy Written :)</div>
<!-- Close the html tags -->
</body>
</html>
when I run the index.php in my browser, I get the following error:
Query failed : Table 'mrshoppc_mainly.$storeShop' doesn't exist
But when I use the following code, I get the right output which is the name of the subdomain and the name of the table in mysql database as well:
$storeShop = isSubdomain();
echo $storeShop;
and I know the table exist. P.S. the table name $storeShop is dynamic, so it could be any name that user chooses and it will be created in the mysql database.
I hope I explained it good enough for someone to be able to help me.
Could someone please tell me why I get the mentioned error and how to solve it?
I suspect this is caused by smarty as I never used to get this error before I started using smarty.
Thanks in advance.
You are not parsing your string that contains the PHP variable.
$sql .= 'FROM $storeShop ';
To PHP single-quoted stings ' ' are literally what you have between the quotes.
" " Double quoted string will be Interpreted by PHP.
Try this:
$sql .= "FROM $storeShop "; // OR
$sql .= 'From '. $storeShop .' ';
PHP Strings
mis been a long time since i used smarty but from what i remeber there is no such thoing as:
{$storeShop[$storeShop].id}
you could use however:{$storeShop.$another_storeShop.id}
if $storeshop is like array('storeshop_key'=>array('id'->'id'))
also $smarty->assign('$storeShop', $value); will create variable $$storeShop which is not correct
tips: print arrays in php before sending to smarty var_dump($value) and then in smarty use {$storeShop|#print_r} to make sure everything is right
just remove
$smarty->assign('$storeShop', $value);
from your PHP code
I'm trying to echo a PHP tag by doing this:
echo "<?php echo \"test\"; ?>";
The result should be just "test" without quotes, but my code isn't working. What is happening is that nothing is shown on the page, but the source code is "<?php echo "teste"; ?>"
Most of you will want to know why I want to do this. I'm trying to make my own template system; the simplest way is just using file_get_contents and replacing what I want with str_replace and then using echo.
The problem is, that in the template file, I have to have some PHP functions that doesn't work when I echo the page, is there another simple way to do this? Or if you just answer my question will help a lot!
Here is an example of what I am trying to accomplish:
template.tpl:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[__TITULO__]</title>
</head>
<body >
<p>Nome: [__NOME__] <br />
Email: [__EMAIL__]<br />
<?php
if ($cidade != "") {?>
Cidade: [__CIDADE__]<br />
<?php
}
?>
Telefone: ([__DDD__]) [__TELEFONE__] <br />
Fax:
([__DDDFAX__]) [__FAX__] <br />
Interesse: [__INTERESSE__]<br />
Mensagem:
[__MENSAGEM__] </p>
</body>
</html>
index.php
<?php
$cidade = "Teste";
$file = file_get_contents('template.php');
$file = str_replace("[__TITULO__]","Esse Título é téste!", $file);
$file = str_replace("[__NOME__]","Cárlos", $file);
$file = str_replace("[__EMAIL__]","moura.kadu#gmail.com", $file);
if ($cidade != "") {
$file = str_replace("[__CIDADE__]",$cidade, $file);
}
echo $file;
?>
I can solve all this just not showing the div that has no content. like if i have a template, and in it i have 2 divs:
<div id="content1">[__content1__]</div>
<div id="content2">[__content2__]</div>
if the time that i set the content to replace the template I set the content1 and not set content 2 the div content2 will not show...
Use htmlspecialchars
That will convert the < > to < and >
You are dealing with two sets of source code here that should never be confused - the server code (PHP, which is whatever is in the <?php ?> tags) and the client (or browser) code which includes all HTML tags. The output of the server code is itself code that gets sent to the browser. Here you are in fact successfully echoing a PHP tag, but it is meaningless to the browser, which is why the browser ignores it and doesn't show anything unless you look at the client code that got sent to it.
To implement templates in this style, either they should not have any PHP code, or the resulting string (which you have stored in $file) should itself be executed as though it were PHP, rather than echoing it straight to the client. There are various ways to do this. One is to parse out the PHP tags in the string, echo everything that is not within the PHP tags and run eval() on everything that is.