【发布时间】:2016-03-28 16:25:13
【问题描述】:
我正在尝试将图像从一个文件夹复制到另一个文件夹。我觉得我的路径是错误的,但是我尝试了这么多路径组合,现在我不确定是不是问题。
我正在尝试将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");
只是为了进一步说明问题:
- 用户上传的照片(存储在user_photos中)存储在我的数据库中的完整路径中,例如,如果Alice上传了一个名为
alice.jpg的文件,它将存储为user_data/user_photos/alice.jpg。这就是为什么我有变量$shortened_url,它只会获取文件的基本名称,即从user_data/user_photos/alice.jpg获取alice.jpg。我需要$shortened_url,因为数据库中的profile_pics列仅包含图像的基本名称,而不是完整路径。 - 使用
if statement,我正在尝试获取图像的基本名称,查看我的user_photos文件中是否存在同名图像,如果存在,请将其复制到profile_pics文件夹中并通过 UPDATE 语句将基本名称设置为profile_pics列。 UPDATE 语句工作正常,数据库中的图像名称确实发生了变化,但图像只是没有复制过来,这会损坏图像,因为它无法在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
- 查看
user_photos文件夹中是否存在名为$file的图像。 - 如果文件夹中有名为
alice.jpg的文件,则将该图像复制到profile_pics文件夹中。 - 就是这样。
【问题讨论】:
-
您应该在代码中添加一些测试以确定脚本在什么时候失败。如果文件根本没有找到要开始的文件,也许 file_exists 代码上的 else 会向自己显示一条消息。
-
@LukePittman - 嗯,看来你是对的。我有一个 else 语句,它回显了
don't exist和上面的所有copy()路径,它们都回显了 else 语句 - 这意味着没有一个copy()可以找到该文件。但我该如何解决这个问题?我需要它来查看文件是否存在,如果没有if (file_exists($file),我想不出其他方法来检查它的存在? -
你能展示你更新的代码吗?
-
@LukePittman - 当然,除了 if 语句之外没有太大变化:`if (file_exists($file)) { copy("../../" . $file, ". ./../profile_pics/" . $shortened_url); } else { echo "
不存在"; }`` .. 其他一切都保持不变,如上所示。
标签: php