1 / 47

Files

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.

Download Presentation

Files

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Files

  2. 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'])

  3. File Open Modes

  4. 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); ?>

  5. 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..

  6. 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.

  7. 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.

  8. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle);

  9. 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

  10. 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

  11. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Close the file fclose($handle);

  12. 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.

  13. 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);

  14. Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, “\nFred:Male”); fclose($handle);

  15. 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)

  16. 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

  17. 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.

  18. 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)

  19. 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.

  20. 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

  21. 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.

  22. 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'

  23. Directory Example //In filesystems . means current directory $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle);

  24. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); $handle = opendir('./'); Open current directory

  25. 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

  26. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); closedir($handle); Close the directory stream

  27. 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

  28. We know all this... so what's new?

  29. 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>

  30. 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

  31. 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!

  32. 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.

  33. 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

  34. 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

  35. 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 />'; } }

  36. 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

  37. 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.

  38. 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.

  39. 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.

  40. 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

  41. 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>

  42. 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" />

  43. 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"); } }

  44. 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

  45. 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.

  46. 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");

  47. HOE: File Uploads

More Related