简体   繁体   English

用PHP重命名图像文件

[英]Rename image file with PHP

I just want to make sure I'm doing this right. 我只想确保自己做对了。 This is a simple upload class. 这是一个简单的上载类。 I need to change the below code to rename the actual image file, with a variable name (a Joomla user id and keep the extension of course. It's easy to get the logged in user id. So my image filename before upload would be whatever the user had (usersimagename.jpg) and have it changed to a numeric userid.ext like (62.png) populated by joomla's user variable. 我需要更改以下代码以使用变量名称(Joomla用户ID并保留扩展名)来重命名实际的图像文件。很容易获得登录的用户ID。因此,上传之前我的图像文件名可以是用户具有(usersimagename.jpg)并将其更改为由joomla的用户变量填充的数字userid.ext,例如(62.png)。

<?php

$uploaddir = $_REQUEST['path'];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "success";
} else {
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
// Otherwise onSubmit event will not be fired
echo "error";
 }

 ?>

If I understand your question right you want to keep the file extension while changing the actual name for storage. 如果我对您的问题理解正确,那么您想在更改存储的实际名称时保留文件扩展名。 I don't know the Joomla variable but something like this should work 我不知道Joomla变量,但是这样的事情应该可以工作

<?php
    $ext = strrchr($_FILES['userfile']['name'],".");

    $uploadfile = $uploaddir . $JOOMLAID . $ext;
?>

Then follow this up with the rest of your code. 然后再执行其余的代码。

You could also substitute $JOOMLAID with whatever generated name you can think of. 您也可以将$ JOOMLAID替换为您能想到的任何生成的名称。

The code itself is operationally fine, but logistically is a nightmare. 该代码本身在操作上还不错,但从逻辑上讲是一场噩梦。 You're allowing the user to specify both a path AND filename for the final storage location. 您允许用户为最终存储位置指定路径和文件名。 Consider what happens if a malicious user gets into your site. 考虑如果恶意用户进入您的站点会发生什么。 They can trivially replace ANY file on your server that your webserver's userID has access to. 他们可以轻松替换您的服务器上您的Web服务器的userID可以访问的任何文件。

eg 例如

$_REQUEST['path'] = '/etc/';
$_FILES['userfile']['name'] = 'passwd';

or 要么

$_REQUEST['path'] = 'c:\windows\system32\';
$_FILES['userfile']['name'] = 'ntoskrnl.exe';

while these are just shock-value examples, and not likely to be modifiable by your webserver, it is an example of how easily your code will allow someone to totally pwn your server. 尽管这些只是震撼价值的示例,并且不可能被您的Web服务器修改,但这是一个示例,您的代码将允许他人轻易地完全伪造您的服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM