Click to See Complete Forum and Search --> : File Naming, why no working?


Vasilli
08-24-2003, 07:05 AM
I am having a bit of a problem, i got a snippet of code fomr the php.net site that SHOULD rename a file upon upload, however it dosn't Take a look and see if you can figure out what i am doing wrong.


$sName = $_FILES['img1']['name']; // The name of the file
$sName = str_replace(chr(32), chr(95), $sName);
$ext = split ('[.]', $sName); // Split the name from the file
$sFileExt = $ext[count($ext)-1];

$sFileDateName = "../images/cars/". date('dmYs_zw') . "." . $sFileExt;

echo $sFileDateName; // this is what i want the files to be named
echo "<br>";
echo $sName; // this is what they are named at this time
echo "<br>";
echo $sFileExt; // and this is just the extension

if (preg_match('/^(gif|png|jpe?g)$/',$sFileExt))
{
function my_copy($sName, $sFileDateName)
{
if(is_file($sName)){
return copy($sName, $sFileDateName) && chmod($sFileDateName, 0755);
}
else
{
die("Sorry cannot copy file: $sName");
}
}
}
else echo 'The file you are trying to upload has not got an image extension.;



As you have probably guessed i am trying to name the files with the date, so as to not double up on files. Anyone done this before, or know what i am not doing correctly?

Thanks in advance
Jono

Kr|Z
08-24-2003, 07:26 AM
The file should be copied from the temporary file on the server, not from the name of the file.

You should copy the file from this variable:

$_FILES['img1']['tmp_name'];

And get the name of the file from this variable:

$_FILES['img1']['name'];

Change these lines to:


if(is_file($_FILES['img1']['tmp_name'])){
return copy($_FILES['img1']['tmp_name'], $sFileDateName) && chmod($sFileDateName, 0755);
}

Vasilli
08-25-2003, 07:38 AM
Hmm

Now it dosn't copy the file at all (not into old name or new name??)

any ideas why?

i will post what i changed it too


$sName = $_FILES['img1']['tmp_name']; // The name of the file
$sName = str_replace(chr(32), chr(95), $sName);
$ext = split ('[.]', $sName); // Split the name from the file
$sFileExt = $ext[count($ext)-1];

$sFileDateName = "../images/cars/". date('dmYs_zw') . "." . $sFileExt;

echo $sFileDateName;
echo "<br>";
echo $sName;
echo "<br>";
echo $sFileExt;

if (preg_match('/^(gif|png|jpe?g)$/',$sFileExt))
{
function my_copy($sName, $sFileDateName)
{
if(is_file($_FILES['img1']['tmp_name'])){
return copy($_FILES['img1']['tmp_name'], $sFileDateName) && chmod($sFileDateName, 0755);
}
else
{
die("Sorry cannot copy file: $sName");
}
}
}
else echo $DivS.'The file you are trying to upload has not got an image extension, please check that it has either .jpg, .jpeg, .gif or .png and try again'.$DivE;



Thanks again!

Jono

Kr|Z
08-25-2003, 08:59 AM
The first line should still be:

$sName = $_FILES['img1']['name']; // The name of the file