We have seen in Part 1 of this tutorial how to read the title tags of an html file. Now we will develop a script for reading all the title tags of the files present inside a directory. The basic script remains same and we will only be keeping this basic script within a while loop. This while loop will list all the files present inside a directory.
You must read how in part 1 we have developed the code to handle a file in read mode and collect the text between title tags. Also read how the directory handler works to display all the files.
Here is the code to handle the directory listing.
$path="../dir-name/";// Right your path of the directory
$handle=opendir($path);
while (($file_name = readdir($handle))!==false) {
We can open files of particular type by using its extensions. Here we will use one if condition to add or exclude different types of files. ( read more on stristr())
if(stristr($file_name,".php")){ // read the file now }
Rest of the code is same as part 1. So here is the complete code.
<?
///////////////function my_strip///////////
function my_strip($start,$end,$total){
$total = stristr($total,$start);
$f2 = stristr($total,$end);
return substr($total,strlen($start),-strlen($f2));
}
/////////////////////End of function my_strip ///
///////////// Reading of file content////
$i=0;
$path="../dir-name/";// Right your path of the file
$handle=opendir($path);
while (($file_name = readdir($handle))!==false) {
if(stristr($file_name,".php")){
$url=$path.$file_name;
$contents="";
$fd = fopen ($url, "r"); // opening the file in read mode
while($buffer = fread ($fd,1024)){
$contents .=$buffer;
}
/////// End of reading file content ////////
//////// We will start with collecting title part ///////
$t=my_strip("<title>","</title>",$contents);
echo $t;
echo "<br>";
$i=$i+1;
}
}
echo $i;
?>
Article Source
Thursday, October 30, 2008
Searching for All titles inside a directory of a page using PHP
Wednesday, October 29, 2008
Searching for title inside a file using PHP
We can collect the text written between two landmarks inside a file. These landmarks can be starting and ending of html tags. So what ever written within a tag can be copied or collected for further processing. Before we go for an example, read the tutorial on how to get part of a string by using one staring and ending strings.
Let us try to understand this by an example. We will try to develop a script which will search and collect the text written within the title tags of a page. Read here if you want to know more about title tags in an html page. Here is an example of title tag.
<title>This is the title text of a page</title>
As you can see within the page we can use starting and ending title tags or any pair of tags as two landmarks and collect the characters or string within it.
Now let us learn how to open a file and read the content. Here is the code part to do that.
$url="../dir-name/index.php";
$contents="";
$fd = fopen ($url, "r"); // opening the file in read mode
while($buffer = fread ($fd,1024)){
$contents .=$buffer;
}
Now as we have the content of the file stored in a variable $content , we will use our function my_strip ( read details about my_strip function here) to collect the title part only from the variable and print to the screen.
$t=my_strip("<title>","</title>",$contents);
echo $t;
With this we can give any URL and see the title of the file. This way like title tag we can read any other tag like meta keywords, meta description, body tag etc of a page. You can see many applications can be developed using this but let us try to develop few more things from this.
First is reading all the files of a directory and displaying all the titles of the files inside that directory
Second develop a hyperlink using these titles to query google for these titles. ( think why ? )
The above two codes we will discuss in next section. Before that here is the full code as we discussed in the above tutorial.
<?
///////////////function my_strip///////////
function my_strip($start,$end,$total){
$total = stristr($total,$start);
$f2 = stristr($total,$end);
return substr($total,strlen($start),-strlen($f2));
}
/////////////////////End of function my_strip ///
///////////// Reading of file content////
$url="../dir-name/index.php";// Right your path of the file
$contents="";
$fd = fopen ($url, "r"); // opening the file in read mode
while($buffer = fread ($fd,1024)){
$contents .=$buffer;
}
/////// End of reading file content ////////
//////// We will start with collecting title part ///////
$t=my_strip("<title>","</title>",$contents);
echo $t;
?>
Once we know the title text , we can go for str_ireplace command to replace the old title with new title and then write the content to file again.
Article Source
Getting the last updated time of the file in PHP
We can get the last updated date of any file by using filemtime function in PHP. This function returns date in UNIX Timestamp format and we can convert it to our requirement by using date function.
This function filemtime() uses the server file system so it works for local systems only, we can't use this function to get the modified time of any remote file system.
Here is the code to get the last modified date of any file. We are checking for a existing file ( test.php)
echo date("m/d/Y",filemtime(“test.php”));
The above code will display the modified date in month/day/year format.
Note that we have used date function to convert the Unix Timestamp time returned by filemtime() function.
Article Source
How to get the file name of the current loaded script using PHP ?
We can get the current file name or the file executing the code by using SCRIPT_NAME. This will give us the path from the server root so the name of the current directory will also be included. Here is the code.
$file = $_SERVER["SCRIPT_NAME"];
echo $file;
The above lines will print the present file name along with the directory name. For example if our current file is test.php and it is running inside my_file directory then the output of above code will be.
/my_file/test.php
We will add some more code to the above line to get the only file name from the above code. We will use explode command to break the string by using delimiter “/” .
As the output of this explode command is an array then we will collect the last element of this array to get our file name. Here the index of last element of the array is total element of the array minus one, because the index of the elements start from 0 ( not from one ). So index of the last element of the array = total number of elements – 1
Here is the code to get the last element of the array with the explode command to get the array.
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
Here $pfile is the variable which will have the value of present file name.
We can use $pfile in different application where current file name is required .
Here is the complete code.
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
echo $pfile;
Article Source
How to delete all the files in a directory using PHP ?
We have seen how a file can be deleted by using unlink function in PHP. The same function can be used along with directory handler to list and delete all the files present inside. We have discussed how to display all the files present inside a directory. Now let us try to develop a function and to this function we will post directory name as parameter and the function will use unlink command to remove files by looping through all the files of the directory.
Here is the code to this.
function EmptyDir($dir) {
$handle=opendir($dir);
while (($file = readdir($handle))!==false) {
echo "$file
";
@unlink($dir.'/'.$file);
}
closedir($handle);
}
EmptyDir('images');
Here images is the directory name we want to empty
Article Source
How to delete a file using PHP ?
We can delete files by giving its URL or path in PHP by using unlink command. This command will work only if write permission is given to the folder or file. Without this the delete command will fail. Here is the command to delete the file.
unlink($path);
Here $path is the relative path of the file calculated from the script execution. Here is an example of deleting file by using relative path
$path="images/all11.css";
if(unlink($path)) echo "Deleted file ";
We have used if condition to check whether the file delete command is successful or not. But the command below will not work.
$path="http://domainname/file/red.jpg";
if(unlink($path)) echo "Deleted file ";
The warning message will say unlink() [function.unlink]: HTTP does not allow unlinking
Article Source
How to write to a file using PHP
We can write to a file by using fwrite() function PHP. Please note that we have to open the file in write mode and if write permission is there then only we can open it in write mode. If the file does not exist then one new file will be created. We can change the permission of the file also. You can read the content of a file by using fopen() function in PHP. This is the way to write entries to a guestbook, counter and many other scripts if you are not using any database for storing data. . Here we will see how to write to a file.
<?
$body_content="This is my content"; // Store some text to enter inside the file
$file_name="test_file.txt"; // file name
$fp = fopen ($file_name, "w");
// Open the file in write mode, if file does not exist then it will be created.
fwrite ($fp,$body_content); // entering data to the file
fclose ($fp); // closing the file pointer
chmod($file_name,0777); // changing the file permission.
?>
PHP File open to read internal file
WE can open a file or a URL to read by using fopen() function of PHP. While opening we can give mode of file open ( read, write.. etc ). By using fopen we can read any external url also. We can write to a file by using fwrite function. Let us start with reading one internal file ( of the same site ). We have a file name as delete.htm. We will use the command fopen() to open the file in read mode.
We will be using fread() function to read the content by using a file pointer. Fread() reads up to lengthbytes from the file pointer referenced by fd. Reading stops when length bytes have been read or EOF is reached, whichever comes first.
We have also used the function filesize() to know the size of the file and used it in the fread function.
We will be using all these functions to read the content of another file and print the content as out put. Here is the code.
<?
$filename = "delete.htm"; // This is at root of the file using this script.
$fd = fopen ($filename, "r"); // opening the file in read mode
$contents = fread ($fd, filesize($filename)); // reading the content of the file
fclose ($fd); // Closing the file pointer
echo $contents; // printing the file content of the file
?>
Article Source
JavaScript and memory leaks
Credits: This tutorial is written by Volkan. He runs the site Sarmal.com, a bilingual site featuring all his work, products, services, and up-to-date profile information in English and Turkish.
If you are developing client-side re-usable scripting objects, sooner or later you will find yourself spotting out memory leaks. Chances are that your browser will suck memory like a sponge and you will hardly be able to find a reason why your lovely DHTML navigation's responsiveness decreases severely after visiting a couple of pages within your site.
A Microsoft developer Justing Rogers has described IE leak patterns in his excellent article.
In this article, we will review those patterns from a slightly different perspective and support it with diagrams and memory utilization graphs. We will also introduce several subtler leak scenarios. Before we begin, I strongly recommend you to read that article if you have not already read.
Why does the memory leak?
The problem of memory leakage is not just limited to Internet Explorer. Almost any browser (including but not limited to Mozilla, Netscape and Opera) will leak memory if you provide adequate conditions (and it is not that hard to do so, as we will see shortly). But (in my humble opinion, ymmv etc.) Internet Explorer is the king of leakers.
Don't get me wrong. I do not belong to the crowd yelling "Hey IE has memory leaks, checkout this new tool [link-to-tool] and see for yourself". Let us discuss how crappy Internet Explorer is and cover up all the flaws in other browsers".
Each browser has its own strengths and weaknesses. For instance, Mozilla consumes too much of memory at initial boot, it is not good in string and array operations; Opera may crash if you write a ridiculously complex DHTML script which confuses its rendering engine.
Although we will be focusing on the memory leaking situations in Internet Explorer, this discussion is equally applicable to other browsers.
A simple beginning
[Exhibit 1 - Memory leaking insert due to inline script]
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
var parentDiv =
document.createElement("<div onclick='foo()'>");
parentDiv.bigString = new Array(1000).join(
new Array(2000).join("XXXXX"));
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
The first assignment parentDiv=document.createElement(...); will create a div element and create a temporary scope for it where the scripting object resides. The second assignment parentDiv.bigString=... attaches a large object to parentDiv. When LeakMemory() method is called, a DOM element will be created within the scope of this function, a very large object will be attached to it as a member property and the DOM element will be de-allocated and removed from memory as soon as the function exits, since it is an object created within the local scope of the function.
When you run the example and click the button a few times, your memory graph will probably look like this:
No visible leak huh? What if we do this a few hundred times instead of twenty, or a few thousand times? Will it be the same? The following code calls the assignment over and over again to accomplish this goal:[Exhibit 2 - Memory leaking insert (frequency increased) ]
And here follows the corresponding graph:
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
for(i = 0; i < 5000; i++){
var parentDiv =
document.createElement("<div onClick='foo()'>");
}
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
The ramp in the memory usage indicates leak in memory. The horizontal line (the last 20 seconds) at the end of the ramp is the memory after refreshing the page and loading another (about:blank) page. This shows that the leak is an actual leak and not a pseudo leak. The memory will not be reclaimed unless the browser window and other dependant windows if any are closed.
Assume you have a dozen pages that have similar leakage graph. After a few hours, you may want to restart your browser (or even your PC) because it just stops responding. The naughty browser is eating up all your resources. However, this is an extreme case because Windows will increase the virtual memory size as soon as your memory consumption reaches a certain level.
This is not a pretty scenario. Your client/boss will not be very happy, if they discover such a situation in the middle of a product showcase/training/demo.
A careful eye may have caught that there is no bigString in the second example. This means that the leak is merely because of the internal scripting object (i.e. the anonymous script onclick='foo()'). This script was not deallocated properly. This caused memory leak at each iteration. To prove our thesis let us run a slightly different test case:[Exhibit 3 - Leak test without inline script attached]
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
for(i = 0; i < 50000; i++){
var parentDiv =
document.createElement("div");
}
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
And here follows the corresponding memory graph:
JavaScript and memory leaks
Credits: This tutorial is written by Volkan. He runs the site Sarmal.com, a bilingual site featuring all his work, products, services, and up-to-date profile information in English and Turkish.
If you are developing client-side re-usable scripting objects, sooner or later you will find yourself spotting out memory leaks. Chances are that your browser will suck memory like a sponge and you will hardly be able to find a reason why your lovely DHTML navigation's responsiveness decreases severely after visiting a couple of pages within your site.
A Microsoft developer Justing Rogers has described IE leak patterns in his excellent article.
In this article, we will review those patterns from a slightly different perspective and support it with diagrams and memory utilization graphs. We will also introduce several subtler leak scenarios. Before we begin, I strongly recommend you to read that article if you have not already read.
Why does the memory leak?
The problem of memory leakage is not just limited to Internet Explorer. Almost any browser (including but not limited to Mozilla, Netscape and Opera) will leak memory if you provide adequate conditions (and it is not that hard to do so, as we will see shortly). But (in my humble opinion, ymmv etc.) Internet Explorer is the king of leakers.
Don't get me wrong. I do not belong to the crowd yelling "Hey IE has memory leaks, checkout this new tool [link-to-tool] and see for yourself". Let us discuss how crappy Internet Explorer is and cover up all the flaws in other browsers".
Each browser has its own strengths and weaknesses. For instance, Mozilla consumes too much of memory at initial boot, it is not good in string and array operations; Opera may crash if you write a ridiculously complex DHTML script which confuses its rendering engine.
Although we will be focusing on the memory leaking situations in Internet Explorer, this discussion is equally applicable to other browsers.
A simple beginning
Let us begin with a simple example:
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
var parentDiv =
document.createElement("<div onclick='foo()'>");
parentDiv.bigString = new Array(1000).join(
new Array(2000).join("XXXXX"));
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
The first assignment parentDiv=document.createElement(...); will create a div element and create a temporary scope for it where the scripting object resides. The second assignment parentDiv.bigString=... attaches a large object to parentDiv. When LeakMemory() method is called, a DOM element will be created within the scope of this function, a very large object will be attached to it as a member property and the DOM element will be de-allocated and removed from memory as soon as the function exits, since it is an object created within the local scope of the function.
When you run the example and click the button a few times, your memory graph will probably look like this:
Increasing the frequency
No visible leak huh? What if we do this a few hundred times instead of twenty, or a few thousand times? Will it be the same? The following code calls the assignment over and over again to accomplish this goal:
[Exhibit 2 - Memory leaking insert (frequency increased) ]
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
for(i = 0; i < 5000; i++){
var parentDiv =
document.createElement("<div onClick='foo()'>");
}
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
And here follows the corresponding graph:
The ramp in the memory usage indicates leak in memory. The horizontal line (the last 20 seconds) at the end of the ramp is the memory after refreshing the page and loading another (about:blank) page. This shows that the leak is an actual leak and not a pseudo leak. The memory will not be reclaimed unless the browser window and other dependant windows if any are closed.
Assume you have a dozen pages that have similar leakage graph. After a few hours, you may want to restart your browser (or even your PC) because it just stops responding. The naughty browser is eating up all your resources. However, this is an extreme case because Windows will increase the virtual memory size as soon as your memory consumption reaches a certain level.
This is not a pretty scenario. Your client/boss will not be very happy, if they discover such a situation in the middle of a product showcase/training/demo.
A careful eye may have caught that there is no bigString in the second example. This means that the leak is merely because of the internal scripting object (i.e. the anonymous script onclick='foo()'). This script was not deallocated properly. This caused memory leak at each iteration. To prove our thesis let us run a slightly different test case:
[Exhibit 3 - Leak test without inline script attached]
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
for(i = 0; i < 50000; i++){
var parentDiv =
document.createElement("div");
}
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
And here follows the corresponding memory graph:
As you can see, we have done fifty thousand iterations instead of 5000, and still the memory usage is flat (i.e. no leaks). The slight ramp is due to some other process in my PC.
Let us change our code in a more standard and somewhat unobtrusive manner (not the correct term here, but can't find a better one) without embedded inline scripts and re-test it.
Article Source
Dynamically removing/ replacing an external JavaScript or CSS file
Any external JavaScript
or CSS file, whether added manually or dynamically, can be removed from the page. The end result may not be fully what you had in mind, however. I'll talk about this a little later.
Dynamically removing an external JavaScript
or CSS file
To remove an external JavaScript or CSS file from a page, the key is to hunt them down first by traversing the DOM, then call DOM's removeChild() method to do the hit job. A generic approach is to identify an external file to remove based on its file name, though there are certainly other approaches, such as by CSS class name. With that in mind, the below function removes any external JavaScript or CSS file based on the file name entered:function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page
removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page
The function starts out by creating a collection out of either all "SCRIPT" or "LINK" elements on the page depending on the desired file type to remove. The corresponding attribute to look at also changes accordingly ("src" or "href" attribute). Then, the function sets out to loop through the gathered elements backwards to see if any of them match the name of the file that should be removed. There's a reason for the reversed direction- if/whenever an identified element is deleted, the collection collapses by one element each time, and to continue to cycle through the new collection correctly, reversing the direction does the trick (it may encounter undefined elements, hence the first check for allsuspects[i] in the if statement). Now, to delete the identified element, the DOM method parentNode.removeChild() is called on it.
So what actually happens when you remove an external JavaScript or CSS file? Perhaps not entirely what you would expect actually. In the case of JavaScript, while the element is removed from the document tree, any code loaded as part of the external JavaScript file remains in the browser's memory. That is to say, you can still access variables, functions etc that were added when the external file first loaded (at least in IE7 and Firefox 2.x). If you're looking to reclaim browser memory by removing an external JavaScript, don't rely on this operation to do all your work. With external CSS files, when you remove a file, the document does reflow to take into account the removed CSS rules, but unfortunately, not in IE7 (Firefox 2.x and Opera 9 do).
Dynamically replacing an external JavaScript or CSS file
Replacing an external JavaScript or CSS file isn't much different than removing one as far as the process goes. Instead of calling parentNode.removeChild(), you'll be using parentNode.replaceChild() to do the bidding instead:function createjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
return fileref
}
function replacejscssfile(oldfilename, newfilename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
var newelement=createjscssfile(newfilename, filetype)
allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
}
}
}
replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"
Notice the helper function createjscssfile(), which is essentially just a duplicate of loadjscssfile() as seen on the previous page, but modified to return the newly created element instead of actually adding it to the page. It comes in handy when parentNode.replaceChild() is called in replacejscssfile() to replace the old element with the new. Some good news here- when you replace one external CSS file with another, all browsers, including IE7, will reflow the document automatically to take into account the new file's CSS rules.
Conclusion
So when is all this useful? Well, in today's world of Ajax
and ever larger web applications
, being able to load accompanying JavaScript/ CSS files asynchronously and on demand is not only handy, but in some cases, necessary. Have fun finding out what they are, or implementing the technique. :)
Article Source
Thanks,
Webnology Blog Administrator


