重命名文件在上传时增加 - PHP

时间:2012-03-07 02:28:39

标签: php file upload rename auto-increment

我需要在上传时为文件提供正常的号码。我是SFWUpload的用户。我有这段代码:

mkdir("../../imagenes/".$codigo , 0777);
$i = 1;
$nombre = $codigo.'_'.$i.'.jpg';
move_uploaded_file($_FILES['Filedata']['tmp_name'], "../../imagenes/".$codigo."/".$nombre);
chmod("../../imagenes/".$codigo."/".$_FILES['Filedata']['name'], 0777);

$ codigo是代码,例如101213,所以我需要上传图片,如101213_1.jpg,101213_2.jpg,101213_3.jpg,等等。

问题是SWFUpload每张图片运行php ONCE,所以我不能使用foreach循环(我猜)。

我需要脚本来检查文件是否存在并编写下一个文件。例如,如果存在101213_4.jpg,则写入101213_5.jpg。

你能帮帮我怎样才能做到这一点。我是php的新手,并尝试了一切。 :(

提前致谢

罗伯特

2 个答案:

答案 0 :(得分:1)

这是我使用的功能:

function cleanup_name($name){ //accepts name and cleans it up.
$finalDir='/home/username/uploads';

# Go to all lower case for consistency
$name = strtolower($name);
//echo("Name is $name<br>");

$matches=split('\.',$name);
foreach ($matches as $key=>$value){
$exkey=$key;
$exvalue=$value; //if there is more than one period, this will find the actual extension.
//echo("Key $key|$exkey Value $value|$exvalue<br>");
}

if ($exkey<1){die('The file must have an extension.');}
$extension=".".$exvalue;
$loop=0;
while ($loop<($exkey)){
if ($loop<($exkey-1)){$matches[$loop]=".".$matches[$loop];} // this puts extra periods back into the string, but the borrowed code will replace them with underscores.
$stem.=$matches[$loop];
$loop++;
}

//echo("Stem is $stem<br>");
//echo("Extension is $extension<br>");

# Convert whitespace of any kind to single underscores
$stem = preg_replace('/\s+/', '_', $stem);

# Remove any remaining characters other than A-Z, a-z, 0-9 and _
$stem = preg_replace('/[^\w]/', '', $stem);

# Make sure the file extension has no odd characters
if (($extension != '') &&
  (!preg_match('/^\.\w+$/', $extension)))
{
  echo("odd characters in extension");
  //die("Bad file extension");
  return FALSE;
}

$safeExtensions = array(
'.zip',
'.psd',
'.pdf',
'.jpg',
'.jpeg',
'.gif',
'.rar',
'.gz',
'.ai',
'.eps',
'.bmp',
'.pub',
'.xls',
'.doc',
'.wpd',
'.rtf',
'.tiff',
'.tif',
'.pcx',
'.ttf',
'.png',
'.txt',
'.mp3',
'.avi',
'.mov',
'.wav'
);

if (!in_array($extension, $safeExtensions)) {
  echo("Extension &quot;$extension&quot; not approved.");
  //die("File extension not approved");
  return FALSE;
}

# Search for a unique filename by adding a number to the
# stem (first we try without, of course)

$suffix = '';
while (file_exists($finalDir."/".$stem.$suffix.$extension)) {
  if ($suffix == '') {
    $suffix = '0';
  } else {
    $suffix++;
  }
}

# Put the full name back together
$name = "$stem$suffix$extension";
return $name;
}

请特别注意以下部分:“while(file_exists ...”

答案 1 :(得分:0)

嗯......您可以尝试获取文件夹中当前的文件数,然后从那里获取$i

mkdir("../../imagenes/".$codigo , 0777);
$i = count(glob("../../imagenes/".$codigo.'_*.jpg')) + 1;
$nombre = $codigo.'_'.$i.'.jpg';
move_uploaded_file($_FILES['Filedata']['tmp_name'], "../../imagenes/".$codigo."/".$nombre);
chmod("../../imagenes/".$codigo."/".$nombre, 0777);

试试那段代码......