Windows fopen permission denied

У PHP не хватает прав на fopen

На локальной машине (линукс минт) организовал хостинг.

PHP выдает ошибку: PHP Warning: fopen(/var/. /section_pub_id.html): failed to open stream: Permission denied in .

Ошибка, конечно, гуглится, но дают советы выставить права 777. Я считаю что это как-то не правильно, потому, что:

Захожу на купленный виртуальный хостинг по ssh и смотрю там права:

(тоесть никаких 777, и при этом все работает)

Теперь на локальной машине:

При установке вебсервера нагугливались советы по выставлению прав на папки и файлы проекта, которые я применил:

У меня подозрения, что я как-то неправильно поставил пых?

Для начала надо хотя бы узнать, от какого пользователя работает php.

uid=33(www-data) gid=33(www-data) groups=33(www-data)

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

Если объясните или пнёте меня в хороший мануал я буду оооооочень благодарен.

Судя по ответу system — пых работает из под www-data ? И у него конечно же нет прав к моим файлам? Может как то отнести этого www-data к какой-то группе? Пойду гуглить.

Судя по ответу system — пых работает из под www-data ?

И у него конечно же нет прав к моим файлам?
drwxr-xr-x 2 yadfeshhm yadfeshhm

У пользователя yadfeshhm есть права на чтение-запись-выполнение, у остальных только чтение-выполнение.

Может как то отнести этого www-data к какой-то группе?

Можно:
a) Сделать www-data владельцем директории с сайтом (chown -R www-data /path/to/your/dir)
b) Дать всем rwx (777), но ты этого не хочешь и это в некоторых случаях не совсем корректно.
c) Разрешить группе запись в эту директорию и дать права группе www-data на нее (chgrp -R www-data /path/to/your/dir и chmod -R g+w /path/to/your/dir)

Мог опечататься, но вроде все так. Извини, в лоркод оформлять некогда, пишу из не очень удобных условий.

Дополню что нужно проверять права еще и на «вышестоящих» каталогах, может быть такое что дашь права www-data на чтение\выполнение, а на доступ в каталог, например, /var/ у него прав не будет и, как следствие, этот файл останется для него недоступным.

Если с этим будут проблемы — самый простой вариант сделать этот каталог с файлами в home этого пользователя или прям в корне — меньше возможности будет напороться на проблемы в вышестоящих каталогах.

Пошел по пути a)

a) Сделать www-data владельцем директории с сайтом (chown -R www-data /path/to/your/dir)

При редактировании проекта и сохранении (на каждый файл) любого файла требует пароль. Это же не реально))) неужели выход только 777. Как дать права и для пользователя yadfeshhm и для www-data равнозначные и полные?

Re: Пошел по пути a)

Тогда можно залогиниться под пользователем www-data ( sudo -u www-data -s /bin/bash , либо su -s /bin/bash -l www-data из-под рута) и потом редактировать.

При редактировании проекта и сохранении (на каждый файл) любого файла требует пароль. Это же не реально))) неужели выход только 777. Как дать права и для пользователя yadfeshhm и для www-data равнозначные и полные?

chown -R www-data:yadfeshhm /path/to/your/dir
chmod 0760 -R /path/to/your/dir

Читайте также:  Не устанавливается windows 10 с флешки ошибка 0x80070570

А если пойти от обратного и настроить сам apache2

А если в /etc/apache2/envvars заменить пользователя и группу на себя?:

Вроде ничем не грозит и любым новым файлам ничего «чоунить» и «чмодить» не нужно, а? =)

Вроде ничем не грозит и любым новым файлам ничего «чоунить» и «чмодить» не нужно, а? =)

Ничем, просто если кто-то тебе php-shell зальет, получит доступ к всему твоему хомяку, всем документам, и, скорее всего, sudo у тебя тоже есть.

PHP: fopen() Permission denied

I am confused with this code:

when I execute it, I get an error:

where is the problem?

Thanks a lot!I have found the problem,I use FC13,because of the protect of SELinux,some action is denied.So, I just need to get rid of the protect.

8 Answers 8

This issue can also be a result of having SELinux enabled. This can be solved using:

is most likely looking in another directory

I have been receiving the same error «failed to open stream. permission denied»when trying to write a file on the server using PHP. I tried everything on the internet to fix the error. I changed ownership of the files,directories and sub-directories on the server to «apache», I did a chmod 777 on all the files, directories, sub-directories, I ran restorecon -R , I ran chcon unconfined_u:object_r:httpd_user_content_t:s0 on all the files, but the only thing that seemed to work is turning SELinux off completely.

I finally resolved the issue. The problem lay in the boolean parameters used by SELinux. I performed the following command to get a list of all the booleans related to httpd.

This gave a list of about 36 parameters.

I painfully went and turned on every boolean using the setsebool command until the «failed to open stream. permission denied» error went away.

When I turned «on» the httpd_unified boolean, the error went away!! When I turned it «off», the error came back!!

Ошибка bash permission denied

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку bash permission denied. Эта ошибка выводится, даже если вы использовали sudo.

Казалось бы, sudo есть, значит права суперпользователя получены и все должно работать но тут все не так просто. В этой статье мы рассмотрим почему возникает ошибка bash permission denied и как ее обойти.

Ошибка bash permission denied

Допустим, вы выполняете команду:

sudo echo «nameserver 8.8.8.8» >> /etc/resolv.conf

А в результате вместо записи строчки в /etc/resolv.conf получаете ошибку:

bash: /etc/resolv.conf permission denied

В русской локализации это будет отказано в доступе bash linux. Так происходит потому что вы запускаете с правами суперпользователя утилиту echo и она честно выводит вашу строку в стандартный вывод bash с правами суперпользователя. Но bash запущен от обычного пользователя, и когда интерпретатор bash пытается записать полученную строчку в системный файл, естественно, что вы получите ошибку.

Но существует несколько способов обойти это ограничение, вы можете, например, использовать команду tee, которая записывает стандартный вывод в файл или запустить саму оболочку от имени суперпользователя. Рассмотрим сначала вариант с tee:

echo ‘текст’ | sudo tee -a /путь/к/файлу

echo ‘nameserver 8.8.8.8’ | sudo tee -a /etc/resolv.conf

Это очень простое решение, но, кроме того, вы можете запустить оболочку bash с правами суперпользователя, чтобы дать ей доступ на запись:

sudo sh -c ‘echo текст >> /путь/к/файлу’
sudo bash -c ‘echo текст >> /путь/к/файлу’

Читайте также:  Муви мейкер для линукс

sudo bash -c ‘echo nameserver 8.8.8.8 >> /etc/resolv.conf

Еще одно решение, призванное, упростить эту команду, добавить такой код в

sudoe() <
[[ «$#» -ne 2 ]] && echo «Usage: sudoe

» && return 1
echo «$1» | sudo tee —append «$2» > /dev/null
>

Дальше для вывода строки в файл выполняйте:

sudoe ‘текст’ >> /путь/к/файлу

sudoe «nameserver 8.8.8.8» > /etc/resolv.conf

Теперь все будет работать, как и ожидалось, и ошибка bash отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.

Выводы

В этой небольшой статье мы разобрали почему возникает ошибка bash permission denied при использовании команды echo для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.

Permission denied when trying to import a CSV file from PGAdmin

I’m using PGAdmin 1.14.3.

When I try to execute an import command:

ERROR: could not open file «C:\Users\denis\Desktop\BP2Project\USA\US.txt» for reading: Permission denied SQL state: 42501

I did look up other similar questions and none of them solved my issue.

I logged in as user «postgres» who is the superuser. I don’t see why I’m missing permissions. I’m on Windows 7.

8 Answers 8

The user Postgres must have read access on the file from which you are about to copy.

Look at this article to see how to modify files’ security access on Windows.

The permissions article mentioned in the answer by Houari and Flimzy is a good reference material, but a direct answer (the quick fix I used) is:

  • Right click the folder containing the data file(s) that permission was denied to and then click Properties.
  • In the Folder’s Properties window, select the Security tab.
  • Click the Edit button.
  • In the «Permissions for the folder» window that opened, click the Add. button.
  • Type Everyone into the «Enter the object names to select» text area box.
  • Click OK and the window will close.
  • Verify that the default Read & Execute permissions were set to Allow via the check checkbox in the previous window.
  • Click OK and the window will close.
  • Click the Apply button in the Folder Properties window.

Now you can run the SQL COPY statement that needs to access those files.

  • Once done, return to the Folder’s Properties window.
  • Click the Edit button.
  • Select the Everyone entry in the «Group or user names:» field.
  • Click the Remove button.
  • Click OK on the remaining open windows.

The permissions have now been returned to what they were.

Ok, this is how got COPY command working,to export a table to CSV, step by step. Pls note that I am using pgAdmin 111.

  1. Create the target folder you want to export a table to. E.g C:\myExports
  2. Set a read/write permission on this folder following the steps below :

Right click the folder containing the data file(s) that permission was denied >to and then click Properties.

In the Folder’s Properties window, select the Security tab. Click the Edit button.

In the «Permissions for the folder» window that opened, click the Add. button. Type Everyone into the «Enter the object names to select» text area box.

Читайте также:  Тупит комп что делать windows 10

Click OK and the window will close. Verify that the default Read & Execute permissions were set to Allow via the >check checkbox in the previous window. Click OK and the window will close.

Click the Apply button in the Folder Properties window.

This is the tricky part, inside myExports folder create a blank CSV file with your desired name.E.g employee.csv

Then run the Copy command like this :

copy employee to ‘C:\myExports\employee.csv’ delimiter ‘,’ csv;

employee is the table name in this example..

Hope this helps.

If you don’t want to give permissions to Everyone, you can add permissions to the account that started the service. In the Control Panel — Administrative Tools — Services, copy the account name in the ‘Log On’ tab. (On my system the account is called ‘Network Service’.) Then share the folder with the CSV-file with this user as shown in the answer above.

To solve this problem you must give permission to the CSV file because that CSV file present in a COPY command are read directly by the server, but not client application. So to make this file accessible to a server we must give full read-write permission so that Postgresql user can read and write on that file.

Reference: article showing step by step procedure.

I just ran into this error and even after adding postgres to permissions on the file folder and the file itself, it still didn’t work. So, I put the file in a public folder. On Windows this was the path: «C:\Users\Public\Documents\census.csv.» It worked!

Responses to this problem on different threads go something like this 1. «Tell me exactly what command you used» 2. «Make sure you have right permissions» 3. «Just use /copy»

I just tried giving permissions to Everyone on the cvs file I am trying to copy from, and it is still giving me the permission denied error. I think this functionality is broken and has been broken for multiple consecutive releases over multiple consecutive versions of Windows.

for me and I’ve just spent some long hours on this. I have a central db residing on a HP box running 14.04 postgresql-9.5 pgAdmin3 postgis-2.2, shares are made through a tweeked Samba share. My clients are using a mixture of windows 10.1, 7, 8.1 and I have one ubuntu 14.04 desktop.

I’m working with large tables updating records and normalising data and have built the routines around SQL copy statements from CSV files which were made from the core COPY public.table_1 TO (the share folder I’d set up in Samba https://www.youtube.com/watch?v=ndAYZ0DJ-U4) ‘/srv/samba/share/[filename].csv’

I can then update the database once the tables have been amended with COPY table_1 from ‘/srv/samba/share/test.csv’ USING DELIMITERS ‘,’ WITH NULL AS » CSV HEADER; from any of my clients.

The key as far as I have been able to determine is that the clients doing the updating must be superusers, also everything must tie up in terms of users as there are 4 servers working together here Postgresql, Samba, UNIX and WINS All of my users are registered on each of the servers with the same username and password homogeneity is the main factor.

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