- php copy function, failed to open stream: Permission denied
- PHP: mkdir, почему permission denied при 0777?
- PHP apache image upload getting error Permission denied in [closed]
- SELinux influences «failed to open stream: Permission denied” PHP error
- How do I save php file in var/www/html when it shows error «Permission denied»? [duplicate]
- 2 Answers 2
php copy function, failed to open stream: Permission denied
I am trying to upload image on server, below is script that I found on Internet and in worked locally, when I deployed code and database is gives me «failed to open stream: Permission denied» error.
$l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; > //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) < //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) < //print error message echo 'Nepoznata vrsta fajla!
'; $errors=1; > else < //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size >MAX_SIZE*1024) < echo 'To large file!
'; $errors=1; > //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="Content/Images/".$image_name; //we verify if the image has been uploaded, and print error instead //$copied = copy($_FILES['image']['tmp_name'], $newname); $copied = copy('$_FILES['image']['tmp_name'], $newname); //echo $_FILES['image']['tmp_name'].'
'; //echo $_FILES['image']['name']; if (!$copied) < echo 'Error occurred!
'; $errors=1; >>> //If no errors registred, print the success message /*if(isset($_POST['Submit']) && !$errors) < echo "You have successfully uploaded image.
"; >*/ ?>
I saw some answerers from stackoverflow like answers1 and answer2 but I am not sure how to do that? Is there any other suggestion? thanks.
PHP: mkdir, почему permission denied при 0777?
В этой ошибке указано, что php скрипт, расположенный тут:
/var/www/www-root/data/www/xndaasdqfjqwm7b.xn--p1ai/vendor/yiisoft/yii2/helpers/BaseFileHelper.php
видимо пытается создать папку ( mkdir() line 488)
Так какой именно папке вы права задаете?
Посмотрите в коде/логах, какую папку он пытается создать и где и вот там уже и назначайте права.
в 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 ;).
PHP apache image upload getting error Permission denied in [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
- Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
- This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
I have redhat 8 and install LAMP; all things are working, but when I want to upload images through PHP script below:
else < echo "File is not an image."; $uploadOk = 0; >> // Check if file already exists if (file_exists($target_file)) < echo "Sorry, file already exists."; $uploadOk = 0; >// Check file size if ($_FILES["fileToUpload"]["size"] > 500000) < echo "Sorry, your file is too large."; $uploadOk = 0; >// Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) < echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; >// Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) < echo "Sorry, your file was not uploaded."; >else < // if everything is ok, try to upload file if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) < echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; >else < echo "Sorry, there was an error uploading your file."; >> ?>
File is an image — image/png. Warning: move_uploaded_file(/imageslogo_white.png): failed to open stream: Permission denied in /var/www/html/apinew/upload.php on line 42
Warning: move_uploaded_file(): Unable to move ‘/tmp/phpPVJeWk’ to ‘/imageslogo_white.png’ in /var/www/html/apinew/upload.php on line 42 Sorry, there was an error uploading your file.
http://3.122.192.102/apinew/index.php
drwxrwxrwx. 3 apache apache 55 Oct 24 08:52 apinew drwxrwxrwx. 2 apache apache 6 Oct 24 11:05 images -rwxrwxrwx. 1 apache apache 288 Oct 24 10:27 index.php -rwxrwxrwx. 1 apache apache 1713 Oct 24 13:13 upload.php
SELinux influences «failed to open stream: Permission denied” PHP error
Yesterday I’ve spent 5 hours straight discovering a seemingly unreasonable error «failed to open stream. permission denied», which was occuring after any operations of writing to file system: fopen (with «w» and «a» flags), move_uploaded_file, file_put_contents. I’ve rechecked many times directories owner (user and group — chown, chgrp), have change folder attributes to unsecure 777 (rwx with chmod ), but it has no effect. I even reinstalled an Apache and PHP, but still was facing the same error. As it is appeared after hours of reading various documentation the origin of error was SELinux restrictions automatically applied for Apache service httpd. I’ve simply turned off the SELinux by editing /etc/selinux/config file on my Fedora (release 20) via changing line:
- (practical) How can I grant Apache httpd service write-delete-update permissions on directory without totally disabling SELinux?
- (theoretical) What is the SELinux? What it is intended for? Why (for what reason) it was created? Why should I use it? Is there a reason to keep SElinux enabled on local dev machine?
solely to moderators of the resource: I know that this issue covers more administrating than actual programming, but I’m sure it affects developers in much more severe way than say novice administrators, so choosing between SuperUser and StackOverflow I took the latter. However it is up to you whether to move the question at SuperUser or keep at this place.
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.
- Open Terminal
- type sudo nautilus hit enter
- Navigate to the target file or folder you want to change permissions (/var/www)
- Right click the file or folder (html folder)
- Select Properties
- Click on the Permissions tab
- Click on the Access files in the Others section
- Select “Create and delete files”
- Click Change Permissions for Enclosed Files
- In the resulting window, Select Read and Write under Files and Create and delete files under Folders
- Click Change
- 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.