Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

PHP some filesystem functions

PHP have many functions to acces and manipulate files, the most important filesystem functions are posted here...

basename() : Returns the filename component from a path.
<?php
$path = "/directory1/index.html";
echo basename($path);
// display: index.html
echo basename($path ,".html" ); // display: index
?>

file_exists() : Checks if a file or directory exists ot not.
<?php
echo file_exists("test.txt"); // returns True if exists, otherwise returns False
?>

rename() : Renames a file or directory.
<?php
rename("dir1","dir2"); // You can rename a file or a folder
?>

copy() : Copies a file.
<?php
copy("sourcefile.txt","destinationfile.txt");
?>

unlink() : Deletes a file.
<?php
unlink("file.txt"); // returns True if deleted successfully, False if not deleted.
?>



filesize() : Returns the size of the file.
<?php
echo filesize("file.txt"); // returns the size of file.txt in bytes, or False in failure.
?>

filetype() : Returns the file type.
<?php
echo filetype("file.txt"); // returns type: file.
//Possible types are: file, dir, link, block, char, fifo, unknown.
?>

is_readable() : Checks whether a file is readable, returns true if yes.
is_writable() : Checks whether a file is writeable, returns true if yes.

fileperms() : Returns the permissions of a file.
filemtime() : Returns the last modification time of a file, Display a number in second, to convert it to humain redable date format, use:
<?php
echo date("F d Y H:i:s", filemtime("test.txt")); // returns date format: September 03 2008 18:27:35
?>


If you have any question, or need more details or functions, post a comment here.

Get Filename without extension

Hello,

It's sometimes usefull to pick the name of the file without its extension, and this is very easy with php !

PHP Code:
<?php
$arr = explode(".", $allname);
$filename = $arr[0];

?>
But this script will not work the file name is dotted, in that case use this:

PHP Code:
<?php
$filename = preg_replace( '/\.[a-z0-9]+$/i' , '' , 'dotted.file.Name' );

?>
Or:

<?php
$FileNameTokens = explode('.', $allname);
$fileName = implode(".", array_slice($FileNameTokens, 0, count($FileNameTokens) - 1));

?>

If this is a few hard to understand, this script is easier:

PHP Code:
<?php
function getFilenameWithoutExt($filename){
$pos = strripos($filename, '.');
if($pos === false){
return $filename;
}else{
return substr($filename, 0, $pos);
}
}

?>

I hope this will help you.

PHP Force Download

We used to just link to a file to download it, for example to let users download myfile.zip, you just link to it: domain.com/myfile.zip ...
But the problem is, what if you want to let user download a html file or maybe php file without executing it ? I mean if you link to file.html it will just load it, and not download and save it, so how to do that ?

the answer is very easy, for example mypage.html, you want to let visitors download it, so do the following:

The php code:
<?php

$file = 'file.php'; // Her choose any file !
if (file_exists(
$file))
{
header('Content-disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/force-download');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. filesize(
$file));
header('Pragma: no-cache');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
readfile(
$file);
}
else
{
$errorfile = 'the file "' . $file ;
}


?>

PHP file upload script

Firstly, to let visitors upload a file, you must create a form so enable users to choose a file:
In your html page, copy this:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

This will enable the user to choose what file to upload and click "Upload File" button.
Choose a file to upload:



If you want to add a file size limit, add this line:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Now create a file "upload.php" and a directory "uploads/"

In upload.php copy this php code:
$target_path = "uploads/" ;
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
This code will put all uploaded files to uploads/ directory.
$_FILES['uploadedfile']['name'] will get the file name, and add it to the string $target_path.
For example if someone upload a file: myfile.zip , it will save it to: uploads/myfile.zip .

To check if the file was uploaded successfully, add this script:
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}

PHP fget: read a file line by line

To get only one line of a text file, or get line by line, we have to use fget() php function instead of fread() .

We saw in the previous lesson, that if you want to read a file, you can open it and put all it's content in some variable. But in this script we will see how to get the data from the file line by line until the end of file is reached:
<?php

$filename = 'myfile.txt' ;
$file = fopen($filename , 'r' ) or exit ( "Enable to open file");

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

?>

Why to use this script:
Let's say you have a text file with many line:

----myfile.txt------
Hello Word.
We love PHP !
Here are great tutorials
And scripts and codes !
--------------------

if you use this script
$contents = fread($handle, filesize($filename));
echo $contents;
This will show:
Hello Word.We love PHP !Here are great tutorialsAnd scripts and codes !
And this is beacuse HTML script don't understand the new line character, so you need to create a new line with "<br />".

So we have to use:

<?php

$filename = 'myfile.txt' ;
$file = fopen($filename , 'r' ) or exit ( "Enable to open file");

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

?>
Display:
Hello Word.
We love PHP !
Here are great tutorials
And scripts and codes !

PHP files, how to read and write to files ?

In this lesson we will talk about using files in php: Reading, Writing and overwriting files.

To open a file
The first thing, before reading or writing to a file, we need to open it, to be ready.

To open a new file in php, use this script:
$filename = "myfile.txt";
$handle = fopen($filename, "r");



This is very easy ! Yes ?
$filenam is just the name and path of the file you want to open to eighter read or write, it can be "something.txt" if it's in the same folder than the php page, or like :"folder1/something.txt" if its in another folder.
In the second line, fopen($filename, "r") , the "r" means that we will read the file, all possible values are:
"r" : Only read a file
"r+" : read and write, start from the begenning of the file.
"a" : write only, write to the end of the file.
"a+" : write and read, start from the end of the file.
"w" : Delete the content of the file, and write over it.
"w+" : Delete the content of the file, then you can read or write to it.

To read a file:

Now, to read a file and copy the content to a string:
$contents = fread($handle, filesize($filename));


Now in the variable $contents you have all the text in the source file.
The script should be:
$filename = "myfile.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));


you can then use echo function to write it to the html page, or you can split it by a delimiter ( we will se that soon).

To write to a file:

As we said before, there are many ways to write to a file:
To write to the beginning of the file, use the "r+" in the fopen() function.
To write to the end of the file, use the "a" in the fopen() function.
To overwrite the file, if you want to replace the current content of the file, then use the "w" in the fopen() function.

Then :
$filename = "myfile.txt";
$handle = fopen($filename, "a");
fwrite($handle, 'some text to add to the file');

In this case you will put the scring to the end of the file

In case you want to put a string to the begenning to the file, just use: "r+", just like that:
$filename = "myfile.txt";
$handle = fopen($filename, "a");
fwrite($handle, 'some text to the beginning oh the file');


Or, if you want to overwrite the file with php, you can use "w".
$filename = "myfile.txt";
$handle = fopen($filename, "w");
fwrite($handle, 'new content for the file');


This is easy, don't think ?

It may be very helpful to check if the file can be read or wrote, you can use this script:
$handle = fopen($filename, "w") or die("can't open the file");




The next lessons will be about reading external files. Soon :)