470 likes | 612 Views
Files. Open/Close a File. A file is opened with fopen() as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. Each file is opened in a particular mode. A file is closed with fclose() or when your script ends.
E N D
Open/Close a File • A file is opened with fopen()as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. • Each file is opened in a particular mode. • A file is closed with fclose()or when yourscript ends. • Use full path to file • Path to currently running script: dirname($_SERVER['SCRIPT_FILENAME'])
File Open/Close Example <?php // open file to read $toread = fopen(‘some/file.ext’,’r’); // open (possibly new) file to write $towrite = fopen(‘some/file.ext’,’w’); // close both files fclose($toread); fclose($towrite); ?>
Now what..? If you open a file to read, you can use more in-built PHP functions to read data.. If you open the file to write, you can use more in-built PHP functions to write..
Reading Data There are two main functions to read data: fgets($handle,$bytes) Reads up to $bytes of data, stops at newline or end of file (EOF) fread($handle,$bytes) Reads up to $bytes of data, stops at EOF.
Reading Data We need to be aware of the End Of File (EOF) point.. feof($handle) Whether the file has reached the EOF point. Returns true if have reached EOF.
Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle);
Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); $handle = fopen('people.txt', 'r'); Open the file and assign the resource to $handle
Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } While NOT at the end of the file, pointed to by $handle, get and echo the data line by line
Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Close the file fclose($handle);
File Open shortcuts.. There are two ‘shortcut’ functions that don’t require a file to be opened: $lines = file($filename) Reads entire file into an array with each line a separate entry in the array. $str = file_get_contents($filename) Reads entire file into a single string.
Writing Data • To write data to a file use: fwrite($handle,$data) Write $data to the file. • There is write shortcut function.. file_put_contents($filename, $data);
Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, “\nFred:Male”); fclose($handle);
Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, '\nFred:Male'); fclose($handle); Open file to append data (mode 'a') $handle = fopen('people.txt', 'a'); fwrite($handle, '\nFred:Male'); Write new data (with line break after previous data)
Other File Operations Delete file unlink('filename'); Rename (file or directory) rename('old name', 'new name'); Copy file copy('source', 'destination'); And many, many more! www.php.net/manual/en/ref.filesystem.php
Permissions • On Linux/Unix/Windows access to each file is governed by it's permissions • The web process (apache) runs as a particular “user” e.g. www-data, apache, nobody etc. • Have to be careful when mixing ftp-ed and uploaded files with permissions.
Permissions • Detailed discussion of permissions is beyond the scope of this course. • Setting Permissions. e.g. • Files • Use FTP software to set file permissions to 666 • Use chmod('filename', 0666) • Created Directories • Use FTP software to set file permissions to 777 • Usechmod('directory', 0777)
Security and safe mode • PHP Safe Mode is an attempt to solve the shared-server security problem. • Many ISP's use safe mode for now. • It has been DEPRECATED as of PHP 5.3.0.
Safe mode work around for dcs • Because of the safe mode restrictions, it is not possible to create a folder and then store files in it. • One workaround is to • create the folder first, using the FTP software, • set the permissions to 7 for everyone (757) • This will allow the script to store files in the folder
Safe mode work around (2) • In other servers it is safer to change the group of the folder that you have created manually, so that it is the group of the web server (e.g. nogroup, dba, etc) • Then set the permissions for the group to be 7 (775) • This will allow PHP on the server to create/change files and folders, but not other users of the server.
Dealing With Directories Open a directory $handle = opendir('dirname'); $handle 'points' to the directory Read contents of directory readdir($handle) Returns name of next file in directory Files are sorted as on filesystem Close a directory closedir($handle) Closes directory 'stream'
Directory Example //In filesystems . means current directory $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle);
Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); $handle = opendir('./'); Open current directory
Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } Whilst readdir() returns a name, loop through directory contents, echoing results
Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); closedir($handle); Close the directory stream
Other Directory Operations Get current directory getcwd() Change Directory chdir('dirname'); Create directory mkdir('dirname'); Delete directory (MUST be empty) rmdir('dirname'); And more! www.php.net/manual/en/ref.dir.php
Uploading files <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form>
Uploading files "multipart/form-data" <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form> Signifies that files can be uploaded by the form
Uploading files <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Sets the maximum size file that the form will accept. Checked by PHP... and perhaps a little useless!
Uploading files <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form> <input name="userfile" type="file" /> Creates an input box with a browse button for file selection. The 'name' will be used in the processing to get information about the file and deal with it accordingly.
The uploaded superglobal • File information stored in global array $_FILES For the example (name="userfile") $_FILES['userfile']['name'] Original name of the file $_FILES['userfile']['type'] The mime type of the file (if provided), e.g "image/gif". NOT checked on the PHP side. $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename when initially stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload
Uploaded file functions is_uploaded_file('filename'); • Checks file was uploaded by a form • Ensures script isn't tricked into working on a different file move_uploaded_file('filename','destination'); • Moves temporary file to it's new home basename('path'); • Returns just the filename from a path
Dealing with uploaded files if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { $updir = dirname(__FILE__).'/to/target/'; $upfilename = basename($_FILES['userfile']['name']); if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $updir.$upfilename) ) { echo 'File successfully uploaded<br />'; } else { echo 'File upload failed<br />'; } }
Dealing with uploaded files if (is_uploaded_file($_FILES['userfile']['tmp_name'])) if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { $updir = dirname(__FILE__).'/to/target/'; $upfilename = basename($_FILES['userfile']['name']); if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $updir.$upfilename) ) { echo 'File successfully uploaded<br />'; } else { echo 'File upload failed<br />'; } } Check that the files has been legitimately uploaded
Dealing with uploaded files if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { $updir = dirname(__FILE__).'/to/target/'; $upfilename = basename($_FILES['userfile']['name']); if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $updir.$upfilename) ) { echo 'File successfully uploaded<br />'; } else { echo 'File upload failed<br />'; } } $updir = dirname(__FILE__).'/to/target/'; $upfilename = basename($_FILES['userfile']['name']); Set the directory where the file will go. Then append the 'real' filename to the directory.
Dealing with uploaded files if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { $updir = dirname(__FILE__).'/to/target/'; $upfilename = basename($_FILES['userfile']['name']); if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $updir.$upfilename) ) { echo 'File successfully uploaded<br />'; } else { echo 'File upload failed<br />'; } } if ( move_uploaded_file($_FILES['userfile']['tmp_name'], $updir.$upfilename) ) Move the file to its new location and check if it has succeeded.
Upload error codes • Useful Error Codes • 0: UPLOAD_ERR_OK • No error, file uploaded successfully. • 1: UPLOAD_ERR_INI_SIZE • The uploaded file exceed the upload_max_filesize directive in php.ini. • 2: UPLOAD_ERR_FORM_SIZE • The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. • 3: UPLOAD_ERR_PARTIAL • The uploaded file was only partially uploaded. • 4: UPLOAD_ERR_NO_FILE • No file was uploaded.
Errors • Can use error logic to check what you do • Check the error code • If OK (i.e. 0) • Complete upload processing • If not OK (i.e. any of the other numbers!) • Stop processing and inform user of error • Can also check type of upload • e.g. $_FILES['userfile']['type'] • Some image types • image/gif, image/jpeg, image/png
Uploading multiple files <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send these files: <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input type="submit" value="Send File" /> </form>
Uploading multiple files <form enctype="multipart/form-data" action="form_process.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="300000" /> Send these files: <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input type="submit" value="Send File" /> </form> Filename is set as an array to enable the data for more than one file to be stored. <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" /> <input name="userfile[]" type="file" />
Processing multiple uploads $updir = 'some/dir/'; foreach ($_FILES['userfile']['error'] as $key => $error) { if ($error == 0) { $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name=$_FILES['userfile']['name'][$key]; move_uploaded_file($tmp_name, "$updir$name"); } }
Processing multiple uploads foreach ($_FILES['userfile']['error'] as $key => $error) $updir = 'some/dir/'; foreach ($_FILES['userfile']['error'] as $key => $error) { if ($error == 0) { $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name=$_FILES['userfile']['name'][$key]; move_uploaded_file($tmp_name, "$updir$name"); } } For each file in the array assign the key to $key and the Error Code to $error
Processing multiple uploads $updir = 'some/dir/'; foreach ($_FILES['userfile']['error'] as $key => $error) { if ($error == 0) { $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name=$_FILES['userfile']['name'][$key]; move_uploaded_file($tmp_name, "$updir$name"); } } if ($error == 0) If the error code is 0 (No error) for the current file in the array we'll carry on processing.
Processing multiple uploads $updir = 'some/dir/'; foreach ($_FILES['userfile']['error'] as $key => $error) { if ($error == 0) { $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name=$_FILES['userfile']['name'][$key]; move_uploaded_file($tmp_name, "$updir$name"); } } Get the temporary file name and the original name and then move the file to a previously set location $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name=$_FILES['userfile']['name'][$key]; move_uploaded_file($tmp_name, "$updir$name");