[ back to toc ]

Using Form Data For Actual File Names

Date: 2002/06/17 17:02

I am trying to write a CGI script that uploads a file, which I have it
doing. However, I can only get it working if I hard code in the file
path. I want to make the filename equivalent to values entered by the

To be exact, the user is uploading a picture. On the same form they place
their name. I want to have a script that uploads their picture and places
in a image directory. The file uploaded is placed in the directory and
named theirName.ext

Here is my code:

use CGI;
$query = new CGI;
$ERROR = "";

$fName = $query->param("txtFirst");
$lName = $query->param("txtLast");
$handle = $query->param("photo");

if ($handle ne "") {
$uploadDir= "/campbel8/www/guestbook/photos";
$fileName = "$fName$lName.jpg";
$sThePath = "$uploadDir/$fileName";

open PHOTO_FILE ">$sThePath";
while (<$handle>) {
I do not really unerstand what the problem is with the solution. The
directory where the pictures are put is hard coded in the Perl program and
this is something really good. If you get the directory where the pictures
are put from the form data then you may soon end up with a defaced,
cracked site. Thus DO HAVE your picture directory hardcoded in the Perl
script. This is my advice.

It is also would be a good idea to hard code the allowed file extensions
and after the file is uploaded call 'chmod' to alter the permission of the
file to minimize the risk that the uploaded file with some content that
the untrusted uploader created is ever run on the server.

Hi Peter, thank you for your fast response.
The problem I am having is when ever the file name is a variable. Not
the directory. I definately want the directory to be hard coded in there.
However everything after the directory will be used by a variable. If I
hard code in the file name it works, if I place variable names in there it
does not work.
If I do something like the following
$uploadDir= "/campbel8/www/guestbook/photos";
$fileName = "test.jpg";
$sThePath = "$uploadDir/$fileName";
it works.

If I do something like the following

$uploadDir= "/campbel8/www/guestbook/photos";
$fileName = "$fName$lName.jpg";
$sThePath = "$uploadDir/$fileName";
# $fName and $lName are two values passed in from the form. You can
# see how they are recieved before.

I'm not sure what else I can do.


I see no reason why it does not work. You can print out the content of the
variables into the result HTML into


HTML sections so you may also see some \n characters if there is any in
the CGI variables. In that case you have to chomp them off. That may be
the reason.

You should check the content of the names anyway not to have / charachter
in it, because one could spoecify a name starting


and trying to overwrite some file you do not want.


[ back to toc ]