在php上传图片

时间:2011-09-07 20:48:21

标签: php mysql

当我上传图片时,它会抛出错误。如何在Windows中更改文件夹的权限设置?我的代码有什么问题吗?

//This is my path for storing images. (I am using wamp 2.0)
$targetPath="../artistImages/";

$image=$_FILES['myimage'];
$image['name'] = mysql_real_escape_string($image['name']);
$targetPath.=$image['name'];

if(move_uploaded_file($image['tmp_name'],$targetPath)) {
   $insertQuery="INSERT INTO $tbl_name(ArtistImage)VALUES('".$image['name']."')";                       
   $result=mysql_query($insertQuery) or die("Failed to upload image");
}
else {
   echo "Could not upload file. Check read/write persmissions on the directory";
}

2 个答案:

答案 0 :(得分:1)

您正在尝试将文件移动到已mysql_real_escape_string()的路径,这意味着它可能包含反斜杠,这显然不起作用(至少,不是按照您期望的方式)。

试试这个:

//This is my path for storing images. (I am using wamp 2.0)
$basePath = "../artistImages/";

$image = $_FILES['myimage'];
$storagePath = $basePath.$image['name'];

if (!is_dir($basePath)) {
  echo "Base path '$basePath' does not exist";
} else if (file_exists($storagePath)) {
  echo "File '$storagePath' already exists";
} else if (!move_uploaded_file($image['tmp_name'], $storagePath)) {
   echo "Could not move file to '$storagePath'. Check read/write persmissions on the directory";
} else {
   $insertQuery = "INSERT INTO `$tbl_name` (`ArtistImage`) VALUES ('".mysql_real_escape_string($image['name'])."')";
   if (!mysql_query($insertQuery)) die("DB insert failed: ".mysql_error());
}

请注意,上面的代码包含许多错误消息,您希望在将代码放入实际使用的任何环境之前删除或至少关闭,但它应该可以帮助您调试代码在发展中。

修改

如果你确实需要更改文件夹的权限,那么在Windows版本之间执行它的方法差别很大(实际上它对于所有2K +版本几乎完全相同,但在某些情况下你可能需要更改一些设置才能获得要显示的正确对话框,这将是http://www.SuperUser.com/

的问题

答案 1 :(得分:0)

你需要做几件事:

1-确保在将表格名称列入白名单之前测试$ tablename [ArtistImage]。在将其注入查询之前。
如果不这样做,您仍然可以使用SQL注入,因为转义仅适用于值,而不适用于动态注入SQL语句的表或列名(或其他SQL语法)

$tbl_name = ......
$allowed_tables = array('table1', 'table2');
if (in_array($tbl_name, $allowed_tables)) {
    $query = "......
} else { echo "tablename not allowed"; }

2 - 在表名和VALUES

之间添加一个空格
$insertQuery= "INSERT INTO `$tbl_name` VALUES('".$image['name']."')"; 

请参阅:How to prevent SQL injection with dynamic tablenames?

更简单的答案是从不让用户指定文件的保存位置,或者如何命名(在文件系统上)。
按照@Marc B的建议,只将desciption存储在数据库中,并使用PK(id)作为文件名。

$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO images (description) VALUES ('$description')"
$result = mysql_query($query);
$id = mysql_insert_id; //get the id you just inserted.
$filename = "../fixed_path/".$id.".jpg";
if (!move_uploaded_file($image['tmp_name'], $filename)) 
{ 
   echo "this should never happen" 
}