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.
Related
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++)
{
}
I used #Alex's approach here to remove script tags from a HTML document using the built in DOMDocument. The problem is if I have a script tag with Javascript content and then another script tag that links to an external Javascript source file, not all script tags are removed from the HTML.
$result = '
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
hey
</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
alert("hello");
</script>
</head>
<body>hey</body>
</html>
';
$dom = new DOMDocument();
if($dom->loadHTML($result))
{
$script_tags = $dom->getElementsByTagName('script');
$length = $script_tags->length;
for ($i = 0; $i < $length; $i++) {
if(is_object($script_tags->item($i)->parentNode)) {
$script_tags->item($i)->parentNode->removeChild($script_tags->item($i));
}
}
echo $dom->saveHTML();
}
The above code outputs:
<html>
<head>
<meta charset="utf-8">
<title>hey</title>
<script>
alert("hello");
</script>
</head>
<body>
hey
</body>
</html>
As you can see from the output, only the external script tag was removed. Is there anything I can do to ensure all script tags are removed?
Your error is actually trivial. A DOMNode object (and all its descendants - DOMElement, DOMNodeList and a few others!) is automatically updated when its parent element changes, most notably when its number of children change. This is written on a couple of lines in the PHP doc, but is mostly swept under the carpet.
If you loop using ($k instanceof DOMNode)->length, and subsequently remove elements from the nodes, you'll notice that the length property actually changes! I had to write my own library to counteract this and a few other quirks.
The solution:
if($dom->loadHTML($result))
{
while (($r = $dom->getElementsByTagName("script")) && $r->length) {
$r->item(0)->parentNode->removeChild($r->item(0));
}
echo $dom->saveHTML();
I'm not actually looping - just popping the first element one at a time. The result: http://sebrenauld.co.uk/domremovescript.php
To avoid that you get the surprises of a live node list -- that gets shorter as you delete nodes -- you could work with a copy into an array using iterator_to_array:
foreach(iterator_to_array($dom->getElementsByTagName($tag)) as $node) {
$node->parentNode->removeChild($node);
};
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling PHP functions within HEREDOC strings
I am using Swiftmailer PHP to create an order complete page. When the customer lands on this page, I use an include to a PHP file.
This page file has SwiftMailer EOM HTML that gets sent to the customer. However I have the HTML parts in chunks, so the header is via a function called header and order totals are the same too. I want to be able to include EOM functions inside the EOM. Is this possible?
Id = 46088;
// MAIL FUNCTION
function mailToSend($Id){
// EOM CAN'T BE TABBED
$html = <<<EOM
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
getHeader($Id);
getOrderTotalBoxTable($Id);
</body>
</html>
EOM;
}
mailToSend(46088);
Like #deceze said, you can't, but this will work (extend #xenon comment to an example):
function getHeader($Id = '')
{
$text = '';
$text.=' Your first line of text, store it in an variable <br>';
$text.= 'Hello '.$Id.'<br>';
$text.='Your last text to be returned<br>';
return $text;
}
// MAIL FUNCTION
function mailToSend($Id){
$getHeader = getHeader($Id);
$getOrderTotalBoxTable = getOrderTotalBoxTable($Id);
// EOM CAN'T BE TABBED
$html = <<<EOM
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
$getHeader;
$getOrderTotalBoxTable;
</body>
</html>
EOM;
}
mailToSend(46088);
What you're talking about are Heredocs and they don't support function interpolation, only variable interpolation.
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.
Consider the following PHP code for getting RSS news on a site I'm developing:
<?php
$url = "http://dariknews.bg/rss.php";
$xml = simplexml_load_file($url);
$feed_title = $xml->channel->title;
$feed_description = $xml->channel->description;
$feed_link = $xml->channel->link;
$item = $xml->channel->item;
function getTheData($item){
for ($i = 0; $i < 4; $i++) {
$article_title = $item[$i]->title;
$article_description = $item[$i]->description;
$article_link = $item[$i]->link;
echo "<p><h3>". $article_title. "</h3></p><small>".$article_description."</small><p>";
}
}
?>
The data accumulated by this function should be presented in the following HTML format:
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Новини от Дарик</title>
</head>
<body>
<?php getTheData($item);?>
</body>
</html>
As you see I added windows-1251(cyrillic) and utf-8 encoding but the RSS feed is unreadable if I don't change the browser encoding to utf-8. The default encoding in my case is cyrilic but I get unreadable feed. Any help making this RSS readable in cyrilic(it's from Bulgaria) will be greatly appreciated.
I've just tested your code and the Bulgarian characters displayed fine when I removed the charset=windows-1251 meta tag and just left the UTF-8 one. Want to try that and see if it works?
Also, you might want to change your <html> tag to reflect the fact that your page is in Bulgarian like this: <html xmlns="http://www.w3.org/1999/xhtml" lang="bg" xml:lang="bg">
Or maybe you need to force the web server to send the content as UTF-8 by sending a Content-Type header:
<?php
header("Content-Type: text/html; charset=UTF-8");
?>
Just be sure to include this before ANY other content (even whitespace) is sent to the browser. If you don't you'll get the PHP "headers already sent" error.
Maybe you should take a look at htmlentities.
This can convert to html some characters.
$titleEncoded = htmlentities($article_title,ENT_XHTML,cp1251);