Uploading Files Using CGI and Perl Article

Share this article

Putting It All Together

1. Place the Files on your Server

Place the HTML form somewhere under your Website’s document root, and your CGI script in your Website’s cgi-bin directory.

Note: don’t forget to make the CGI script executable if you’re on a UNIX server – chmod a+rx upload.cgi or chmod 755 upload.cgi
2. Set the Correct Paths and URLs

If necessary, change the upload.cgi URL in the <form> tag to point to the correct URL for the CGI script:

<form action="/cgi-bin/upload.cgi" method="post"
enctype="multipart/form-data">

Also, don’t forget to set the correct path to Perl in your CGI script, and the correct absolute path to the ‘upload’ directory that you created on your server:

my $upload_dir = "/home/mywebsite/htdocs/upload";
3. Test the Script

Let’s try it out! Go to the URL of your file upload form on your server, select a photo to upload, and enter your email address:

Testing the script

Press the “Submit Form” button. If all goes well, the photo will be uploaded to the server, and you should see the “Thanks!” page, which also displays your photo and email address:

Viewing the thank you screen

Congratulations – you’ve written a file upload handler script!

If you get Internal Server Errors, double-check the permissions, paths and URLs described above, and look for other common CGI script pitfalls. For instance, editing a file on Windows and then uploading it to your Web server in Binary format will cause the script to crash on Unix servers.

Final Thoughts

A couple of points about this script are worth a mention:

If you were doing this on a real Website with lots of users, it would be a good idea to create a separate upload directory for each user, so that one user’s photo won’t be overwritten with another user’s photo of the same name!

File upload isn’t perfect. All browsers handle file uploads slightly differently, and some browsers can have trouble uploading files to certain types of servers and scripts. On the whole, though, most users won’t have any problem with the most popular browsers.

That’s it. Have fun with your file uploads!

Go to page: 1 | 2 | 3
Matt DoyleMatt Doyle
View Author

Matt works for Elated.com, which offers great Webmaster resources, from free templates and stock images through to tutorials and forums.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week