@Vova135798

Почему выдает ошибку при загрузке фотографии?

При загрузке фотографии выдает ошибку: Warning: move_uploaded_file(images/): Failed to open stream: No such file or directory in /Applications/MAMP/htdocs/product.php on line 58

Warning: move_uploaded_file(): Unable to move "/Applications/MAMP/tmp/php/phpSAWSI3" to "images/" in /Applications/MAMP/htdocs/product.php on line 58

Папка images находится в папке с product.php

product.php

class Product{
    public $title;
    private $price;
    private $description;
    private $category;
    public $image;
    private $active;

    private $link;
    private $target_path = "images/";


    public function __construct($title){
        $this->title = $title;

        $this->link = new mysqli("localhost", "root", "root", "testdb");
    }

    public function setPrice($price){
        if($price == ""){
            $this->price = 0;
        }
        else{
            $this->price = $price;
        }
    }

    public function setDescription($description){
        if($description == ""){
            $this->description = '';
        }
        else{
            $this->description = $description;
        }
    }

    public function setCategory($category){
        if($category == ""){
            $this->category = '';
        }
        else{
            $this->category = $category;
        }
    }

    public function setImage($image){
        if($image == ''){
            $this->image = '';
        }
        else{
            if($this->is_valid_type($image['name'])){
                $this->target_path .= $image['name'];
                if(move_uploaded_file($image['tmp_name'], $this->target_path)){
                    $this->image = $this->target_path;
                }
            }
        }
    }

    public function setActive($active){
        if($active==1){
            $this->active = 1;
        }
        else{
            $this->active = 0;
        }
    }

    public function addProduct(){
        $query = "INSERT INTO products (title, price, description, category, image, active) VALUES (?,?,?,?,?,?)";
        $stmt = $this->link->prepare($query);
        $stmt->bind_param("sisssi", $this->title, $this->price, $this->description, $this->category, $this->image, $this->active);
        $stmt->execute();
    }

    public function deleteProduct($id){
        $query = "DELETE product WHERE id=?";
        $stmt = $this->link->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
    }

    function is_valid_type($filename){
        $valid_types = array("jpeg", "png", "jpg", "svg");
        $type = explode("." , $filename);
        $file_type = end($type);
        if (in_array($file_type, $valid_types)){
          return true;
        }
        else{
          return false;
        }
    }
}


form.php
<form method="POST" enctype="multipart/form-data" action="">
    <p><label for="title">Название товара</label><br>
        <input type="text" id="title" required name="title">
    </p>
    <p><label for="price">Цена товара</label><br>
        <input type="number" id="price" name="price">
    </p>
    <p><label for="description">Описание товара</label><br>
        <textarea name="description" id="description" cols="30" rows="3"></textarea>
    </p>
    <p><label for="category">Категория товара</label><br>
        <input type="text" id="category" name="category">
    </p>
    <p><label for="image">Картинка товара</label><br>
        <input id="image" type="file" name="image">
    </p><input type="hidden" name="MAX_FILE_SIZE" value="1000000">
    <p><label for="active">Активен</label>
        <input id="active" value="1" name="active" type="checkbox">
    </p>

    <input type="submit" value="Добавить товар">

</form>
<?php

    if(isset($_POST["title"])){
        $new_product = new Product($_POST["title"]);
        $new_product->setPrice($_POST["price"]);
        $new_product->setDescription($_POST["description"]);
        $new_product->setCategory($_POST["category"]);
        $new_product->setImage($_FILES["image"]);
        $new_product->setActive($_POST["active"]);
        $new_product->addProduct();
    }
  • Вопрос задан
  • 53 просмотра
Решения вопроса 1
ipatiev
@ipatiev Куратор тега PHP
Потомок старинного рода Ипатьевых-Колотитьевых
То, что папка images находится в папке с product.php, не имеет вообще никакого значения.
product.php не имеет отношения к работе веб-сервера. из неё просто читается код класса.

При этом путь images/ является относительным. То есть, в зависимости от точки входа может вести в совершенно разные места.
Именно поэтому все пути всегда должны быть абсолютными. Пусть даже и с помощью костыля __DIR__
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
YCLIENTS Москва
от 200 000 до 350 000 ₽
Ведисофт Екатеринбург
от 25 000 ₽
ИТЦ Аусферр Магнитогорск
от 100 000 до 160 000 ₽
26 апр. 2024, в 10:21
1200 руб./в час
26 апр. 2024, в 10:10
1000 руб./за проект