John Davidson

php - Why Symfony File Upload path always begins with /public folder when using getenv()?

0 comments
Message:


This is my code:


.env file:


UPLOAD_PATH=".var/uploads/docs"

MyController.php


$destination = getenv('UPLOAD_PATH');
/** @var UploadedFile $uploadedFile */
$uploadedFile = $form['file']->getData();
dump($uploadedFile->move($destination, $uploadedFile->getClientOriginalName()));

The dump output:


  pathname: "./var/uploads/docs/test.txt"
realPath: "/var/www/html/public/var/uploads/docs/test.txt"

Actually my intention is to save it in var folder but it always ends up in public/var... every path I enter no matter how and what end up in public folder.


However when I try this it works fine:


$destination = $this->getParameter('kernel.project_dir').'/var/uploads/docs';

I want to use the first way with getenv and .env, is there any way to make it work and upload files to desired folder?



My Answer:
/uploads

Controller file:

php
$uploadPath = getenv('UPLOAD_PATH');
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/public' . $uploadPath;

// Rest of the file upload logic here


When using `getenv('UPLOAD_PATH')`, the path always begins with the `/public` folder because `getenv()` retrieves the value of an environment variable, which in this case is the `UPLOAD_PATH` variable set in the `.env` file.

To avoid this, you can modify the `UPLOAD_PATH` variable in the `.env` file to remove the `/public` prefix:


UPLOAD_PATH=/uploads


Then, in your controller file, you can concatenate the `UPLOAD_PATH` directly without adding the `/public` prefix:

php
$uploadPath = getenv('UPLOAD_PATH');
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $uploadPath;

// Rest of the file upload logic here

Rate this post

3 of 5 based on 4240 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us