我正在尝试将图像从一个文件夹复制到另一个文件夹。我觉得我的路径是错的,但我已经尝试了很多路径组合,我现在不确定它是否是问题。
我正在尝试将图像(如果存在)从user_photos
文件夹复制到profile_pics
文件夹中。以下是它们所在的位置,以及曾经调用过的change_dp.php
脚本将执行copy()
。
www > user_data > user_photos > photos_are_here
www > user_data > profile_pics > photos_are_here
www > inc > change_dp.php
以下是change_dp.php
:
$all_pics = mysqli_query ($connect, "SELECT * FROM user_photos WHERE username = '$username'");
$row_query = mysqli_fetch_assoc($all_pics);
$get_photo_owner = $row_query['username'];
$get_photo_id = $_GET['id'];
$get_pic_with_id = mysqli_query ($connect, "SELECT * FROM user_photos WHERE id = '$get_photo_id'");
$row_query2 = mysqli_fetch_assoc($get_pic_with_id);
$img_url = $row_query2['img_url'];
$file = $img_url;
$arrPathInfo = pathinfo($file);
$shortened_url = $arrPathInfo['basename'];
if (file_exists($file)) {
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
}
$pro_pic_change = mysqli_query($connect, "UPDATE users SET profile_pic='$shortened_url' WHERE username = '$username'") or die ($connect);
header("Location: /photos/$get_photo_owner");
更多地说明问题:
alice.jpg
的文件,则会将其存储为user_data/user_photos/alice.jpg
。这就是为什么我有变量$shortened_url
,它只获取文件的基本名称,即从alice.jpg
获取user_data/user_photos/alice.jpg
。我需要$shortened_url
,因为数据库中的列profile_pics
只包含图像的基本名称,而不是完整路径。if statement
,我尝试获取图像的基本名称,查看我的user_photos
文件中是否存在具有相同名称的图像,如果存在,则将其复制到{ {1}}文件夹,并通过UPDATE语句将基本名称设置为profile_pics
列。 UPDATE语句工作正常,图像名称确实在数据库中更改,但图像不会复制,这会破坏图像,因为它无法在profile_pics
文件夹中找到它。我尝试过:
profile_pics
没有哪个有用。
修改:
以下是我希望代码执行的操作:
让我们为copy($file, "../profile_pics/" . $shortened_url);
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
copy($file, "user_data/profile_pics/" . $shortened_url);
分配值,例如:
$file
$file = user_data/user_photos/alice.jpg
文件夹中是否存在名为$ file的图片。user_photos
的文件,请将该图像复制到alice.jpg
文件夹中。答案 0 :(得分:0)
您可以使用__DIR__
魔术常量,然后根据您可以使用realpath()
函数甚至dirname()
函数转到目录层次结构中的较高级别。这样可以减少混淆,减少错误。
E.g:
$upOneLevel = realpath(__DIR__."../");
$upTwoLevels = realpath(__DIR__."../../");
因此,要访问您的文件,请使用:
$fileRealPath = $upOneLevel."/".$file;
$fileRealDestination = $upOneLevel."user_data/profile_pics/".$shortened_url;
我还建议仅在文件存在且复制命令成功执行时才更新数据库中的数据:
if (file_exists($fileRealPath)) {
if(copy($fileRealPath, $fileRealDestination)) {
//TODO db logic here
} else {
//TODO error handling here
}
} else {
//TODO error handling here
}