Dec
09
2008
13

Differences Between PHP 4 and 5

Language Features
• PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types.
• The foreach construct now supports by-reference declaration of the value element.
• A number of new functions, particularly for string and arraymanipulation, has also been added to the core platform.

Objects
• For all intents and purposes, all objects in PHP 5 are passed by reference. This means that assigning an object to a variable will not create a copy of the former, but simply creates another reference to it.
• Constants, aswell as staticmethods and properties, can nowbe definedwithin the scope of a class.
• Class methods and properties now feature visibility, and can be declared as public, private or protected. Classes and methods can also be declared as final to prevent further inheritance.
• Since all objects are assigned by reference, you now need a specialized mechanism to copy objects. This is provided by the clone construct and the __clone() magic method.
• PHP 5 features unified constructors and destructors—all constructors should now be named __construct(), and the new __destruct() magic method has been added for object destruction.
• With the addition of interfaces and abstract classes, PHP developers now have far greater control over how they implement their object-oriented code. Interfaces can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint.
• Class definitions can now be loaded on demand by using the __autoload() function.

Magic Methods
A multitude of new “magic” methods has been introduced in PHP 5:
• __get() and __set() are called when accessing or assigning an undefined object property, while __call() is executed when calling a non-existent method of a class.
• __isset() is called when passing an undefined property to the isset() construct.
• __unset() is called when passing an undefined property to unset().
• __toString() is called when trying to directly echo or print() an object.
• __set_state() is inserted dynamically by var_export() to allow for reinitialization on execution of var_export()’s output.

Selected New Extensions
• SimpleXML allows easy access to XML data using object and array notation.
• PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the formof the libxml2-based DOM and XSL extensions.
• The PHP Data Objects (PDO) extension provides a unified database access extension that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer—except for prepared queries, it does nothing to abstract the actual database code (SQL), itself.
• The hash extension is a new replacement for the GPLed libmhash; it was added to the PHP core starting with version 5.1.2. It can produce hashes using many algorithms, including the familiarMD5and SHA1, aswell as some more secure (albeit slower) algorithms, such as snefru.
• The Standard PHP Library (SPL) provides numerous interfaces that enhance the way classes interact with the PHP language, including the new Iterator interfaces.
• The new Reflection extension allows for runtime introspection of executing PHP code.

Error Management
• Classes now support exceptions; the new set_exception_handler() function allows you to define a script-wide exception handler.
• The E_STRICT error reporting level has been added to the language to emit notices when legacy or deprecated code is encountered.

(Thanks to PHP|architect’s Zend PHP 5 Certification Study Guide for this post)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 11. PHP 4/5 Differences |
Dec
09
2008
0

File Streams

Stream Connects
Steam connects allow us to pass options to the steam handlers that we use to access network resources. We can instruct HTTP stream to perform a POST operation, so we can use PHP to submit forms on others websites.

$options = array(’http’ => array(’user_agent’ => "PHP Browser",’max_redirects’ => 3));
$http_options = stream_context_create($options);
$file = file_get_contents("http://localhost/", false, $http_options);

As you can see the first line we set the options, we then pass them trough stream_create_context so we can then use it with file_get_contents. This will tell the sever we are connecting to that we are useing “PHP Browser” to view their website.

Advanced Stream Functionality
We can use PHP’s stream services to Create an Internet or Unix domain server socket using stream_socket_server(); like so:

$socket = stream_socket_server("tcp://0.0.0.0:1037");
while ($conn = stream_socket_accept($socket)) {
	fwrite($conn, "Hello World\n");
	fclose($conn);
}
fclose($socket);

As you can see we created a server on port 1037, we can then use other servers to connect to our server this server and get the contents like such:

$socket = stream_socket_client(’tcp://0.0.0.0:1037’);
while (!feof($socket)) {
echo fread($socket, 100);
}
fclose($socket);

Stream Filters
We can use stream filters with php so we can pass data in and out and alter them dynamically. Such as:
- Changing to uppercase
- Encode trough ROT-13 encoder
- Compress using bzip2
The filters are applied in a chain so you can set them up to run trough multiple filters you can then use the same multiple filters to get the correct end result at the client.

Server with filters:

$socket = stream_socket_server("tcp://0.0.0.0:1037");
while ($conn = stream_socket_accept($socket)) {
	stream_filter_append($conn, ’string.toupper’);
	stream_filter_append($conn, ’zlib.deflate’);
	fwrite($conn, "Hello World\n");
	fclose($conn);
}
fclose($socket);

In this example we apply filter “string.toupper” this will change it to upper case, an additional layer “zlib.deflate” filter compresses it.

The client with filters unencodeing:

$socket = stream_socket_client(’tcp://0.0.0.0:1037’);
stream_filter_append($socket, ’zlib.inflate’);
while (!feof($socket)) {
	echo fread($socket, 100);
}
fclose($socket);

In this example we do the opposite when created the server, the client must apply filter so that it is again readable therefore we use “zlib.inflate”

So as you can see PHP has so many levels, we can use REST to transfer data between servers but we can also create mini servers within our servers to talk to each other. Or we can just use file_get_contents to get files from other servers. The possibilities are endless!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 10. Streams and Network Programming |
Dec
09
2008
0

File System Functions

Streams and Network Programming - File System Functions

The PHP5 Zend Certification contains questions about file system functions, they do this so much that their free on-line sample test first question is:
How can precisely one byte be read from a file, pointed by $fp?
A) fseek($fp, 1)
B) fgets($fp, 1)
C) fgetss($fp, 1)
D) fgetc($fp)
E) All of the above
…. The answer? … If you read my last blogpost you’d go with fgets because “Gets line from file pointer” but that’s incorrect the correct answer is fgetc($fp);

Anyway, enough proving that you need to know all of this and lets get into it:

PHP File Functions (some)

PHP Functions
fopen($filename, $mode);

fopen("counter.txt", "a+");

The code above will open counter.txt file so we can do what we want. Read its data and even write data to the end of the file. The $mode where covered in the last blog post.
filesize($filename);

filesize("counter.txt");

This function gets the size of the givenfile in bytes, or FALSE.
filesize() may return unexpected results for files which are larger than 2GB. For files between 2GB and 4GB in size this can usually be overcome by using sprintf(”%u”, filesize($file)).
fgets($filepointer);

fgets($fp, $length);

$fp is the variable holding the contents of the file, must be provided by fopen() or fstockopen().
The file stops reading when the value of length-1 is reached, a new line or at End Of File (EOF), if no length is given it goes on until EOL.
ftruncate($fp, $length);

ftruncate($fp, "5");

This function truncates a file to a given length, it takes the variable holding the contents of the file (filepointer). It must be writeable (correct mode). The size variable tells us how much data we want, if the size is larger its filled with null bytes, if the size is smaller the extra data is lost.
fwrite($fp, $contents, $length);

fwrite($fp, "I will be saved to file", "23");

The function above saves files with the contents you want. The file perimeter needs to know the file pointer resource that was created using fopen(); . The second perimeter is what the contents of the file will be, the third perimeter is optional but is the length of the string we want to be saved. It will stop saving after the bytes specified in the length. If you use multiple fwrite on a filepointer, they will append each other.
feof($fp);

while(!feof($fp)){
	echo fgets($file). "<br />";
}

feof Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE. The code above will output each line until the EOF is reached, at which point the loop will end.
fread($fp, $length);

fread($fp, "20");

The fread function reads the contents of the loaded file from the file pointer. Reading stops as soon as the length is met, it reaches EOF, file is unreachable or 8192 bytes have been read.
This will obviously return the contents of the file, or FALSE if nothing s read.
fseek($fp, $offset, $whence );

fseek($fp, "10", SEEK_SET)

fseek uses the file pointer and gets contents from the file. The second perimeter is the length and depending on the third perimeter is how it will be gathered.
* SEEK_SET - Set position equal to offset bytes.
* SEEK_CUR - Set position to current location plus offset .
* SEEK_END - Set position to end-of-file plus offset .

readfile($file);

readfile("counter.txt");

This does exactly what it says on the tin, it reads the contents of a file and prints it to the script. readfile();.
file_get_contents($file,$incpath,$context,$offset,$maxlen);

file_get_contents("counter.txt");

Once again it does what it says, it gets the entire contents of a file and returns it to a string. Personaly I enter NULL in the second and third perimeter as ive had no use of these yet. The forth perimeter lets you ahve an offset what byte do you want to start reading the file and maxlen is the maximum length of the data you want to read.
file_put_contents($file, $contents, FILE_APPEND);

file_put_contents("counter.txt", "30 visitors today", FILE_APPEND);

Write a string to a file using this function, the first perimeter is the filename, the second is the data we want to write to the file. The third perimiter is known as flags, leave this empty or use FILE_APPEND if you want the new data, to be after the data that used to be in their. Their are some more.

chdir($directory);

echo getcwd() . "\n"; //prints /home/is-hacked/
echo file_exists('php.gif') //Prints FALSE
chdir('public_html'); //changes directory
echo getcwd() . "\n"; //prints /home/is-hacked/public_html/
file_exists('php.gif') //Prints TRUE

As you can see chdir changes the directory that is being used in the php script. If (most likely) safemode is on then chdir checks if you own the folder your moving to. You can then use other functions after the directory change.
getcwd();

echo getcwd(); //Display directory

This function returns the current working directory that the script is being run in.
mkdir($pathname, $mode, $recursive);

mkdir("newdir", 0666, true); //Make directory

The function allows you to create a new directory in the directory that you are currently in. The first perimeter is the directory name, the seccond is the mode you can read more about modes in chmod The function returns true or false, if it works or not.
rmdir($pathname);

rmdir("newdir"); //removes directory

This function DELETES the directory and files inside, it returns TRUE on deletion or false on failure
unlink($filename);

unlink("newfile.txt"); //removes file

You can delete files also using the unlink function, just enter the files name and have fun.
chmod($file, $mode);

chmod("/test/file.txt", 0666); //chmod file

The chmod function changes the files permissions, this can be done so you can make a file writeable, write to the file, then chmod it back to readable only. This is useful for security and such, When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

is_dir();

var_dump(is_dir('a_file.txt')); //Returns FALSE (is file)
var_dump(is_dir('public_html'));//Returns TRUE is active directory

This tells us weather a file name is a directory, as expected it returns true if the directory exists and false if it does not.
is_file($filename);

is_file("counter.txt"); //checks if file exists

Tells whether the filename is a regular file, returns TRUE if it is a file and FALSE if it is not.
is_readable($filename); and is_writable($filename);

is_readable("counter.txt"); //checks if path exists and is readable
is_writable("counter.txt"); //checks if path file exists and is writeable

It does what it says if the file is readable it returns true or false. If the file is writable it returns true of false.
is_uploaded_file($filename);

 is_uploaded_file("counter.txt"); //checks if path is an uploaded file

Ths returns TRUE if the file named was uploaded by a HTTP Post, this is useful for security. It is most likely used as such:

 is_uploaded_file($_FILES['userfile']['tmp_name']);
Written by Adam in: 10. Streams and Network Programming |
Dec
09
2008
0

PHP File Reading and Writing

Streams and Network Programming - File Reading and Writing

Whenever you access a file using fopen(), file(), readfile(), include, require and a multitude of other functions, PHP uses the functionality provided by the streams layer to do the actual “dirty work.”. PHP Streams allows us to access php input/output, standard file access, http resources, ftp and zlib compressed data. Their are other compressors that can be added such as rot13 and tools to manipulate stream data.

Reading File, Clearing File, Saving New File

//OPEN A FILE
$file = fopen("counter.txt", ’a+); //Load counter.txt
if ($file == false) { //make sure it opened correctly
	die ("Unable to open/create file");
}
 
//CHECK FILE
if (filesize("counter.txt") == 0) {
	$counter = 0; //if file contains no size the counter must be 0
} else {
	$counter = (int) fgets($file); //Get a number from counter.txt
}
 
//CLEAR DATA FROM FILE
ftruncate($file, 0); //truncate file (remove all data)
 
//UPDATE GATHERED DATA
$counter++; //Increase value by one
//Save New Data
fwrite($file, $counter);
//End User Output
echo "There has been $counter hits to this site.";

In the example above as the comments show, we easily OPEN a file using file mode a+ allowing us to read and save files. We then check the file see if the size is 0, if it is then it contains no data, so for rest of script to work we set counter to 0, if it does have a size we read its data. Once all this is done we delete the data from the file, increase the counter and write the new value to the (now) empty document.
w3schools examples

File Modes

  • r Read only. Starts at the beginning of the file
  • r+ Read/Write. Starts at the beginning of the file
  • w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
  • w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
  • a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
  • a+ Read/Append. Preserves file content by writing to the end of the file
  • x Write only. Creates a new file. Returns FALSE and an error if file already exists
  • x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

These are used along with fopen() to do your desired manipulation.
Each of these modes can be coupled with a modifier that indicates how the data is to be read and written: the b flag (e.g.: w+b) forces “binary” mode, which will make sure that all data is written to the file unaltered. There is also a Windows only flag, t, which will transparently translate UNIX newlines (\n) to Windows newlines (\r\n). In addition, the w, w+, a, and a+ modes will automatically create a new file if it doesn’t yet exist; in contrast, x and x+ will throw an E_WARNING if the file already exists.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 10. Streams and Network Programming |
Dec
09
2008
0

XML: XPath

XPath (XML Path Language) is used to access and search XML documents, it is a query language for retrieving data from an XML document. XPath can be complex. SimpleXML uses xpath like such SimpleXMLElement::xpath(); if used on root element it will search the entire xml document or if used on a child it will search the entire child.

XPath reutns an array of SimpleXMLElment objects, here is an example of searching root and child

// Search the root element
$results = $library-&gt;xpath(/library/book/title’);
foreach ($results as $title){
	echo $title . "\n";
}
 
// Search the first child element
$results = $library-&gt;book[0]-&gt;xpath(’title’);
foreach ($results as $title){
	echo $title . "\n";
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 06. XML and Web Services |
Dec
07
2008
0

Web Features: Cookies

Cookies allow us to store data on the users computer, so we can identify them and they can have their own options. It is limited storage wth only 4-6kb. The most common use of cookies is with sessions to store their login data.

Cookies are send by server using headers, they are not secure and can be modified even when sent over HTTPS.

setting cookie

setcookie("hide_menu", "1");

This will be sent to the user in header, and stored in its browsers files for a limited time. We can increase that time by adding a UNIX timestamp:

setcookie("hide_menu", "1", time() + 86400);

This will try and ask the user to save cookie for a day, but a lot of users clear cookies regularly (or on browser exit).

Their are many arguments for setcookie:

setcookie($name, $value, $time, $path, $domain, $secure);

• name - the name in which you will use $_COOKIE['name'] to read
• value - the content of the cookie
• time - how long you want to ask the user to store the cookie for.
• path—allows you to specify a path (relative to your website’s root) where the cookie will be accessible; the browser will only send a cookie to pages within this path.
• domain—allows you to limit access to the cookie to pages within a specific domain or hostname; note that you cannot set this value to a domain other than the one of the page setting the cookie (e.g.: the host www.phparch.com can set a cookie for hades.phparch.com, but not for www.microsoft.com).
• secure—this requests that the browser only send this cookie as part of its request headers when communicating under HTTPS.

Reading Cookies
We can use the $_COOKIE superglobal, cookies are sent to the server using a single request header (that’s right, sent in a request!)

if ($_COOKIE[’hide_menu’] == 1) {
	// hide menu
}

As you can see we read the value of cookie and do what we want with it.

Delete Cookies
Their is no way to delete a cookie, because we have little control. We can however ask setcookie to update it with a new value and a different expiry date from the past:

setcookie("hide_menu", false, -3600);
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 09. Web Features |
Dec
07
2008
0

Web Features: HTTP Headers

I know a lot about HTTP Headers, as I have used Wireshark a sniffer of requests from my computer.

A server responds to a HTTP request with information about the data that is to follow. The data are strings “key: value” and are terminated by a newline character.
PHP and your Computer sends and received HTTP Headers fine by itself, but their may be times when you want to overwrite the standard headers and use your own.

You can do this using PHP’s header(); function, one thing to remember is that header must be called before any output or whitespace out of the php tags. If you don’t the header will have no effect and php will output warnings.

Headers Examples

Their are many uses of Headers, such as GDImages making output of a imagefile look like an image of an end user. We will go trough some now:
Redirect

header("Location: http://phparch.com"); //Redirect Location
exit(); //Stop any more requests on our server

As you can see we are redirecting the user to a different website using a header redirect, we use exit to ensure that portions of the script are not called unexpectedly. I use this a lot to redirect a user to login page if they don’t have access to restricted content.
compression
HTTP supports compression therefore PHP does. It has a impact on bandwidth by a possible decrease in 90% of fle size, but because its performed on the fly it uses up more server resources. You can set the compression level from 1 to 9 (9 being highest) the default is 6.

You can turn this on in the PHP.ini to compress every request:

zlib.output_compression = on
zlib.output_compression_level = 9

or the most common is to use ob_start in the header of every script:

ob_start("ob_gzhandler");

Caching
Sometimes we dont want any browser to cache a pages contents, as it is updated very often. We can use php to manipulate the browsers actions towards caching data (some listen some dont):

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Thu, 31 May 1988 04:35:00 GMT");

As you can see we first tell it not to cache what so ever, followed by a second check setting the cache to expire in the past 1988!

We can do the opposite and extend the cache time of a document useing the same headers such as:

$date = gmdate("D, j M Y H:i:s", time() + 2592000); // 30 Days from now
header("Expires: " . $data . " UTC");
header("Cache-Control: Public");
header("Pragma: Public");
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 09. Web Features |
Dec
07
2008
0

Web Features: GET and POST data

GET or POST
PHP makes it very easy to handle data sent using either POST or GET. However, this doesn’t mean that you should choose one or the other at random. From a design perspective, a POST transaction indicates that you intend to modify data (i.e.: you are sending information over to the server). A GET transaction, on the other hand, indicates that you intend to retrieve data instead. These guidelines are routinely ignored by most Web developers—much to the detriment of proper programming techniques. Even from a practical perspective, however, you will have to use POST in some circumstances; for example:
• You need your data to be transparently encoded using an arbitrary character set
• You need to send a multi-part form—for example, one that contains a file
• You are sending large amounts of data

POST Superglobal

if ($_POST[’login’]) { //check if submit buttion was clicked
	if ($_POST[’user’] == "admin" && $_POST[’pass’] == "secretpassword") { //ensure both username and password match
		// Handle login
	}
}

Their post is easy right, we can also use it with arrays:

<input type="checkbox" name="languages[]" value="Ruby" />Ruby
<input type="checkbox" name="languages[]" value="Perl" />Perl
<input type="checkbox" name="languages[]" value="PHP" />PHP

This can be interperated in PHP useing the post superglobal and array handleing:

foreach ($_POST[’languages’] as $language) {
	switch ($language) {
	case ’PHP’ :
		echo "PHP? Awesome! <br />";
	break;
	case ’Perl’ :
		echo "Perl? Ew. Just Ew. <br />";
	break;
	case ’Ruby’ :
		echo "Ruby? Can you say... ’bandwagon?’ <br />";
	break;
	default:
		echo "Unknown language!";
	}
}

GET Superglobal
When data is sent via GET (over the url) we then use the superglobal to get data:

echo $_GET['dataname']; // simple GET
// or
echo $_GET['dataname']['by']; //Get useing array

As you can see from the URL ( index.php?dataname=GET&dataname[by]=Zend ) the user can change the data directly.

You should be aware that PHP can not use some charictors in the URL such as & therefore we can use function urlencode($data) to encode the data in a readable format see example:

$data = "Max & Ruby";
echo "http://www.phparch.com/index.php?name=" . urlencode ($data);

The PHP interpreter will automatically decode all incoming data for us, so there is no need to execute urldecode() on anything extracted from $_GET.

Request Superglobal
PHP allows us to use $_REQUEST this allows us to interperate both GET and POST data no matter how they are sent. This means we can use both forms to submit data or get to submit data. Personaly I see little use if you use this, you may as well just use $_GET universal.

The problem with using this approach is that, technically, you don’t know where the data comes from. This is a potentially major security issue that you should be fully aware of.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 09. Web Features |
Dec
07
2008
1

Web Features: Forms

Forms is the cornerstone behind PHP in my opinion, its all out input and output without forms we would be limited.

We interact with scripts using two HTTP methods GET and POST. The difference is that GET data is sent over the url (index.php?method=get&data=zend) and POST data is sent along with data payload (over HTTP).

Their are limits such as you can only upload files using POST, and most browsers implement limitations on length of a query string. Remember that Get and POST can both be manipulated by the user in varos ways it is advised to escape input.

Get or Post in HTML:
We should all know this allready but to specify the HTTP Method we use:

<form action="index.php" method="GET">

or

<form action="index.php" method="POST">

GET Superglobal
When data is sent via GET (over the url) we then use the superglobal to get data:

echo $_GET['dataname'];=

As you can see from the URL ( index.php?dataname=GET&dataname[by]=Zend ) this is how the data is passed.

POST Superglobal
PHP allows us to use $_POST[’login’] this passes data along with HTTP protocol allowing data transfer between user and server.

Request Superglobal
PHP allows us to use $_REQUEST this allows us to interoperate both GET and POST data.

Uploads
Remember uploads are great, but they are a high security risk. A malicious uploaded file could being the end to your websites data and highly annoy your users as you have lost their personal data.

Uploads can only be uploaded via multipart/form-data this is because it uses the multi-part HTTP Post. This is done in the enc type:

<form enctype="multipart/form-data" action="index.php" method="post">
	<input type="hidden" name="MAX_FILE_SIZE" value="50000" />
	<input name="filedata" type="file" />
	<input type="submit" value="Send file" />
</form>

max_file_size sets the maximum file size, but this can be altered by the end user and therefore not security. You can limit the amount of data uploaded by a POST operation by modifying a number of configuration directives, such as post_max_size, max_input_time and upload_max_filesize.

Once a file is uploaded to php it is stored in a temporary location, unless advised to move it elsewhere if its not then its destroyed. The temporary location can be accessed via the $_FILES superglobal to get many aspects of what is received such as the original file name (name) the mime type (type) the size of the file in bytes (size) and the name of the temporary files location (tmp_name) finally we can also reweave any error information (error) this returns “UPLOAD_ERR_OK” if it was good. All this information can be spoofed by the user.

Uploads and security
Ensure that UPLOAD_ERR_OK is received, ensure the file size is not zero and the the file has a tmp_name. PHP has two additional functions is_uploaded_file(); that checks that the file is actually uploaded and at its said location and move_uploaded_file(); that does what is_uploaded_file does and then moves it to a different location on the server.
It is always advised to NEVER use the filename provided instead use a mixture of random name and original so the user can not know its destination until you want them to.
You should read more about upload security before following my advice.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 09. Web Features |
Dec
07
2008
0

Web Features: Sessions

Sessions in PHP are a great way to track your users to implement many features such as user areas or for your own statistics to log their movement. Lots of uses, but with many implementations you must ensure they are secure when used in conjunction with cookies.

Sessions are stored on local filesystem, and can not be implemented by the user. Unless a user can return to the website and continue with its old session, their are possible vulnerabilities with session hacking. (covered in security chapter).

HTTP is stateless so the webserver does not care if requests come from user A or B each request is handled without regard. Sessions are used to create a state between requests.

Sessions are maintained by using a unique session identifier, pass and stored in cookies or passed with forms and GET arguments.

Unless you change the PHP.INI to do this automatic we have to use session_start()session_regenerate_id() to change the session ID this helps prevent session fixation (where someone steels someone else session).

Once a session has been started you can access it using $_SESSION superglobal:

session_start(); // Start Session
$_SESSION['uid'] = 10; //Session UID set with value of 10
 
if($_SESSION['uid'] == 10){ //Check if session uid is 10, if it is the user is the admin
	echo "Welcome Admin!";
} else {
	echo "Welcome User";
}

Remember to read previous post [url=http://zend.is-hacked.com/2008/php-session-security/]PHP Session Security[/url]

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 09. Web Features |