如何在 PHP 的存储目录中上传图像,它给了我错误"image is not uploaded"



上传图像时出错。错误是image in not uploaded请帮我计算一下。

class User extends DatabaseConnection{
public function addNewUser() {
$db = $this->getConn();
$add_query = "INSERT into `users`"
. "(`user_id` , `first_name` , `middle_name` , `last_name` , `user_name` , `email` , `contact_number` , `password` , `gender` , `date_of_birth` , `country` , `city` , `profile_image` , `created_at` , `updated_at`  , `role`)"
. "VALUES"
. "('NULL' , '$this->first_name' , '$this->middle_name' , '$this->last_name' , '$this->user_name' , '$this->email' , '$this->contact_number' , '$this->password' , '$this->gender' , '$this->dob' , '$this->country' , '$this->city' , '$this->profile_image' , NOW() ,  NOW() , 'visitor')";
$db->query($add_query);
if ($db->errno) {
throw new Exception($db->error);

$storage_path = "../storage/" . "$this->user_name " . "/";
if (!is_dir('../storage')) {
if (!mkdir('../storage')) {
throw new Exception("Storage Directory not created");
}
}
if (!is_dir("../storage/$this->user_name")) {
if (!mkdir("../storage/$this->user_name")) {
throw new Exception("User Directory not created");
}
}
$upload = move_uploaded_file($this->profile_tmp_name, $storage_path . $this->profile_image);
if (!$upload) {
throw new Exception("User Image not uploaded");
}
}
}
}

我认为这里的主要问题在于您使用的字符串类型。

在PHP中,至少有两种字符串表示方式。

  • 单引号->按原样写入所有内容,例如'hello $world'将按字面打印hello $world

  • 双引号->打印出嵌入其中的变量,例如"$data"将打印出变量$data的值。请注意,不是"简单"的数据变量,或者那些具有限定符(如$this->data甚至$row['data'](的数据变量有要括在大括号之间,如"{$this->data}""{$row['data']}",否则解析器将很难解析它们,因此可能会得到意外的结果。

话虽如此,您的代码可以更改为以下。。。

$add_query = "INSERT into `users`"
. "(`user_id` , `first_name` , `middle_name` , `last_name` , `user_name` , `email` , `contact_number` , `password` , `gender` , `date_of_birth` , `country` , `city` , `profile_image` , `created_at` , `updated_at`  , `role`)"
. "VALUES"
. "('NULL' , {$this->first_name} , {$this->middle_name} , {$this->last_name} , {$this->user_name} , {$this->email} , {$this->contact_number} , {$this->password} , {$this->gender} , {$this->dob} , {$this->country} , {$this->city} , {$this->profile_image} , NOW() ,  NOW() , 'visitor')";
$db->query($add_query);
if ($db->errno) {
throw new Exception($db->error);

$storage_path = "../storage/" . $this->user_name . "/";
if (!is_dir('../storage')) {
if (!mkdir('../storage')) {
throw new Exception("Storage Directory not created");
}
}
if (!is_dir("../storage/{$this->user_name}")) {
if (!mkdir("../storage/{$this->user_name}")) {
throw new Exception("User Directory not created");
}
}

$upload = move_uploaded_file($this->profile_tmp_name, $storage_path . $this->profile_image);
if (!$upload) {
throw new Exception("User Image not uploaded");
}
}

但是,如果问题仍然存在。然后,你必须确保你试图移动上传文件的目录已经存在,并且对试图对其进行写入的用户具有写入权限。通常在UNIX上,这可以通过chmod 777 /path/to/directory实现。

最新更新