Creating a directory with mkdir php

Asked

Viewed 357 times

0

I wrote a feature on php to upload files by running localhost it works normal creating the correct directory, but on the server it creates wrong, if I step the way: home\banners, it creates a folder with the name bootstrap.. and does not save the file, it is as if the function is not making use of the third parameter of the mkdir(path, mode, recursive = true), follows the function:

// arquivo config.php
define('DP', DIRECTORY_SEPARATOR);
define('UPLOAD_DIRECTORY', __DIR__ . '\..\assets' . DP);

// arquivo controllers.php
public function saveUploadFile(string $uploaddirectory = '', UploadedFile $file)
{
    // PEGA EXTENÇÃO DO ARQUIVO
    $_['ext'] = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
    // RENOMEIA PARA NUMERO EXADECIMAL ALEATORIO
    $_['rename'] = bin2hex(random_bytes(16));
    // JUNTA NOME DO ARQUIVO + EXTENSÇÃO
    $image = sprintf('%s.%0.8s', $_['rename'], $_['ext']);
    // CRIA PATH QUE SERA SALVA A IMAGEM        
    $_['path'] = UPLOAD_DIRECTORY . $uploaddirectory;       
    // SE NÃO EXISTE DIRETORIO CRIAR
    if( !is_dir( $_[ 'path' ] ) ) {
        if( !mkdir( $_['path'], 0777, true ) ){
            exit('falha ao criar arquivo no diretorio '. $_['path']);
        }
    }
    // MOVE ARQUIVO PARA O PATH
    $file->moveTo($_['path'] . DP . $image);
    // DEVOLVE CAMINHO ONDE IMAGEM FOI SALVA
    return $_['path'] . DP . $image;
}

Folder structure:

root
  ├── app
  │    └── Controllers
  │            └── Controllers.php
  ├── bootstrap
  │     └── Config.php
  └── assets
       └── // imagens devem ficar aqui

1 answer

2


Change:

\..\assets

For:

/../assets

Allies don’t even need to use:

define('DP', DIRECTORY_SEPARATOR);

Both Windows and Linux accept /, then do it like this:

// arquivo config.php
define('UPLOAD_DIRECTORY', __DIR__ . '/../assets/');

// arquivo controllers.php
public function saveUploadFile(string $uploaddirectory = '', UploadedFile $file)
{
    // PEGA EXTENÇÃO DO ARQUIVO
    $_['ext'] = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
    // RENOMEIA PARA NUMERO EXADECIMAL ALEATORIO
    $_['rename'] = bin2hex(random_bytes(16));
    // JUNTA NOME DO ARQUIVO + EXTENSÇÃO
    $image = sprintf('%s.%0.8s', $_['rename'], $_['ext']);
    // CRIA PATH QUE SERA SALVA A IMAGEM        
    $_['path'] = UPLOAD_DIRECTORY . $uploaddirectory;       
    // SE NÃO EXISTE DIRETORIO CRIAR
    if( !is_dir( $_[ 'path' ] ) ) {
        if( !mkdir( $_['path'], 0777, true ) ){
            exit('falha ao criar arquivo no diretorio '. $_['path']);
        }
    }
    // MOVE ARQUIVO PARA O PATH
    $file->moveTo($_['path'] . '/' . $image);
    // DEVOLVE CAMINHO ONDE IMAGEM FOI SALVA
    return $_['path'] . '/' . $image;
}

extras

Now about the use of $_['ext'], $_['path'], etc, really do not know why to do this, the variables are already isolated in the scope of saveUploadFile, there is no reason to keep creating an array, something else your array or this started, it should have something like this:

public function saveUploadFile(string $uploaddirectory = '', UploadedFile $file)
{
    // PEGA EXTENÇÃO DO ARQUIVO
    $_ = array();

Because if you don’t you’ll probably fill the PHP log with several warnings no need, still yes it would be more practical only to create the vars directly, since this in the scope of the method, has no need of arrays.

Another jealousy that makes no sense are the parameters:

saveUploadFile(string $uploaddirectory = '', UploadedFile $file)

There is no reason why the first parameter should be opitional, in fact it is impossible for it to be opitional, that is, there is no way to pass the second without passing the first, the right would be:

saveUploadFile(string $uploaddirectory, UploadedFile $file)

The end result would be this:

// arquivo config.php
define('UPLOAD_DIRECTORY', __DIR__ . '/../assets/');

// arquivo controllers.php
public function saveUploadFile(string $uploaddirectory, UploadedFile $file)
{
    // PEGA EXTENÇÃO DO ARQUIVO
    $ext = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);

    // RENOMEIA PARA NUMERO EXADECIMAL ALEATORIO
    $rename = bin2hex(random_bytes(16));

    // JUNTA NOME DO ARQUIVO + EXTENSÇÃO
    $image = sprintf('%s.%0.8s', $rename, $ext);

    // CRIA PATH QUE SERA SALVA A IMAGEM        
    $path = UPLOAD_DIRECTORY . $uploaddirectory;

    // SE NÃO EXISTE DIRETORIO CRIAR
    if( !is_dir( $path ) ) {
        if( !mkdir( $path, 0777, true ) ){
            exit('falha ao criar arquivo no diretorio '. $path);
        }
    }

    // MOVE ARQUIVO PARA O PATH
    $file->moveTo($path . '/' . $image);

    // DEVOLVE CAMINHO ONDE IMAGEM FOI SALVA
    return $path . '/' . $image;
}
  • 1

    was that same, the backslashed fixed other parts of the code too and now this creating correctly, thank you!

  • @Hebertlima I typed wrong a line, change $_ext = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION); for $ext = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);, already corrected in the reply

  • had noticed, and fixed here xD vlw

  • About DIRECTORY_SEPARATOR I recommend reading (since there is what we call multiplatform) https://answall.com/questions/2304/difference-entrepath-separator-e-directory-separator

  • 1

    @Marcosxavier makes no difference to operating systems within native PHP functions. The only use is if you will pass to commands like exec(), although nowadays WINDOWS also no longer suffers from this problem, rarely will use this.

  • about DIRECTORY_SEPARATOR is my custom to use, ends up being automatico rs

  • 2

    @Hebertlima then do not use things in automatic, use when necessary :) ... in case writing / is write much less than writing DIRECTORY_SEPARATOR or DS

  • I will also review the part of the unnecessary arrays and the initialization, I have this bad habit of not initializing the arrays =X @Guilhermenascimento

  • @Guilherme Nascimento Question of good practices. It is for reasons like this that bad codes are appearing. Little things like this will leave the dev relaxed. My point of view, not that use / or Ds or DIRECTORY_SEPARATOR.

  • 2

    Dear @Marcosxavier good practice is synonymous with myths in programming, there are many things that are misleading, people understand the language but do not understand the architecture of the operating system, then make up fabulas about why you should use X form or Y form. The question is to understand the need for a Feature and the goal by which it was created, even in large frameworks I have already found "redundancies" that you realize it’s because of DEV confusion or simply because people follow "cake recipes" but don’t really learn the essence.

  • I disagree with your opinion in some quarters, but I respect it. I think (speaking of IT), cake recipes serve exactly to avoid reworks or redundant codes. If in this great framework you cited found redundancy imagine if you did not have the cake recipes. Patterns help prevent (in a multi-dev project) that everyone does it their own way, if you do it yourself, I see no problem following your own pattern. As for not understanding system architecture nor will I enter the merit.

  • 2

    Dear @Marcosxavier the problem is people following cake recipe without learning the basics and learning the essence, for me you are not disagreeing with me, in fact you are not understanding the root of the problem I want to talk about

  • 2

    I always say (there are many references on the site itself, if you search) that the expression "Good practices" is usually accompanied by nonsense. Time is solidifying this experience (there are already 30 years in the area, there are things that are shot and fall). "Good practices" simply do not exist. If you have a reason to do something, it is by reason (and you say what it is). If you do not say the real reason, it is because you do not know for sure. If you have something that you really think is "good practice," you don’t need a new name for it. I say this to open the minds of colleagues who unfortunately will hear a lot of the phrase around.

  • In the first answer, I agree on the essence and on disagreement and understanding, I understand and disagree. I close my part in this discussion. As Bacco has much more time than me in the area and has formed opinion also and in view of that, what to pass from here will not add to the topic. It’s nothing personal, for me it’s a healthy discussion.

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.