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.
Related
I'm trying to put content into another file in the specific div. I tried file_put_contents and fopen, these are working but i want to put content in different way. I have different email template, so i'm trying to add the message and subject dynamically into the template in the specific div, once content added then i will get content from template and send the email.
What i'm trying
In the market_template.php i have a template where i'm showing the $_REQUEST values in the relevant div
<!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>Marketing Template</title>
</head>
<body>
<div class="main">
<div id="subject">
<?php
if(isset($_REQUEST['subject'])){
echo $_REQUEST['subject'];
}
?>
</div>
<div id="message">
<?php
if(isset($_REQUEST['message'])){
echo $_REQUEST['message'];
}?>
</div>
</div>
</body>
</html>
In my core.php i'm pushing the content through url query string and then i'm getting the market_template.php content.
// Getting content from file
$url = base_url.'market_template.php?eml_sub='.$subject.'&eml_msg='.$message;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
if(!empty($data)){
echo $data;
}
But the problem is that url query string does not adding full content into the template. For example i added in the URL
?eml_sub=This is test subject
But in the result i get only first word This the rest of content does not added and also second variable value is not adding.
So is there possible to put the value into another file and then get through php, i would like to appreciate. Thank you
As I said in the comment, in this part : ?eml_sub=This is test subject, it will take only the first word This because of the space in the URL.
One way to prevent that behavior is to use urlencode() function and urldecode() function after treatment.
Doc:
http://php.net/manual/en/function.urlencode.php
http://php.net/manual/en/function.urldecode.php
I am using a form to insert text into a MySQL database.
When the user keys in text manually into the form, the results are inserted into the database perfectly.
However if the user copies and pastes text from say another web page, there are hidden p tags which are sent to the database with the text. The tags are not viewable within the form itself but when submitted they are still sent to the database.
If I then use a MySQL SELECT statement to display the results on a web page, the unwanted tags are displayed and they break the layout of my web page!
Therefore I just need to know how I stop unwanted 'p' 'span' and 'div' tags from being inserted into my MySQL database when I copy and paste text from another web page.
The web form in question is part of a content management system that I am building. I need the form to be bullet proof from a user point of view. And the reality is that users will more than likely be copying and pasting text from other websites and also possibly from word documents and I need to ensure that no unwanted 'p' 'span' and 'div' tags are inserted into the database when copied and pasted from third party sources.
Here is my code for the form:
<!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>
<title>Untitled</title>
<script type="text/javascript" src="http://www.achcreative.net/ckeditor/ckeditor.js"></script>
<link href="../elite.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!--Begin Main Menu -->
<?php include("includes/menu.inc.php"); ?>
<!--End Main Menu -->
<h2 class="subheaderh2">Insert New News Entry</h2>
<form method="post" action="insert_news.php">
<input name="publish" type="hidden" id="publish" value="publish" />
<table>
<tr><td><p>News Title:</p></td></tr>
<tr><td><input name="newstitle" type="text" size="43" id="newstitle"></td></tr>
<tr><td><p>News Article:</p></td></tr>
<tr><td><textarea name="newsarticle" cols="40" rows="10" id="newsarticle"></textarea>
<script type="text/javascript">
//<![CDATA[
// Replace the <textarea id="editor"> with an CKEditor
// instance, using default configurations.
CKEDITOR.replace( 'newsarticle',
{
toolbar :
[
[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
]
});
//]]>
</script>
</td></tr>
<tr><td height="30" colspan="2"><input type="submit" value="Submit"></td></tr>
</table></form>
<p>Return</p>
</body>
</html>
Here is my code for the form processing script:
<!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>
<title>Untitled</title>
</head>
<body>
<h2 class="subheaderh2">News Entry Results</h2>
<?php
// create short variable names
$newstitle=$_POST['newstitle'];
$newsarticle=$_POST['newsarticle'];
$publish=$_POST['publish'];
if (!$newstitle || !$newsarticle)
{
echo '<p>You have not entered all the required details.<br />'
.'Please go back and try again.</p>'
.'<p>Return</p>';
exit;
}
if (!get_magic_quotes_gpc())
{
$newstitle = addslashes($newstitle);
$newsarticle = addslashes($newsarticle);
}
$time = date("l jS F Y - g:iA");
// connect to the database
include('../connect-db.php');
/* Create the prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO news (id, newstitle, newsarticle, date, archive) values (NULL, ?, ?, NOW(), ?)")) {
/* Bind our params */
$stmt->bind_param('sss', $newstitle, $newsarticle, $publish);
/* Set our params */
$newstitle=$_POST['newstitle'];
$newsarticle=$_POST['newsarticle'];
$publish=$_POST['publish'];
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "{$newstitle}";
echo "<br />{$newsarticle}";
echo "Inserted into database on: ";
echo "$time";
echo "<br />";
echo "<br />";
echo 'view results';
/* Close the statement */
$stmt->close();
}
else {
/* Error */
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
/* close our connection */
$mysqli->close();
?>
</body>
</html>
Many thanks in advance
Regards
Andrew
I want to point out that your code is vulnerable to XSS.
Now back to your question:
you probably use a html editor. Try to strip remove unwanted tags before them go submitted with javascript and onsubmit attribute. You can strip the tags with following regex:
value_of_editor.replace(/<[^>]+>/g,'');
Also make sure to dont output raw html but escape html before sending html to client.
Update:
It's not necessary to put escaped message to database - i think its just waste of length of data. And you should always check what you are outputting to client.
CKEditor offers a large number of configuration options that affect the final output of the content.
If you don't want HTML tags included when something is pasted into the editor, you can force paste operations to be text only, which will strip out HTML tags.
config.forcePasteAsPlainText = true;
It would be helpful if you could include an example of problematic content that is copied from another web page and pasted into the editor. Include the following three pieces.
1) The portion of the web page that was copied.
2) The source code from that web page for the portion that is being copied.
3) The source code of the CKEditor content after the paste operation.
To see the source code within the editor, you'll need to temporarily add the "Source" button back into your toolbar:
CKEDITOR.replace( 'newsarticle',
{
toolbar :
[
[ 'Source','Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
]
});
After the paste operation, click the source button and copy the content that was pasted. This will allow you to see exactly what is happening.
The list of configuration options is available here:
CKEditor 3 JavaScript API Documentation Namespace CKEDITOR.config
You should use the function strip_tags in order to strip (obvious) tags and potentially harmful code off of strings. (be it html or php code)
$foo = strip_tags('<b>code with html</b>'); // $foo will be "code with html"
You can use the strip_tags() function on the text that needs to be inserted in your database.
Here's the reference
I need to count the no. of lines of inline java script between script tags in php files. How do I do it? Will grep linux command suffice or I can get some tool to do it? Please help.
You might use a regular expression like to extract the content of each SCRIPT tag in your files and than count the \n occurrences within the content.
This regex should match all script tag including the opening and closing tag:
/<script[^>]*?>(.*)?</script>/sm
You should than remove the tags and lines without any code to count the real lines of JavaScript code.
Please take a look on the following code,it works but you may need to updates as per your requirements
<?php
$file = file('thisfile.php');
for($i=0;$i<count($file);$i++)
{
if(trim($file[$i]) == "<script language=\"javascript\">")
{
$start = $i.'<br>';
}
if(trim($file[$i]) == "</script>")
{
$end = $i.'<br>';
}
}
?>
<!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>
<script language="javascript">
var a = 10;
var b = 10;
var c = 10;
var d = 10;
var e = 10;
var e = 10;
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php echo ($end - $start)-1; ?>
</body>
</html>
save this php file as thisfile.php then try
Have a nice day
If you need to do this from a processed HTML page, use DOM to get all script tags without a src attribute. Then for each found node split the child TextNode by the linebreak or simple count them. Done.
If you need to grab this from actual PHP source code, use the Tokenizer to find T_STRINGS and similar parser tokens and analyze them for <script> blocks, but note that it might be impossible to find them all, if there is code like:
echo '<' . $scriptTag . '>' . $code . '</' . $scriptTag . '>';
because that wont be analyzable as a JavaScript String before PHP processed it.
Say you have a PHP variable called $description with the following value (that contains quotes and line breaks):
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
You want to pass the contents of this variable into a Javascript function that writes that value into an INPUT of type text.
How would you do this? I tried this:
$description = htmlspecialchars ( $product->description, ENT_QUOTES );
However, I get a JS error. I also tried this:
$description = rawurlencode ( $product->description );
This encodes the value like so:
Michael%20Kors%0A%0ATromp%20L%27oeil%20Sheath%20Dress%0A%0AYou%20will%20certainly%20%22trick%20the%20ey%22%20of%20many%20in%20this%20gorgeous%20illusion.%20Add%20it%20to%20your%20fall%20wardrobe%20before%20it%20disappears.%0A%0AAvailable%20in%20Black%2FNude
This value can be passed as a JS variable, but I don't know of a JS function that will cleanly reverse a PHP rawurlencode.
Is there a matching pair of functions that I could use to encode a variable in PHP to allow it to be passed into a JS function -- and then reverse the encoding in JS so that I get the original value of the PHP variable?
EDIT: To clarify the question and reply to comments, here is some test code:
<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<script type="text/javascript">
<?php
// this does not work with JS as i get an unterminated string literal if i just use addslashes in the following commented-out line
// echo 'alert(\'' . addslashes($str) . '\');';
// this works with JS (the alert activates) but how do i un-rawurlencode in JS?
// echo 'alert(\'' . rawurlencode($str) . '\');';
// this does not work with JS, because of the line breaks
echo 'alert(\'' . htmlspecialchars ($str, ENT_QUOTES) . '\');';
?>
</script>
simplest would be to use json_encode()
I ran into problems using some of the answers proposed here, including issues with line breaks and decoding certain html entitites like /. I ended up using rawurlencode (in PHP) and decodeURIComponent (in Javascript) as matching functions to encode/decode the string so it could be passed as a JS variable. Here is working code for anybody else running into this problem.
<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
Available in Black/Nude
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
<script type="text/javascript">
<?php
echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
?>
You can use json_encode if available. It encodes the string according to the JSON data format that is a subset of JavaScript; so any JSON is also valid JavaScript.
<script type="text/javascript">
<?php
echo 'alert('. json_encode($str).');';
?>
</script>
Otherwise try PHP’s rawurlencode and decode it with JavaScript’s decodeURI:
<script type="text/javascript">
<?php
echo 'alert(decodeURI("'. rawurlencode($str).'"));';
?>
</script>
Json is the solution.
See sample code
Two pages to demonstrate
First Page json.php
<!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>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
// This is more like it!
$('#submit').live('click', function() {
var id=$("#id").attr("value");
$.getJSON("json-call.php", {id:id}, function callback(data) {
$("#list").html("var1:"+data['var1']+"<br/>"+"var2:"+data['var2']+"<br />id:"+data['id']);
});
});
});
</script>
<input id="id" type="text" value="test value" />
<input type="button" id="submit" value="submit" />
<div id="list"></div>
</body>
</html>
Second Page json-call.php
$var1 = 'your name';
$var2 = 'your address';
$id = $_REQUEST['id'];
print(json_encode(array ('var1' => $var1, 'var2' => $var2, 'id'=>$id)));
and Results
var1:your name
var2:your address
id:test value
Not sure whether json_decode does everything you need. htmlspecialchars() and htmlspecialchars_decode() should do the trick for everything but the line breaks. The line breaks are kind of a pain, since the combination of linebreaks and carriage returns will depend on the browser, but I think something like this should work:
$value = "your string with quotes and newlines in it.";
//take cares of quotes
$js_value = htmlspecialchars($value);
//first line replaces an ASCII newline with a JavaScript newline
$js_value = str_replace("\n",'\n',$js_value);
//second line replaces an ASCII carriage return with nothing, so you don't get duplicates
$js_value = str_replace("\r",'',$js_value);
//reverse to convert it back to PHP
$php_value = str_replace('\n',"\r\n",$js_value);
$php_value = htmlspecialchars_decode($php_value);
Maybe not the most elegant solution, but that's not really my specialty. ;) Also, keep in mind that newline characters will just end up like spaces in an <input type="text"> field.
Here is a litle something I have made:
function safefor_js($str) {
return str_replace(array("'",'"',"\n"), array('\x22','\x27','\\n'), $str);
}
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
When I run player.php it's giving this error:
Warning: Cannot modify header information - headers already sent by (output started
at /www/110mb.com/m/u/s/i/c/k/i/n/musicking/htdocs/player.php:8) in
/www/110mb.com/m/u/s/i/c/k/i/n/musicking/htdocs/player.php on line 24
Can you please help?
<!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>Player</title>
</head>
<body>
<?php
if(isset($_POST["song"])&& $_POST['song'] != "")
{
$song = $_POST["song"];
}
else {$song=array();}
for ($i="0"; $i<count($song); $i++) {
}
//start of new php codep
// create doctype
//$array = array(
// 'song.mp3','song.mp3','song.mp3',
//);
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");
// create root element
$root = $dom->createElement("xml");
$dom->appendChild($root);
$i = "1";
foreach ($song as $counter) {
// create child element
$song = $dom->createElement("track");
$root->appendChild($song);
$song1 = $dom->createElement("path");
$song->appendChild($song1);
// create text node
$text = $dom->createTextNode($counter);
$song1->appendChild($text);
$song1 = $dom->createElement("title");
$song->appendChild($song1);
$text = $dom->createTextNode("song ".$i);
$song1->appendChild($text);
$i++;
}
// save and display tree
$dom->save("playlist.xml");
?>
<script type="text/javascript" src="swfobject.js">
</script>
<div id="flashPlayer">
This text will be replaced by the flash music player.
</div>
<script type="text/javascript">
var so = new SWFObject("playerMultipleList.swf", "mymovie", "295", "200", "7", "#FFFFFF");
so.addVariable("autoPlay","yes")
so.addVariable("playlistPath","playlist.xml")
so.write("flashPlayer");
</script>
</body>
</html>
The error message is triggering because of the HTML that appears before your first <?php tag. You cannot output anything before header() is called. To fix this error start your document with the <?php tag and only start outputting HTML after you are done handling the condition that outputs XML for flash.
A cleaner solution would be to separate out the XML generation for flash and the HTML output into different files.
The error message means that the php script has already sent output to the browser before calling the header() function or anything else that requires modifying the http headers.
it is really hard to try and diagnose where the problem is occuring without see the script properly formatted, but this line:
header("Content-Type: text/plain");
should be at the start of the script in php tags.
Seems that you're trying to use a Flash MP3 Player, but you're mixing up some things.
You're generating the XML playlist file on the same file that you have the player, you could do it, but I think that will be clearer and simpler to have lets say, a genPlayList.php file that will generate the XML file for you.
Then in your MP3 Player page you can have only a reference to that script:
....
so.addVariable("playlistPath","genPlayList.php");
....
like nav says, it means output has already been sent. In this case it's all the
<!DOCTYPE html PUBLIC ...
....
<body>
you got going on there.
You should move the entire php processing block before this.
Try to use javascript redirect instead of redirect with header.