Home > database >  Can't save image by php
Can't save image by php

Time:10-22

I have this chunk of code, I want to write a file to the server and save it to DB, the problem is that file is not saved.

if (($_FILES['thumbnail']['name']!="")){
        $target_dir = "img/";
        $file = $_FILES['thumbnail']['name'];
        $path = pathinfo($file);
        $filename = $path['filename'];
        $ext = $path['extension'];
        $temp_name = $_FILES['thumbnail']['tmp_name'];
        $path_filename_ext = $target_dir.$filename.".".$ext;
       
       var_dump(move_uploaded_file($temp_name,$path_filename_ext));

      }

In errors it returns this:

Warning
: move_uploaded_file(img/textak.txt): failed to open stream: Permission denied in
/home/kloucto2/www/create_new_article.php
on line
21


Warning
: move_uploaded_file(): Unable to move '/tmp/phpxRsCsr' to 'img/textak.txt' in
/home/kloucto2/www/create_new_article.php
on line
21

bool(false)

The form looks like this:

 <form id="article-form" class="login-form" enctype="multipart/form-data" method="POST" action="">
            <label for="thumbnail">Vyber thumbnail pro článek:</label>
            <input type="file" form='article-form' id="thumbnail" name="thumbnail">
        </form>

CodePudding user response:

I had not have w permission to others set

CodePudding user response:

Here is how to upload file in php

if (isset($_FILES['thumbnail'])){
    $target_dir = __DIR__ . "/img/";
    $data = $_FILES['thumbnail'];
    $filename = $data['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $rawData = $data['tmp_name'];


    $path_filename_ext = $target_dir . $filename . "." . $ext;

    if(!is_dir($target_dir)){
       // Create directory with permission 
        mkdir($target_dir, 0777, true);
        chmod($target_dir, 0755);
    }
    
    if(file_exists($path_filename_ext)){
       //Save with new name by appending date in front
        $path_filename_ext =  $target_dir . date("d-m-h-m-s") . "-" .$filename . "." .$ext;
    }

   if(move_uploaded_file($rawData, $path_filename_ext)){
       //var_export($_FILES);
       echo "Upload completed";
   }else{
      echo "Upload failed"
   }
}
  • Related