O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #97. Create a Media Upload/Download Center

Allow users to upload and download media files from your application.

Sometimes the customers of your site will want to trade more than just text. They will want to trade media files, images, and who knows what else. The legality of such things aside, this hack will walk you through building a simple media upload/download center for your site.

Figure 10-9 shows the page flow of the upload/download center. The user starts at index.php, where he uploads a file through upload.php. The upload.php script forwards himto the dir.php page, which then shows the files that are available as downloads. Clicking on any of the files will download them through the download.php script.

The page flow of the media upload/download center

Figure 10-9. The page flow of the media upload/download center

The Code

Save the code in Example 10-4 as media.sql. It's a simple little SQL statement to create a new table.

Example 10-4. Creating the media table for file uploads

DROP TABLE IF EXISTS media;
CREATE TABLE media (
        id MEDIUMINT NOT NULL AUTO_INCREMENT,
		filename TEXT,
		mime_type TEXT,
		PRIMARY KEY( id )
);

Save the HTML in Example 10-5 as index.php.

Example 10-5. A form allowing for an upload

<html> 
<body>
		<form enctype="multipart/form-data" action="upload.php" method="post">
				<input type="hidden" name="MAX_FILE_SIZE" value="2000000" /> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> </body> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required