Php file puts content permission denied in

File_put_contents Failed to open stream Permission denied in

Больно не пинайте — поиском пользовался, гуглом тоже, даже с хостером решали проблему. но проблема не исчезла:

Есть генератор текста (бессмысленного):
— генерится текст
— кладется в переменную $text
— далее из файла links.txt берутся 3 первые строки, выводятся после текста и удаляются

Кусок кода, который выводит ссылки после текста:

1 2 3 4 5 6 7 8 9 10 11 12
$row_number0 = 0; $row_number1 = 1; $row_number2 = 2; $links = file("links.txt"); echo "$text"; echo "$links[$row_number0]"; echo "$links[$row_number1]"; echo "$links[$row_number2]"; unset($links[$row_number0]); unset($links[$row_number1]); unset($links[$row_number2]); file_put_contents("/var/www/arthyrgrex/data/www/site.com/gen/links.txt", implode("", $links), LOCK_EX);

Ошибка в следующем:
В файле links.txt содержится примерно 25000 ссылок.
Когда я обращаюсь к генератору (обращаюсь каждую секунду), чтобы сгенерить текст и ссылки — в файл links.txt должно сохраниться на 3 ссылки меньше. Так происходит в большинстве случаев.
Но часто бывает так, что в файле было 24000 ссылок — я обратился к генератору, а обратно в файл сохранилось не 23997 ссылок, а 14000 или вообще 0 ссылок.
Т.е. каким-то боком теряется содержимое переменной $links .

В логах следующая ситуация:

PHP Warning: file_put_contents(links.txt): failed to open stream: Permission denied in /var/www/arthyrgrex/data/www/site.com/gen/gen.php on line 69
file_put_contents("/var/www/arthyrgrex/data/www/site.com/gen/links.txt", implode("", $links), LOCK_EX);
1. В функции file_put_contents использовать флаг LOCK_EX 2. Проверять содержимое переменной перед записью в файл, чтобы убедиться, что записывается не пустая переменная (например, используя функцию strlen()). 3. В файле /var/www/arthyrgrex/data/www/danissimo.tk/gen/gen.php перед строкой 69 добавить код, проверяющий не только переменную, но и наличие искомого файла по указанному адресу - if(is_file(адрес)){код}.

Права 777 и пользователя выставлял на /site.com/gen/links.txt (для файлов и папок).
Флаг LOCK_EX — использовал.

Но результат — тот же.
Либо пропадает большое количество ссылок, либо все сразу.
И такое происходит каждые 15 минут.

Огромная просьба подкинуть идей по решению данной проблемы!
Заранее благодарен

Источник

PHP: «failed to open stream: Permission denied»

The file or folder user does not have the permissions to write in the directory. 755 – This set of permission is commonly used in web server. To check permission, use the same command as for the owner check: You’ll see something like: Where «drwxr-xr-x» is access permission.

PHP: «failed to open stream: Permission denied»

move_uploaded_file(/var/www/php/Site/userData/radi/110729.png):failed to open stream: Permission denied in /var/www/php/Site/upload.php

move_uploaded_file(): unable to move ‘/tmp/phpUFvMcn’ to ‘/var/www/php/Site/userData/radi/110729.png’ in /var/www/php/Site/upload.php

And for ‘file_put_content()’ and ‘mkdir()’

  1. Check owners that runs PHP. To check — simply add these strings near your «file_put_contents» in your PHP file echo «current user: «.get_current_user(); echo «script was executed under user: «.exec(‘whoami’);
  2. If you see the difference between current user and «script user», then you’ve found the issue.
current user: root script was executed under user: www-data 

Just set the appropriate user to your php files directory/directory you want to write from your PHP script: In Linux terminal execute:

chown -R www-data:www-data /path/to/the/folder 

please, note, that «www-data» user is only for example. You should use your user you get from the «script was executed under user» output.

Читайте также:  Питон рандомное число из заданного диапазона

P.S: To check folder owner, you could use this linux command:

P.P.S: check if your folder has the right access permission: 755 The folder php files should have «644» access permission.

To check permission, use the same command as for the owner check:

drwxr-xr-x 10 www-data www-data 4096 Aug 5 15:18 api 

Where «drwxr-xr-x» is access permission. Google it, to get more info about.

Open http.conf (in /opt/lampp/etc/httpd.conf) file.

 # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User hostname Group hostname 
$_SERVER["DOCUMENT_ROOT"]."/myFolder/path to upload folder". 

From Laravel I got failed to open stream: Permission, If you cd into your app, you will probably see that some folders have the «www-data» user or group. If you are using Laravel Forge, to fix this, you want to change the user and group to «forge». Instead of cd’ing into every directory and running this on every file and folder, you can do this recursively with the -R flag.

Php/iis: failed to open stream: Permission denied

Warning: fopen(D:\inetpub\wwwroot\req2) [function.fopen]: failed to open stream: Permission denied in D:\inetpub\wwwroot\test.php on line 44 can’t open file

I gave «Full Control» permissions to IIS in the wwwroot directory. I had also tried the absolute path: $_SERVER[‘DOCUMENT_ROOT’].»\\req2″

but i still get the same error. I am running IIS 7 on Windows 7.

In Windows, you need to give user, IUSR the permission.

Right click folder —> Properties —> Security —> Edit —> allow Full Control —> apply —> do this for all, or just the correct user

Also, if you run into this with downloaded code, make sure that you have «unblocked» it to run locally.

File encryption must also be disabled.

Got this today on Windows 10 after I shared the wwwroot folder. Was working before that. Had to take the sharing off and reapply iis_iusr access permissions.

PHP Warning: ftp_get(): failed to open stream, 2. The second parameter of the ftp_get function specifies the local path where you want to download the remote file to. Previously you were downloading the file to /var/www/public_html/ where probably you don’t have permissions to create files.

File_put_contents — failed to open stream: Permission denied

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)

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?

Читайте также:  Web технологий html css xml

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.

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 

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’.

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.

Php copy function, failed to open stream: Permission, In your ftp client (or web-based file manager), you should be able to right-click on the folder and see an option for attributes or permissions. From there, 777 permission simply means that Owner, Group and …

Failed to open stream: Permission denied in /opt/lampp/htdocs

I am using Ubuntu 16.04 & xampp 5.6.30. I am trying to create a simple login program using file with validation but I am facing problem while putting my data into a file named «login.txt».

file_put_contents(login.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.php on line 38 
$input = $userName.'|'.$userPassword.'\n'; $myfile = file_put_contents('login.txt', $input.PHP_EOL , FILE_APPEND | LOCK_EX); 

This error is due to file permissions. The php/apache user does not have the permissions to write in the directory. One way of fixing that is to change the mod byte of the directory with the command chmod . You need super permissions to execute this modification if your session user does not own the directory.

$ sudo chmod -R 777 /path/to/directory 

The mod 777 set read/write and execution to directory for every users on the system. The R option applies recursively the modification to every files and sub-directories. So, you can change the permission of all the contents of your htdocs directory all at once.

Читайте также:  Свечение вокруг блока css

Permission errors can be solved using the following two methods.

Method 1:

Find web server user

Note: It will be daemon by default if you haven’t changed it.

In my case it’s daemon , replace it with yours in following command.
sudo chown -R daemon /opt/lampp/htdocs/[Working Project]/ 

As in Linux chown is used to change ownership of any folder or file. So this command gives ownership of that folder to the daemon user, which will enable the daemon user to have complete access to that folder and everything inside it too.

Method 2:

Give All permissions to that file.

The following command gives Read , Write and Execute permissions to User , Group and Owner . So User is you, who can also modify it, other programs such as text editors can also edit them, and so PHP too.

sudo chmod 777 /opt/lampp/htdocs/[Working Project]/File.txt 

Here permissions are provided using numeric number

  • 7 is for all permissions read , write and execute .
  • 6 is used for read and write .
  • 5 is used for read and execute .
  • 4 is used for read only.

The permissions are granted in ugo pattern.

Alternative command:
sudo chmod u+rwx,g+rwx,o+rwx /opt/lampp/htdocs/[Working Project]/File.txt 

Here it is more clear that which permissions you’re assigning to whom. so u stands for User, and is being assigned Read(r), Write(w) and Execute(e) permissions, similarly g is for Group, and o is Other.

Advice:

Method 2 is not suitable for most of the scenarios. I recommend using the First Method because method 2 will only give read, write and execute permissions to a file where the file must be created by you manually first. What if you wanted php to create the file according to your logic in the website. In that case this method will not work. if daemon will be the owner, it can do that only.

This error is due to file permissions. The file or folder user does not have the permissions to write in the directory.

$ sudo chmod -R 755 /directory 

755 – This set of permission is commonly used in web server. The owner has all the permissions to read, write and execute. Everyone else can only read and execute, but cannot make changes to the file.

You can run the command below in a terminal to give the htdocs folder and all of it’s contents all permissions (read/write/execute for all users). Note that this is not safe in any way, especially in production!

$ sudo chmod -R 777 /opt/lampp/htdocs/ 

File_get_contents(): failed to open stream: Permission, The first column will be the owner typically it will be nobody. 2.Change the owner of images and tmp_file_upload to be become nobody or whatever the owner you found in step 1. 3.Chmod images and tmp_file_upload now to be writable by the owner, if needed [Seems you already have this in place].

Источник

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