Filemodes in Perl
O_RDONLY
Read only
O_WRONLY
Write only
O_RDWR
Read and write
O_CREAT
Create the file if it doesn’t exist
O_EXCL
Fail if the file already exists
O_APPEND
Append to the file
O_TRUNC
Truncate the file
O_NONBLOCK
Non-blocking access
Example use:
$path = "C:\\file.txt"; sysopen(FH, $path, O_RDONLY) or die $!;
Find specific words in file using Perl
open (INPUT, "< C:\\data\\test.txt") or die "Couldn't open C:\\data\\test.txt for reading: $!\n"; $char = "thisword"; while (<INPUT>) { print if /$char/; } close(INPUT);
Get file size and create time of file in PHP
All file have certain properties that can be displayed using PHP. These properties include the last access time, the last modified time, the last changed time, and the size of the file.
Example:
<HTML> <HEAD> <TITLE>Returning information about a file</TITLE> </HEAD> <BODY> <? print "The size of the file is "; print filesize( "samplefile.doc" ); print "<br>"; $atime = fileatime( "samplefile.doc" ); print "This file accessed on "; print date("l, M d, Y g:i a", $atime); print "<br>"; $mtime = filemtime( "samplefile.doc" ); print "This file was modified on "; print date("l, M d, Y g:i a", $mtime); print "<br>"; $ctime = filectime( "samplefile.doc" ); print "This file was changed on "; print date("l, M d, Y g:i a", $ctime); ?> </BODY> </HTML>
Calculate disk space used by files under a directory
The RecursiveDirectoryIterator extends the DirectoryIterator with a getChildren() method that provides access to the elements in a subdirectory. The RecursiveIteratorIterator flattens the hierarchy that the RecursiveDirectoryIterator returns into one list.
<?php $dir = new RecursiveDirectoryIterator('C:\wamp'); $totalSize = 0; foreach (new RecursiveIteratorIterator($dir) as $file) { $totalSize += $file->getSize(); } print "The total size is $totalSize.\n"; ?>
Create a temporary file to store program data in PHP
We can use the tempnam() function to generate a temporary filename in a specified directory.
<?php $temp = tempnam ("/home/w3/public_html", "someprefix"); ?>
The tempnam() function always creates a unique file in the directory specified and with the prefix specified. After the file is created, the name of the file is returned. We have to delete the file using the unlink() function.
@unlink ($temp) or die ("Cannot delete $temp");
Get file permissions of a file in PHP
We can use the fileperms() function to get the number value of the permissions, or use the is_* (is_dir(), is_executable(), is_file(), is_link(), is_readable(), and is_writable()) functions to get human-readable results.
Example Using fileperms():
<?php $fn = "/home/public_html/file.txt"; if ((fileperms ($fn) & 0777) != 0644) { chmod ($fn, 0644); // rw-r--r- } ?>
Example using the is_* functions:
<?php $fn = "/home/public_html/file.txt"; if (!is_readable ($fn)) { chmod ($fn, 0777); // rwxrwxrwx } ?>
Web Configuration files in asp.net
There is an advantage in ASP.NET of grouping individual pages together into an application is that we can set values to all these pages at one shot.That is by setting the properties of the application.The setting of values for the properties of an application that will control the application at runtime is known as configuring the ASP.NET application.
For eg , consider that we want to set the session state timeout property to 10 minutes.We can very well do this using the IIS snap-in of the MMC.Howerver,this would require the web server to restart for the changes to take effect.This is how configurration was done in the ages of ASP 3.0 and below.However,with ASP.NET coming into the picture configuration management has been drastically simplified.In ASP.NET all that we need to do to configure an application,is to create a configuration file called web.config and place it in the root directory of the application.The settings that we have provided in this file are applied through out the application including its sub-directories.This web.config is an XML based file.A web.config file that sets the session state time out property for the application would look like as shown in following example :-
<configuration> <system.web> <sessionState timeout ="10"/> </system.web> </configuration>
Additionally,in the days prior to ASP.NET,moving an application from one server to another was a cumbersome process.Not only all the files had to be copied but also all the controls and components had to be registered in the registry.With ASP.NET,doing the same is as simple as performing XCOPY operation (copying all the files along with their directory structure).ASP.NET provides you with configuration files to customize your website and also to push it to the edge of the envelope for your applications.However,the major advantage of using configuration files lies in the flexibility it has to offer to developers.Applications that makes full use of configuration files need not have information (that varies often) hard coded intothe code.This makes the web application more flexibilties as if enables the web admintrator to customize the values even after developing the application.Addtionaly,it provides a herarchical configuration infrastructure that enables extensible configuration data to be defined and throughoutan application,site or machine.
Fetching a URL with file_get_contents()
To retrieve the contents of a URL. For example, you want to include part of one web page in another page’s content, we can use the file_get_contents() function in php.
<?php $page = file_get_contents('http://www.w3mentor.com/robots.txt'); ?>
Working with directories in Isolated Storage in C#
Files can be stored in Isolated Storage under directories. Directories must be created using the CreateDirectory method of IsolatedStorageFile class.
IsolatedStorageFile mStore = IsolatedStorageFile.GetMachineStoreForAssembly(); mStore.CreateDirectory("dirname"); IsolatedStorageFileStream mStream = new IsolatedStorageFileStream(@"dirname\settings.ini", FileMode.Create, mStore);
The code above will create a file named settings.ini under a directory named dirname.
It is simple to read the file by opening the directory as shown below. The directory existence must be tested like the file existence before opening it. The GetDirectoryNames(filemask) method helps to find an existing directory.
string[] listofdirs = mStore.GetDirectoryNames("dirname"); if(directories.Length == 0) { Console.WriteLine("Dir not found"); mStore.CreateDirectory("dirname"); } else { Console.WriteLine("Dir exists"); }
PHP and cURL : Part 3 – cURL and HTTP requests
The four main cURL functions that will be used in a cURL script to load a web resource, read its content and display the content are :
resource curl_init ( [string url]) bool curl_setopt ( resource curl_handle, string option, mixed value) mixed curl_exec ( resource curl_handle) mixed curl_close ( resource curl_handle)
The general process for using the above functions flow as:
- Initialise Curl
- Set URL for the web resource to be loaded
- Retrieve and print the URL contents
- Close Curl
Example code:
<?php $curl = curl_init(); //initialize curl curl_setopt ($curl, CURLOPT_URL, "http://www.w3mentor.com"); //Set URL for the web resource to be loaded curl_exec ($curl); //Retrieve the URL contents curl_close ($curl); //close curl ?>
The curl_init() function returns a cURL instance for us to use and it takes an optional parameter as the URL to retrieve.
The curl_setopt() function takes three parameters. The first one is the instance of cURL. The second parameter is a constant value for the setting you want to change and the third parameter is the URL to the resource to work with.
The curl_exec() function takes a curl instance as the parameter and executes the request and returns a boolean true or false.
The curl_close() function takes a curl instance as the parameter. A call to this function closes the cURL session and frees up the associated memory.
We can capture the content returned by cURL by setting the CURLOPT_RETURNTRANSFER to 1.
<?php $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, "http://www.w3mentor.com"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec ($curl); curl_close ($curl); print $result; ?>
The contents of the site at http://w3mentor.com will be stored in the variable $result. We can manipulate the content easily now.
We can also have cURL write to a file directly by setting the CURLOPT_FILE parameter to a file pointer.
<?php $curl = curl_init(); $fp = fopen("outfile.txt", "w"); curl_setopt ($curl, CURLOPT_URL, "http://www.w3mentor.com"); curl_setopt($curl, CURLOPT_FILE, $fp); curl_exec ($curl); curl_close ($curl); ?>
The output from cURL is written to the file “outfile.txt”.
File upload related settings in php.ini
There are a few settings in the PHP configuration file (php.ini) related to file uploading:
- file_uploads = On/Off – Whether or not to allow HTTP file uploads.
- upload_tmp_dir = directory – The temporary directory used for storing files when doing file upload.
- upload_max_filesize = size – The maximum size of an uploaded file.
- max_file_uploads – Maximum number of file uploads allowed.
Upload and store files in Mysql using PHP : Part 2 – PHP file processing
To store uploaded files to MySQL database, you can use the normal INSERT statement as shown in the php example listed below:
<?php $con = mysql_connect("localhost", "", ""); mysql_select_db("w3m"); $error = $_FILES['w3img']['error']; $tmp_name = $_FILES['w3img']['tmp_name']; $size = $_FILES['w3img']['size']; $name = $_FILES['w3img']['name']; $type = $_FILES['w3img']['type']; print("\n"); if ($error == UPLOAD_ERR_OK && $size > 0) { $fp = fopen($tmp_name, 'r'); $content = fread($fp, $size); fclose($fp); $content = addslashes($content); $sql = "INSERT INTO fyi_files (name, type, size, content)" . " VALUES ('$name', '$type', $size, '$content')"; mysql_query($sql, $con); print("File stored.\n"); } else { print("Database Save for upload failed.\n"); } print(" \n"); mysql_close($con); ?>
The addslashes() function is used to add backslashes to special characters that need to be escaped in SQL statements.
Upload and store files in Mysql using PHP : Part 1 – Design MySql Table
A MySQL database can be used to store files uploaded using PHP.The table columns must be created using BLOB columns to hold the binary file.The blob column can hold up to 65,535 characters.
Example code:
<?php $con = mysql_connect("localhost", "", ""); mysql_select_db("w3m"); $sql = "CREATE TABLE updfiles (" . " id INTEGER NOT NULL AUTO_INCREMENT" . ", name VARCHAR(80) NOT NULL" . ", type VARCHAR(80) NOT NULL" . ", size INTEGER NOT NULL" . ", content BLOB" . ", PRIMARY KEY (id)" . ")"; mysql_query($sql, $con); mysql_close($con); ?>
Check for empty files in http upload using PHP
Bad upload process could result in empty files and developers need to check for empty files before using them, because the PHP engine could give no error. For example, if a user typed a bad file name in the upload field and submitted the form, the PHP engine will take it as an empty file without raising any error.
<?php $file = '/tmp/w3img.gif'; $error = $_FILES['w3img']['error']; $tmp_name = $_FILES['w3img']['tmp_name']; print(" \n"); if ($error==UPLOAD_ERR_OK) { if ($_FILES['w3img']['size'] > 0) { move_uploaded_file($tmp_name, $file); print("File uploaded.\n"); } else { print("Loaded file is empty.\n"); } } else if ($error==UPLOAD_ERR_NO_FILE) { print("No files specified.\n"); } else { print("Upload failed.\n"); } print(" \n"); ?>
Detect http file upload errors in PHP
Errors that occur during file upload create an error code in $_FILES[$field]['error']. Possible error code values are:
- UPLOAD_ERR_OK (0) – There is no error, the file uploaded with success.
- UPLOAD_ERR_INI_SIZE (1) – The uploaded file exceeds the upload_max_filesize directive in php.ini.
- UPLOAD_ERR_FORM_SIZE (2) – The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
- UPLOAD_ERR_PARTIAL (3) – The uploaded file was only partially uploaded.
- UPLOAD_ERR_NO_FILE (4) – No file was uploaded.
- UPLOAD_ERR_NO_TMP_DIR (5) – Missing a temporary folder.
<?php $file = '/tmp/w3image.gif'; $error = $_FILES['w3img']['error']; $tmp_name = $_FILES['w3img']['tmp_name']; print("<pre>\n"); if ($error==UPLOAD_ERR_OK) { move_uploaded_file($tmp_name, $file); print("File uploaded.\n"); } else if ($error==UPLOAD_ERR_NO_FILE) { print("No files specified.\n"); } else { print("Upload failed.\n"); } print("\n"); ?>
Move uploaded files to a different directory using PHP
PHP stores uploaded files in a temporary directory with temporary file names. It is a good practise to move uploaded files to a permanent directory, if you want to keep them permanently. The move_uploaded_file() function can be used to move uploaded files.
Example code:
<?php $file = '/tmp/w3image.gif'; print("<pre>\n"); move_uploaded_file($_FILES['w3img']['tmp_name'], $file); print("File uploaded: ".$file."\n"); print("
\n”);
?>
In a shared hosting environment, you may need to ask the administrators which directories you can use to store files.
Retrieve uploaded file information using PHP
When a file upload form posts the file to a Web server, the called PHP script specified in the form action attribute is used to process the file. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$field]['name'] – The Original file name on the browser system.
$_FILES[$field]['type'] – The file type determined by the browser.
$_FILES[$field]['size'] – The Number of bytes of the file content.
$_FILES[$field]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$field]['error'] – The error code associated with this file upload.
The $field is the name used in the tag.
using FORM tag appropriately for uploading files
The files specified in the will be transferred from the browser to the Web server by using a HTTP Post. This transferring (uploading) process is controlled by a properly written
Example:
<FORM ACTION=receiving.php METHOD=post ENCTYPE=multipart/form-data>
The METHOD must be “post” and ENCTYPE must be “multipart/form-data” in order for the process to work.
Example code:
<?php print("<html><form action=filesupload.php method=post enctype=multipart/form-data>\n"); print("Please submit an image file to w3mentor:<br>\n"); print("<input type=file name=imgfile><br>\n"); print("<input type=submit>\n"); print("</form></html>\n"); ?>
File Upload dialog using PHP and HTML
File upload allows visitors to specify a file on the browser’s system and submit it to the Web server. This is a useful feature for interactive Web sites.
To present an input field on your Web page to allow users to specify a local file to upload, the
<INPUT TYPE="FILE" ...>
tag is used inside a
<FORM ...>
tag. The
<INPUT TYPE="FILE" ...>
will be displayed as a text input field followed by a “browse” button. Users can either enter the full path name of a local file, or click Browse button to go through a dialog box to select a file interactively.
Example code:
<?php print("<html><form>\n"); print("<input type=file>\n"); print("<input type=submit>\n"); print("</form></html>\n"); ?>
Programatically monitor directory for changes using c#
To check for changes to a directory i.e a new file or folder added to the directory or a file or folder deleted from the directory, we must use the filesystemwatcher class. This class allows us to raise events when changes occur to a directory. We create a new FileSystemWatcher object, specifying the directory in the Path property and register for the Created and Deleted events. The events are turned on by setting EnableRaisingEvents to true.
Example code:
FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\mydir"; // Register for events watcher.Created += new FileSystemEventHandler(watcher_Changed); watcher.Deleted += new FileSystemEventHandler(watcher_Changed); // Start Watching watcher.EnableRaisingEvents = true; // Event Handler static void watcher_Changed(object sender,FileSystemEventArgs e) { Console.WriteLine("Directory changed({0}): {1}", e.ChangeType, e.FullPath); }
