2010/11 : [1]building web applications using mysql and php (w1)slide topic files

47
2010/11 : [1] Building Web Applications using MySQL and PHP (W1) Slide Topic Files

Upload: shon-weaver

Post on 24-Dec-2015

219 views

Category:

Documents


3 download

TRANSCRIPT

2010/11 : [1]Building Web Applications using MySQL and PHP (W1)Slide Topic

Files

2010/11 : [2]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

• Use full path to file• Path to currently running script:

dirname($_SERVER['SCRIPT_FILENAME'])

Open/Close a File

2010/11 : [3]Building Web Applications using MySQL and PHP (W1)Slide Topic

File Open Modes‘r’ Open for reading only. Start at beginning of

file.

‘r+’ Open for reading and writing. Start at beginning of file.

‘w’ Open for writing only. Remove all previous content, if file doesn’t exist, create it.

‘a’ Open writing, but start at END of current content.

‘a+’ Open for reading and writing, start at END and create file if necessary.

2010/11 : [4]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

?>

2010/11 : [5]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

2010/11 : [6]Building Web Applications using MySQL and PHP (W1)Slide Topic

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.

2010/11 : [7]Building Web Applications using MySQL and PHP (W1)Slide Topic

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.

2010/11 : [8]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Reading Example

$handle = fopen('people.txt', 'r');

while (!feof($handle)) {

echo fgets($handle, 1024);

echo '<br />';

}

fclose($handle);

2010/11 : [9]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Reading Example

$handle = fopen('people.txt', 'r');

while (!feof($handle)) {

echo fgets($handle, 1024);

echo '<br />';

}

fclose($handle);

Open the file and assign the resource to $handle

$handle = fopen('people.txt', 'r');

2010/11 : [10]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Reading Example

$handle = fopen('people.txt', 'r');

while (!feof($handle)) {

echo fgets($handle, 1024);

echo '<br />';

}

fclose($handle);

While NOT at the end of the file, pointed to by $handle,get and echo the data line by line

while (!feof($handle)) {echo fgets($handle, 1024);echo '<br />';

}

2010/11 : [11]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Reading Example

$handle = fopen('people.txt', 'r');

while (!feof($handle)) {

echo fgets($handle, 1024);

echo '<br />';

}

fclose($handle);

Close the file

fclose($handle);

2010/11 : [12]Building Web Applications using MySQL and PHP (W1)Slide Topic

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.

2010/11 : [13]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

2010/11 : [14]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Writing Example

$handle = fopen('people.txt', 'a');

fwrite($handle, “\nFred:Male”);

fclose($handle);

2010/11 : [15]Building Web Applications using MySQL and PHP (W1)Slide Topic

Data Writing Example

$handle = fopen('people.txt', 'a');

fwrite($handle, '\nFred:Male');

fclose($handle);

$handle = fopen('people.txt', 'a');

Open file to append data (mode 'a')

fwrite($handle, '\nFred:Male');

Write new data (with line break after previous data)

2010/11 : [16]Building Web Applications using MySQL and PHP (W1)Slide Topic

Other File Operations

Delete fileunlink('filename');

Rename (file or directory)rename('old name', 'new name');

Copy filecopy('source', 'destination');

And many, many more!www.php.net/manual/en/ref.filesystem.php

2010/11 : [17]Building Web Applications using MySQL and PHP (W1)Slide Topic

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.

2010/11 : [18]Building Web Applications using MySQL and PHP (W1)Slide Topic

• 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

• Use chmod('directory', 0777)

Permissions

2010/11 : [19]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

Security and safe mode

2010/11 : [20]Building Web Applications using MySQL and PHP (W1)Slide Topic

• 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 for dcs

2010/11 : [21]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

Safe mode work around (2)

2010/11 : [22]Building Web Applications using MySQL and PHP (W1)Slide Topic

Dealing With Directories

Open a directory$handle = opendir('dirname');

$handle 'points' to the directory

Read contents of directoryreaddir($handle)

Returns name of next file in directory

Files are sorted as on filesystem

Close a directoryclosedir($handle)

Closes directory 'stream'

2010/11 : [23]Building Web Applications using MySQL and PHP (W1)Slide Topic

Directory Example

//In filesystems . means current directory

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{

echo "$file<br />";

}

closedir($handle);

2010/11 : [24]Building Web Applications using MySQL and PHP (W1)Slide Topic

Directory Example

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{

echo "$file<br />";

}

closedir($handle);

Open current directory$handle = opendir('./');

2010/11 : [25]Building Web Applications using MySQL and PHP (W1)Slide Topic

Directory Example

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{

echo "$file<br />";

}

closedir($handle);

Whilst readdir() returns a name, loop through directory contents, echoing results

while(false !== ($file=readdir($handle)))

{

echo "$file<br />";

}

2010/11 : [26]Building Web Applications using MySQL and PHP (W1)Slide Topic

Directory Example

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{

echo "$file<br />";

}

closedir($handle);Close the directory stream

closedir($handle);

2010/11 : [27]Building Web Applications using MySQL and PHP (W1)Slide Topic

Other Directory Operations

Get current directorygetcwd()

Change Directorychdir('dirname');

Create directorymkdir('dirname');

Delete directory (MUST be empty)rmdir('dirname');

And more!www.php.net/manual/en/ref.dir.php

2010/11 : [28]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

2010/11 : [29]Building Web Applications using MySQL and PHP (W1)Slide Topic

<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

2010/11 : [30]Building Web Applications using MySQL and PHP (W1)Slide Topic

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>

"multipart/form-data"

Signifies that files can be uploaded by the form

2010/11 : [31]Building Web Applications using MySQL and PHP (W1)Slide Topic

<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

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

2010/11 : [32]Building Web Applications using MySQL and PHP (W1)Slide Topic

<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

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

2010/11 : [33]Building Web Applications using MySQL and PHP (W1)Slide Topic

• 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

The uploaded superglobal

2010/11 : [34]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

Uploaded file functions

2010/11 : [35]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

2010/11 : [36]Building Web Applications using MySQL and PHP (W1)Slide Topic

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 filesif (is_uploaded_file($_FILES['userfile']['tmp_name']))

Check that the files has been legitimately uploaded

2010/11 : [37]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

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

2010/11 : [38]Building Web Applications using MySQL and PHP (W1)Slide Topic

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 ( move_uploaded_file($_FILES['userfile']['tmp_name'],$updir.$upfilename) )

Move the file to its new location and check if it has succeeded.

2010/11 : [39]Building Web Applications using MySQL and PHP (W1)Slide Topic

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

Upload error codes

2010/11 : [40]Building Web Applications using MySQL and PHP (W1)Slide Topic

• 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

Errors

2010/11 : [41]Building Web Applications using MySQL and PHP (W1)Slide Topic

<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

2010/11 : [42]Building Web Applications using MySQL and PHP (W1)Slide Topic

<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

<input name="userfile[]" type="file" /><input name="userfile[]" type="file" /><input name="userfile[]" type="file" /><input name="userfile[]" type="file" />

Filename is set as an array to enable the data for more than one file to be stored.

2010/11 : [43]Building Web Applications using MySQL and PHP (W1)Slide Topic

$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

2010/11 : [44]Building Web Applications using MySQL and PHP (W1)Slide Topic

$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)

For each file in the array assign the key to $key and the Error Code to $error

2010/11 : [45]Building Web Applications using MySQL and PHP (W1)Slide Topic

$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

if ($error == 0)

If the error code is 0 (No error) for the current file in the array we'll carry on processing.

2010/11 : [46]Building Web Applications using MySQL and PHP (W1)Slide Topic

$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

$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

2010/11 : [47]Building Web Applications using MySQL and PHP (W1)Slide Topic

HOE: File Uploads