Upload
ahmed-swilam
View
286
Download
0
Embed Size (px)
Citation preview
File I/O – PHP Best Practices
Outline
• Files• Files in PHP• Traversing Directories• Serialization• PHP Best Practices
Files• Files are data records on the hard disk. We use them
to save persistent data.
• We are responsible for the format in which we will write the data to the file.
Files in PHP• string file_get_contents ($file)
• This function is used to get file contents from local file system, or from an external URL.
• file_put_contents($file, $data)
• Saves a string to a file.
Files in PHP• array file ( string $filename ):
• Takes a file path and returns an array containing each line from that file content.
• bool file_exists($file) :
• Checks whether the passed file exists.
Files in PHP• int filesize($file) :
• Returns the size of the specified file in bytes.
Traversing Directories• Traversing Directories :
• Directory traversing fits the recursive model. It can be done using recursion.
• Using the functions opendir(), is_dir(), closedir(), we will be implementing a solution to traverse a certain directory and display all the directories and files inside it.
Traversing Directoriesfunction traverse($dir) { echo "Directory: $dir <br>"; if( !( $dp = opendir($dir) ) ) return; while((false !== $file = readdir($dp))){ if($file != '.' && $file !='..'){ if(is_dir("$dir/$file") ){ traverse("$dir/$file"); } else{ echo "File: $dir/$file<br>"; } } } closedir($dp); }traverse('/var/www');
Serialization• Serlialize($item):
• Use this function to convert any type to a string to save it to a file ( or for any other use ).
<?php$var = array( ‘1’ => ‘xxx’, ‘2’ => ‘yyy’ );echo serialize($var); // a:2:
{i:1;s:3:"xxx";i:2;s:3:"yyy";}
?>
Serialization• mixed unserlialize($item):
• It does the opposite of serialize(), it converts the serialized object back to its original value.
<?php$var = array( ‘1’ => ‘xxx’, ‘2’ => ‘yyy’ );echo unserialize( serialize($var) );
?>
PHP Best Practices
1. Always escape output. Use htmlspecialchars().
2. Always filter/ validate user input.
3. Don't copy variables for no reason.$description = strip_tags($_POST['description']);
$description = ‘something’ . $description;
echo $description;
4. Favor built-in functions over custom functions.
PHP Best Practices
5. Use regular expressions only when necessary, use string functions if they achieve what’s required instead.
6. Remember that disk I/O is the slowest operation you can do.
7. Use opcode cache to cache the PHP intermediate code ( APC cache ).
8. Know the difference between single and double quotes.
9. Use echo instead of print.
Questions?
We hope you enjoyed the course and it was of a good value to you.
Please keep in touch,Ahmed KamalFacebook : /ahmed.kamalSkype: nc_a.kamalMobile : 0104740817
Ahmed SwilamFacebook : /ahmed.swilamSkype: nc_a.swilamMobile : 0108247940
Best wishes