Using session in PHP
What Is PHP Session Capable Of
PHP session is capable of storing the information in the form of session variables, in order to handle the ever-increasing traffic on a website. For instance, consider a shopping website, with products scattered in different categories and different pages. In such a situation, a user may switch from one page t another and keep on adding products from different pages to his or her shopping cart.
Memcache
The Memcache module also provides a session handler (memcache).
More information about memcached can be found at » http://www.danga.com/memcached/.
Below is one example
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."
\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)
\n";
$get_result = $memcache->get('key');
echo "Data from the cache:
\n";
var_dump($get_result);
?>
PHP Design Patterns
* Factory Patterns: The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.
* Singleton Patterns: The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
i got this good stuff from a newly coming website on PHP, http://www.e-php.info
metaphone — Calculate the metaphone key of a string
string metaphone ( string $str [, int $phones ] )
Calculates the metaphone key of str .
Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
Metaphone was developed by Lawrence Philips
quotemeta — Quote meta characters
Description
Returns a version of str with a backslash character (\) before every character that is among these:
. \ + * ? [ ^ ] ( $ )
Returns the string with meta characters quoted.
This function is
binary-safe.
parse_str — Parses the string into variables
- str
-
The input string.
- arr
-
If the second parameter arr is present, variables are stored in this variable as array elements instead.
void parse_str ( string $str [, array &$arr ] )
No value is returned.
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?> sha1 — Calculate the sha1 hash of a string
Returns the sha1 hash as a string.
$str = 'apple';
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
echo "Would you like a green or red apple?";
exit;
}
?> array_values — Return all the values of an array
Description
array_values() returns all the values from the input array and indexes numerically the array.
Example#1 array_values() example
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?> The above example will output:
Array
(
[0] => XL
[1] => gold
)
array_flip — Exchanges all keys with their associated values in an array
Description
array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.
Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.
If a value has several occurrences, the latest key will be used as its values, and all others will be lost.
Parameters
- trans
-
An array of key/value pairs to be flipped.
Return Values
Returns the flipped array on success and FALSE on failure.
Examples
Example#1 array_flip() example
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>
Example#2 array_flip() example : collision
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?> now $trans is:
Array
(
[1] => b
[2] => c
)
array_walk — Apply a user function to every member of an array
Description
Returns TRUE on success or FALSE on failure.
Applies the user-defined function funcname to each element of the array array. Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname .
If function funcname requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls funcname . These warnings may be suppressed by prepending the PHP error operator @ to the array_walk() call, or by using error_reporting().
Note: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.
Note: Passing the key and userdata to funcname was added in 4.0.0
array_walk() is not affected by the internal array pointer of array . array_walk() will walk through the entire array regardless of pointer position.
Users may not change the array itself from the callback function. e.g. Add/delete elements, unset elements, etc. If the array that array_walk() is applied to is changed, the behavior of this function is undefined, and unpredictable.
Example#1 array_walk() example
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2
\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?> The above example will output:
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple
readfile — Outputs a file
Description
Reads a file and writes it to the output buffer.
Parameters
- filename
-
The filename being read.
- use_include_path
-
You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.
- context
-
A context stream resource.
Return Values
Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.
session_cache_limiter('none'); //*Use before session_start()
session_start();
$file = 'ASDFGgg.pdf';
_Download("files_dir/".$file, $file);
function _Download($f_location,$f_name){
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($f_location));
header('Content-Disposition: attachment; filename=' . basename($f_name));
readfile($f_location);
}
?>is_uploaded_file — Tells whether the file was uploaded via HTTP POST
Description
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the clients machine $_FILES['userfile']['name'] does not work.
Parameters
- filename
-
The filename being checked.
Return Values
Returns TRUE on success or FALSE on failure.
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['userfile']['tmp_name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}
?> move_uploaded_file — Moves an uploaded file to a new location
Description
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination .
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
Parameters
- filename
-
The filename of the uploaded file.
- destination
-
The destination of the moved file.
ob_end_flush — Flush (send) the output buffer and turn off output buffering
Description
This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.
Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
Return Values
Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
ob_start — Turn on output buffering
Description
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
Parameters
- output_callback
-
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE.
If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.
If output_callback returns FALSE original input is sent to the browser.
The output_callback parameter may be bypassed by passing a NULL value.
ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.
Note: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.
- chunk_size
-
If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size . Default value 0 means that the function is called only in the end, other special value 1 sets chunk_size to 4096.
md5 — Calculate the md5 hash of a string
if ((md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Would you like a green or red apple?"; exit;}
?>