Php permission denied www data

Как решить проблему permission denied при сохранении файла php?

На сайте есть форма, через которую клиент должен отправить файл
а сервер должен его сохранить
Форма посылает запрос, я вижу в суперглобальном массиве $_FILES мой массив с temp_name и тп параметрами
На сколько я понимаю файл складываем в папку /temp на сервере (в моем контексте в докер контейнере)
ставил xdebug и останавливался — файл в папке temp действительно есть

Итак, у меня есть массив, теперь я его должен «сохранить» в нужной мне папке
делаю я это через

move_uploaded_file($file['tmp_name'], $absolutePath)

эта функция должна возвратить TRUE если все прошло
но не возвращает
Включил показ ошибок и предупреждений
и вижу там такая ошибка

move_uploaded_file(/app/upload/my_file.xlsx): failed to open stream: Permission denied in . move_uploaded_file(): Unable to move '/tmp/php5FnOTW' to '/app/upload/my_file.xlsx' in . 

Проблема с правами в докере
Помогите разложить все по полочкам в голове, понять проблему и решить ее
в php.ini у параметра upload_tmp_dir стоит null
как я понял в этом случае использует системная папка /temp
переходим внутрь контейнера
ниже вывод ls -la
— в папке с сайтом (upload)
— в корне контейнера (tmp)

drwxrwxr-x 24 1000 1000 4096 Jul 19 13:36 upload drwxrwxrwt 1 root root 4096 Jul 19 14:52 tmp

1000 — это id моего юзера на хост машине (этот id пробрасывается и в контейнер)
root — это рут в контейнере
внутри контейнера посмотрел под кем работает php
/usr/local/etc/php-fpm.d/www.conf

user = www-data group = www-data
uid=33(www-data) gid=33(www-data) groups=33(www-data)
uid=1000(pankov) gid=1000(pankov) группы=1000(pankov),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),109(kvm),122(lpadmin),134(lxd),135(sambashare),999(docker)

Как я понял в temp складывается
права rwx \ rwx \ rwt (что за rwt??)
но пользователь и группа этой папки root
а php от www-data работает,
получается смотрим на последний 3 буквы (others) пермишенов — rwt
чтение и запись разрешена (что за t?)

Читайте также:  Java completablefuture get result

Но сама ошибка говорит, что именно из temp нет возможности переместить в upload
перемещает, выходит, php, который работает от www-data
и этот www-data стучится в upload с r-x (для others) те только чтение (без записи) — поэтому ошибка?
(если я все верно понимаю, то каков способ ее решения? в какой момент давать права работая в докере)

На данный момент я окончательно запутался среди www-data / root / pankov пользователей

Источник

PHP: mkdir, почему permission denied при 0777?

В этой ошибке указано, что php скрипт, расположенный тут:
/var/www/www-root/data/www/xndaasdqfjqwm7b.xn--p1ai/vendor/yiisoft/yii2/helpers/BaseFileHelper.php
видимо пытается создать папку ( mkdir() line 488)

Так какой именно папке вы права задаете?
Посмотрите в коде/логах, какую папку он пытается создать и где и вот там уже и назначайте права.

L0k1

L0k1

webinar

CityCat4

CityCat4

shambler81

в 99% случаях это не понимание всей системы прав линукс
В вашем случае это скорее всего владельцы файлов и группы
По мима 777 так же у файла есть владелец и группа
1. отвечает что этот юзер попадет в первую семерку
вторая за вторую
3 соотваетственно все левые
права на файлы выгледят реально так
index.php root:root 777
В вашем случае вы оперируете самой маской 777
но не забываете что вы даже не тот пользователь.
А апачь может например не иметь прав создавать в этой директории.
Так что сделайте ls — l
посмотрите права
Далее поменяйте владельца на правильного
так

chown -R bitrix:bitrix /home/bitrix/ext_www/site.ru

В вашем случае скорее всего это www-data:www-data или apache:apache
-R -рекурсивно
Команда потенциально опасная и пишите ее всегда с полным путем а не «.» уж больно шустро она меняет права.
ДАлее если все решилось то не работайте от рута а от того полльзователя от кооторого работает сайт.
Ну или меняйте права постоянно.
А вот если не заработало то нужно знать еще о нескольких моментах
Есть еще дополнительные права и даже утилиты ограничивающие скажем специфические вещи, например разрешающие только дописывать. Или запрещающие удалять что-либо в этом каталоге но разрешающие создавать . это отдельная история.
В любом случае с вас ls -la текущей директории и такой же список с работоающей валидно
Так же есть специфические моды представления php которые запрещяют все что кроме 644 755, вплоть до 777 ;).

Источник

Granting write permissions to www-data group

I am creating a website and part of the function is to write out user generated data with php. I’m using nginx on Ubuntu 13.04. A the moment I’m only testing and everything is served through nginx on locahost. My php script fails to write the text file (although I can do this manually) and I think it’s a permissions problem for writing to my /var/www/example.com/public_html directory. At the moment I (iain) own this directory but it seems it would make more sense to transfer ownership of the /var/www directory and everything inside that to the www-data user (or should that be group?) and add myself to the www-data group. Is the following the right way to do this?

useradd -G www-data iain chown -R www-data:www-data /var/www/example.com chmod 775 /var/www 

1 Answer 1

First, useradd creates a new user. As you (iain) already exist, you want to call usermod instead. So that would be:

sudo usermod -aG www-data iain addgroup www-data 

(note the -a on Debian-based servers (Ubuntu included) that will add you to that group, and keep your membership to other groups. Forget it and you will belong to the www-data group only — could be a bad experience if one of them was wheel. On SUSE-type servers the option is -A instead of -aG so read man usermod carefully to get it right.)

Second, you don’t want apache to have full rw access to /var/www : this is potentially a major security breach. As a general rule, allow only what you need, and nothing more (principle of least privilege). In this case, you need apache ( www-data ) and you ( www-data group) to write (and read) in /var/www/example.com/public_html , so

sudo chown -R www-data:www-data /var/www/example.com/public_html sudo chmod -R 770 /var/www/example.com/public_html 

Edit: to answer your original question, yes, any member of www-data can now read and execute /var/www (because the last bit of your permissions is 5 = read + exec). But because you haven’t used the -R switch, that applies only to /var/www , and not to the files and sub-directories it contains. Now, whether they can write is another matter, and depends on the group of /var/www , which you haven’t set. I guess it is typically root:root , so no, they (probably) can’t write.

Edit on 2014-06-22: added a note that -aG option is valid on Debian-based servers. It apparently varies with the distribution, so read man carefully before executing.

Источник

How do I save php file in var/www/html when it shows error «Permission denied»? [duplicate]

I cannot save a php file in var/www/html and my computer shows error «Permission denied» . How to change permission to save file here?

2 Answers 2

You need to change the permissions for /var/www/html folder.

running this command will give everyone write access to the html fodder.

The o stands for other and the + adds the permissions w is write.

Then you should be able to copy you’re php file over to /var/www/html with out using Root permissions

If you want to learn more about the command chmod click on the link below.

You need to change the permissions of that folder to gain access to write files. Here is the GUI method. Only use terminal to open Nautilus with root permisions. There is a risk opening Nautilus as root. Read it here.

  1. Open Terminal
  2. type sudo nautilus hit enter
  3. Navigate to the target file or folder you want to change permissions (/var/www)
  4. Right click the file or folder (html folder)
  5. Select Properties
  6. Click on the Permissions tab
  7. Click on the Access files in the Others section
  8. Select “Create and delete files”
  9. Click Change Permissions for Enclosed Files
  10. In the resulting window, Select Read and Write under Files and Create and delete files under Folders
  11. Click Change
  12. Click Close.

Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

Источник

Оцените статью