Failed to open stream permission denied in php windows

TroL929

Перенес сайт на новый сервер и после этого отвалилась загрузка файлов. Код в общем стандартный и прежде прекрасно работал (Добавлять пока сюда его не буду)

Выдает «Warning: imagepng(images/upload/1090d639d14df68959c5a1ccb0e47556/logo.png): failed to open stream: Permission denied in /var/www/….»
Пути к файлам проверил. Даже права выставил на 777, но это не помогло. Есть предположение что временный файл пишется не корректно, но как проверить не знаю. Только var_dump($_FILES[«logo»]); но выдает он правильную информацию — и название и вес файла.

Прошу советы что можно еще проверить и какими способами можно проверить источники проблем?


  • Вопрос задан

  • 8301 просмотр

Есть подозрение, что imagepng() пытается писать в такое место, где у него нет прав.
Попробуйте вместо images/upload... указать абсолютный путь. Проверьте еще раз, есть ли права. И не только на корневую папку images, но и на вложенные.

Пригласить эксперта

Permission denied in /var/www/…. это права доступа !
если у вас на локальной машине это и как правило linux hosts то откройте права для чтения и записи

Перечень мер, если появилась ошибка «Не удалось открыть поток: отказано в доступе».
1. Узнайте код ошибки php. Для этого поместите этот код в начало файла php.
ini_set(‘error_reporting’, E_ALL);ini_set(‘display_errors’, 1);ini_set(‘display_startup_errors’, 1);
2. К папке должен быть доступ 777. Проверьте это.
3. Тег должен иметь атрибут enctype = «multipart/form-data» method = «post».
<form enctype="multipart/form-data" method="post">
4. Откройте и посмотрите массив $ _FILES на сервере.
print_r ($_FILES);
5. Откройте и посмотрите массив $ _FILES на клиенте.
file = document.getElementById(«get_avatar»).files[0];parts = file.name.split(‘.’);
var a = file.size;var b = parts.pop();var c = file.type;alert(a+b+c);
6. Проверьте права пользователя и группы пользователей на каталог.
cd /var/www/your_site/user
ls -l
Подробнее на profi.spage.me/php/check-file-input-on-php-and-jqu…
В вашем случае, проверьте права на директорию images/upload/1090d639d14df68959c5a1ccb0e47556, права должны быть 777 и проверьте права пользователя и группы пользователей на этот каталог.


  • Показать ещё
    Загружается…

08 окт. 2023, в 23:50

5000 руб./за проект

08 окт. 2023, в 21:59

1000 руб./в час

08 окт. 2023, в 20:00

10000 руб./за проект

Минуточку внимания

Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.

Fix PHP Permission Issues

19th June 2021
1 min read

Hmmm, that’s weird well actually everything was working in my system. When I deployed the application to production facing this weird issue. Ya, I know the feeling.

You can quickly overcome this kind of PHP issues in the following ways:

Solution 1 — Check proper permission

Solution 2 — Check the owner of the folder


Solution 1 — Check proper permission

When you want to write to the files with PHP scripts the file or folder path won’t be having proper write permissions. You can fix it with the following

chmod -R 777 file_or_folder_name

NOTE: Kindly check if 555 or 755 or 775 will work first


Solution 2 — Check the owner of the folder

Sometimes in all the project paths, you will encounter this kind of issue. Then check if the owner of the project is www-data or not.

If not then run the following command

sudo chown -R www-data:www-data /var/www/html

Here I have changed the owner group of html to www-data. Make sure to cross-verify your folder before changing the owner.


Author Image

AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing


I am trying to write a query to a file for debugging. The file is in database/execute.php. The file I want to write to is database/queries.php.

I am trying to use file_put_contents('queries.txt', $query)

But I am getting

file_put_contents(queries.txt) [function.file-put-contents]:
failed to open stream: Permission
denied

I have the queries.txt file chmod’d to 777, what could the issue be?

This question is related to
php
file-io
file-permissions

Try adjusting the directory permissions.

from a terminal, run chmod 777 database (from the directory that contains the database folder)

apache and nobody will have access to this directory if it is chmodd’ed correctly.

The other thing to do is echo «getcwd()». This will show you the current directory, and if this isn’t ‘/something…/database/’ then you’ll need to change ‘query.txt’ to the full path for your server.

The other option

is that you can make Apache (www-data), the owner of the folder

sudo chown -R www-data:www-data /var/www

that should make file_put_contents work now. But for more security you better also set the permissions like below

find /var/www -type d -print0 | xargs -0 chmod 0755 # folder
find /var/www -type f -print0 | xargs -0 chmod 0644 # files
  • change /var/www to the root folder of your php files

Realise this is pretty old now, but there’s no need to manually write queries to a file like this. MySQL has logging support built in, you just need to enable it within your dev environment.

Take a look at the documentation for the ‘general query log’:

http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Gathering info from this link stackoverflow-image save doesn’t work with chmod 777 and from user azerafati and Loek Bergman

if you were to look under /etc/apache/envvars file you will see something like:

export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data

Apache is run under the username ‘www-data’

‘0755’ means the file owner can read/write/execute but group and other users cannot write. so in ur terminal, cd to the folder containing your ‘images’ folder. then type:

find images -type d -exec chmod 0755 {} \;
find images -type f -exec chmod 0755 {} \;
sudo chown -R www-data:www-data images

you must change persmissions first before changing owner.
enter your password when prompted. this will make ‘www-data’ owner of the images folder.

your upload should now work.

I know that it is a very old question, but I wanted to add the good solution with some in depth explanation. You will have to execute two statements on Ubuntu like systems and then it works like a charm.

Permissions in Linux can be represented with three digits. The first digit defines the permission of the owner of the files. The second digit the permissions of a specific group of users. The third digit defines the permissions for all users who are not the owner nor member of the group.

The webserver is supposed to execute with an id that is a member of the group. The webserver should never run with the same id as the owner of the files and directories. In Ubuntu runs apache under the id www-data. That id should be a member of the group for whom the permissions are specified.

To give the directory in which you want to change the content of files the proper rights, execute the statement:

find %DIR% -type d -exec chmod 770 {} \;

.That would imply in the question of the OP that the permissions for the directory %ROOT%/database should be changed accordingly. It is therefor important not to have files within that directory that should never get changed, or removed. It is therefor best practice to create a separate directory for files whose content must be changed.

Reading permissions (4) for a directory means being able to collect all files and directories with their metadata within a directory. Write permissions (2) gives the permission to change the content of the directory. Implying adding and removing files, changing permissions etc.. Execution permission (1) means that you have the right to go into that directory. Without the latter is it impossible to go deeper into the directory. The webserver needs read, write and execute permissions when the content of a file should be changed. Therefor needs the group the digit 7.

The second statement is in the question of the OP:

find %DOCUMENT_ROOT%/database -type f -exec chmod 760 {} \;

Being able to read and write a document is required, but it is not required to execute the file. The 7 is given to the owner of the files, the 6 to the group. The webserver does not need to have the permission to execute the file in order to change its content. Those write permissions should only be given to files in that directory.

All other users should not be given any permission.

For directories that do not require to change its files are group permissions of 5 sufficient.
Documentation about permissions and some examples:

https://wiki.debian.org/Permissions

https://www.linux.com/learn/tutorials/309527-understanding-linux-file-permissions

http://www.linux.org/threads/file-permissions-chmod.4094/

Guys I had this problem for 1 month and did everything but couldn’t fix it, but now I know the solution.

I use a shared linux hosting, when my admin changed the php to 5.3 I got many error for the «file_put_contents» code. try to test my plan:

In your host create a file like mytest.php, and put this code in and save:

<?php        mail('Your-EMail','Email-Title','Email-Message');        ?>

Open the URL «www.your-domain.com/mytest.php» one time and then check your email. you should have an email from your host with the information you entered in mytest.php, check the sender name. if its from Nobody you have problem about «Permission Denied» because something not defined and if the sender name is like my id: [email protected] you dont have prob.

My admin changed the server and installed the host again I think and the problem got solved, tell your host administration what I told you and maybe they find the answer.

hope it helps you!

For anyone using Ubuntu and receiving this error when loading the page locally, but not on a web hosting service,

I just fixed this by opening up nautilus (sudo nautilus) and right click on the file you’re trying to open, click properties > Settings > and give read write to ‘everyone else’

If you are pulling from git from local to server, you will need to clear cache sometimes because of the view files it gets uploaded with it / or other cached files .

php artisan cache:clear

Sometimes it might just to the trick if your application was working before the git pull

had the same problem; my issue was selinux was set to enforcing.

I kept getting the «failed to open stream: Permission denied» error even after chmoding to 777 and making sure all parent folders had execute permissions for the apache user. Turns out my issue was that selinux was set to enforcing (I’m on centos7), this is a devbox so I turned it off.

this might help. It worked for me. try it in the terminal

setenforce 0

This can be resolved in resolved with the following steps :

1. $ php artisan cache:clear

2. $ sudo chmod -R 777 storage

3. $ composer dump-autoload

Hope it helps

Here the solution.
To copy an img from an URL.
this URL: http://url/img.jpg

$image_Url=file_get_contents('http://url/img.jpg');

create the desired path finish the name with .jpg

$file_destino_path="imagenes/my_image.jpg";

file_put_contents($file_destino_path, $image_Url)

There 2 way to resolve this issues

1. use chmod 777 path-to-your-directory.

if it does not work then

2. simply provide the complete path of your file query.txt.

Furthermore, as said in file_put_contents man page in php.net, beware of naming issues.

file_put_contents($dir."/file.txt", "hello");

may not work (even though it is correct on syntax), but

file_put_contents("$dir/file.txt", "hello");

works. I experienced this on different php installed servers.

This error message is indicating that the PHP script is trying to open a file using the fopen() function, but the script does not have the necessary permissions to access the file. The most common cause of this error is that the file or the directory containing the file has incorrect permissions set. To resolve this issue, you need to ensure that the file or directory has the correct permissions for the user or group that the PHP script is running as. This can typically be done by using chmod to set the correct permissions on the file or directory.

<?php

// Define the file path
$file = '/path/to/file.txt';

// Try to open the file for writing
$handle = fopen($file, 'w');

// Check if the file was successfully opened
if ($handle === false) {
    // Output the error message
    echo "Error: failed to open stream: Permission denied";
} else {
    // Output a success message
    echo "File was successfully opened for writing.";

    // Close the file handle
    fclose($handle);
}

?>

  • Remove From My Forums
  • Question

  • User1248075058 posted
    I’m a PHP newbie and I’m getting the following error when viewing a form that I created in PHP.

    PHP Warning:  require_once(C:\Sites\www\custom\templates): failed to open stream: Permission denied in C:\Sites\www\custom\templates\info_request.php on line 3
    PHP Fatal error:  require_once(): Failed opening required » (include_path=’.;c:\php\includes’) in C:\Sites\www\custom\templates\info_request.php on line 3

    I’m on a Windows 2008 Server R1 (64bit) running IIS 7 and PHP through Fast CGI and MySQL server 5.1. Except for this issue PHP is running fine on the server. I’m running PHPMyAdmin and a couple other PHP apps just fine. I confirmed that I have permissions set
    correctly (have even run php files at the directory and file level under full control to test)

    Appreciate any suggestions on how to troubleshoot this issue. Also, are you aware of any forums or community sites geared just for those running PHP under FastCG on IIS 7?

Answers

  • User-1405480850 posted

    Hi,

    The error means that php-cgi.exe doesn’t have appropriate permission. Please use process monitor and see which user is getting access denied for this process and give appropriate permission.

    Thanks,

    Don.

    • Marked as answer by

      Tuesday, September 28, 2021 12:00 AM

  • Failed to mount windows share invalid argument
  • Failed to initialize battleye service windows test signing mode not supported как исправить
  • Facecam 315 драйвер для windows 10
  • Failed to initialize windows socket
  • Facecam 1320 драйвер windows 10