The kernel


The kernel is a piece of software that, roughly speaking, provides a layer between the hardware and the application programs running on a computer. In a strict, computer-science sense, the term 'Linux' refers only to the kernel - the bit that Linus Torvalds wrote in the early 90s.

The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.

Php Directory Functions


  • chdir — Change directory
  • chroot — Change the root directory
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path

File Manipulation

11.3. File Manipulation

There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't connect to the database. It'd be impossible to keep this information in the database, since it's not available at exactly the time you'd need to write to it. PHP provides functions for file manipulation that can perform the following:
  • Check the existence of a file
  • Create a file
  • Append to a file
  • Rename a file
  • Delete a file

The file_exists.php script checks to see if the file is there
<?php
  $file_name="file_exists.php";

  if(file_exists($file_name)) {
    echo ("$file_name does exist.");
  }
  else {
    echo ("$file_name does not exist.");
  }
?>

As you would expect, the file does exist:
The file exists.php does exist. 
 
PHP provides several functions to tell you about various file attributes. PHP has the ability to read data from, and write data to, files on your system. However, it doesn't just stop there. It comes with a full-featured file-and-directory-manipulation API that allows you to:
  • View and modify file attributes
  • Read and list directory contents
  • Alter file permissions
  • Retrieve file contents into a variety of native data structures
  • Search for files based on specific patterns
All of this file manipulation through the API is robust and flexible. These characteristics are why we're writing this book. PHP has a lot of great commands, including all the file manipulation ones.
11.3.1.1. Permissions
Now that you know a file exists, you may think you're done, but you're not. Just because it's there doesn't mean you can read, write, or execute the file. To check for these attributes, use is_readable to check for read access, is_writable to check for write access, and is_executable to check for the ability to execute the file. Each function takes a filename as its parameter. Unless you know the file is in the same directory as your script, you must specify a full path to the file in the filename. You can use concatenation to put the path and filename together, as in:
$file_name = $path_to_file . $file_name_only; 
                                  
 
 
 
 

Including and Requiring PHP Files

To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program. However, PHP provides four functions that enable you to insert code from other files.
  • include
  • require
  • include_once
  • require_once
All the include and require functions can take a local file or URL as input, but they cannot import a remote file. require and include functions are pretty similar in their functionality except for the way in which they handle an irretrievable resource. For example, include and include_once provide a warning if the resource cannot be retrieved and try to continue execution of the program. The require and require_once functions provide stop processing of the particular page if they can't retrieve the resource. Now we're going to get more specific about these four functions.

Defining Functions

There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement:
function some_function([arguments]) { code to execute }

The brackets ([ ]) mean optional. The code could also be written with optional_arguments in place of [arguments]. The function keyword is followed by the name of the function. Function names abide by the same rules as other named objects such as variables in PHP. A pair of parentheses must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly brackets, as seen in the code above.
You can define functions anywhere in your code and call them from virtually anywhere. Scope rules apply. The scope of a variable is the context within which it's defined. For the most part, all PHP variables have only a single scope. A single scope spans included and required files as well. The function is defined on the same page or included in an include file. Functions can have parameters and return values that allow you to reuse code.
To create your own function that simply displays a different hello message, you would write:
 
<?php
function hi()
{
  echo ("Hello from function-land!");
}
//Call the function
hi();
?>

which displays:
Hello from function-land!

PHP - Echo

<?php
$myiString = "Hi!";
echo $myiString;
echo "<h5>I love  PHP!</h5>";
?>
 

Display:

Hi!
I love  PHP!
 A simple form example
 
 
1 <html>
 2 <head>
 3  <title>Building a Form</title>
 4 </head>
 5 <body>
 6  <form action="<?php echo($_SERVER['PHP_SELF']); ?>"
 7        method="get">
 8   <label>
 9         Search: <input type="text" name="search" />
 10    </label>
 11      <input type="submit" value="Go!" />
 12  </form>
 13 </body>
 14 </html>
 

PHP Configuration Directives

Although the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the code you write as well as the techniques that you employ, and your responsibilities might extend slightly beyond the application on occasion.

The configuration of PHP is primarily dictated by a file called php.ini. This file contains many configuration directives, and each of these affects a very specific aspect of PHP. If this file is absent, or if a particular configuration directive is absent from the file, a default value is used.
If you do not know the location of your php.ini file, you can use phpinfo( ) to determine where PHP expects to find it:
 
<?php

    phpinfo();

    ?>

PHP Sessions

The session_start( ) function is used to create a new session. A session is unique to the interaction between a browser and a web database application. If you use your browser to access several sites at once, you'll have several unrelated sessions. Similarly, if several users access your application each has their own session. However, if you access an application using two browsers (or two browser windows) at the same time, in most cases the browsers will share the same session; this can lead to unpredictable behavior—that's the reason why many web sites warn against it.

The first time a user requests a script that calls session_start( ), PHP generates a new session ID and creates an empty file to store session variables. PHP also sends a cookie back to the browser that contains the session ID. However, because the cookie is sent as part of the HTTP headers in the response to the browser, you need to call session_start( ) before any other output is generated

The session identifier generated by PHP is a random string of 32 hexadecimal digits, such as fcc17f071bca9bf7f85ca281094390b4. When a new session is started, PHP creates a session file, using the session identifier, prefixed with sess_, for the filename. For example, the filename associated with our example session ID on a Unix system is /tmp/sess_fcc17f071bca9bf7f85ca281094390b4.

Using Session Variables

The session_start( ) function is also used to find an existing session. If a call is made to session_start( ), and a session has previously been started, PHP attempts to find the session file and initialize the session variables. PHP does this automatically by looking for the session cookie in the browser request whenever you call session_start( ). You don't need to do anything different when starting a new session or restoring an existing one. Even if the identified session file can't be found, session_start( ) simply creates a new session file.


A simple PHP script that uses a session
<?php

  require_once "HTML/Template/ITX.php";



  // This call either creates a new session or finds an existing one.

  session_start( );



  // Check if the value for "count" exists in the session store

  // If not, set a value for "count" and "start"

  if (!isset($_SESSION["count"]))

  {

    $_SESSION["count"] = 0;

    $_SESSION["start"] = time( );

  }



  // Increment the count

  $_SESSION["count"]++;



  $template = new HTML_Template_ITX("./templates");

  $template->loadTemplatefile("example.10-2.tpl", true, true);



  $template->setVariable("SESSION", session_id( ));

  $template->setVariable("COUNT", $_SESSION["count"]);

  $template->setVariable("START", $_SESSION["start"]);

  $duration = time( ) - $_SESSION["start"];

  $template->setVariable("DURATION", $duration);



  $template->parseCurrentBlock( );



  $template->show( );

?>


Length of a String

The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string:
integer strlen(string subject)
We used strlen( ) earlier in the chapter to compare string lengths. Consider another simple example that prints the length of a 16-character string:
print strlen("This is a String");  // prints 16

Creating Arrays

PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:
$numbers = array(5, 4, 3, 2, 1);

$words = array("Web", "Database", "Applications");



// Print the third element from the array of integers: 3

print $numbers[2];



// Print the first element from the array of strings: "Web"

print $words[0];

By creating arrays this way, PHP assigns integer keys, or indexes to each element. By default, the index for the first element in an array is 0—this may seem odd but think of the index as an offset from the starting position in an array. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. You can also create an array by assigning elements to a new, unset variable. The following code fragment illustrates the bracket syntax with an array of strings:
$newArray[0] = "Potatoes";

$newArray[1] = "Carrots";

$newArray[2] = "Spinach";



// Replace the third element

$newArray[2] = "Tomatoes";

In this example, PHP automatically treats $newArray as an array without a call to array( ).
An empty array can be created by assigning to a variable the return value of array( ). Values can then be added using the bracket syntax. PHP automatically assigns the next numeric index as the key (the largest integer key value plus one) when a key isn't supplied. The result of the following fragment is an array containing three items.
$shopping = array( );



$shopping[] = "Milk";

$shopping[] = "Coffee";

$shopping[] = "Sugar";

It's also easy to print individual element values themselves:
print $shopping[0];   // prints "Milk"

print $shopping[1];   // prints "Coffee"

print $shopping[2];   // prints "Sugar"