Hardware Reference
In-Depth Information
Uploading Files to a Server
Using PHP
Next, you're going to write a script that uploads images
to the server. PHP has a predefined variable, $_FILES,
that allows you to get information about any files the user
attempts to upload via HTTP. Like $_REQUEST, which
you saw earlier, $_FILES is an array, and each of the array
elements is a property of the file. You can get the name of
the file, the size of the file, and the file type, which will be
useful when you write a script that takes only JPEG files
below a certain size.
Try It
Here's a PHP script
with an HTML form that
uploads a file. The PHP script doesn't
do anything much so far—it just shows
you the results of the HTTP request.
Save this to your server as save2web.
php.
<?php
if (isset($_FILES)) {
print_r($_FILES);
}
?>
<html>
<body>
View this in a browser, and you'll get a
simple form with a file chooser button
and an upload button. Choose a JPEG
image file and upload, and you'll get a
response that looks like this:
<form action="save2web.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Upload" />
</form>
Array ( [file] => Array ( [name] =>
catcam.jpg [type] => image/jpeg [tmp_
name] => /tmp/phpoZT3BS [error] => 0
[size] => 45745 ) )
</body>
</html>
This is the $_FILES variable printed out
for you.
8
Replace the PHP part of this script
(the part between <?php and ?> ) with
the following. This script checks to see
that the uploaded file is a JPEG file with
fewer than 100 kilobytes, and it saves it
in the same directory as the script.
<?php
if (isset($_FILES)) {
// put the file parameters in variables:
$fileName = $_FILES['file']['name'];
$fileTempName = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
// if the file is a JPEG and under 100K, proceed:
if (($fileType == "image/jpeg") && ($fileSize < 100000)){
// if there's a file error, print it:
if ( $fileError > 0){
echo "Return Code: " . $fileError . "<br />";
}
»
 
Search WWH ::




Custom Search