LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-15-2020, 03:54 PM   #1
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Rep: Reputation: 12
failed to open stream: Permission denied


Hi,

I keep getting the subject message while trying to open a file. I have changed all the permissions to 777 on the directory which will contain the new file . Don't know where to go from here to fix this.

Code:
<?php

error_reporting (E_ALL ^ E_NOTICE);
include("../myPhpFunctions.inc");

if(isset($_POST['submit_row']))  {
 $host="localhost";
 $username="rick";
 $password="";
 $databasename="optumRx.db";
 
 $id=$_POST['Id'];
 $acctfor=$_POST['AcctFor'];
 $invdate=$_POST['InvDate'];
 $orderno=$_POST['OrderNo'];
 $drugno=$_POST['DrugNo'];
 $description=$_POST['Description'];
 $cost=$_POST['Cost'];
 $refills=$_POST['ReFills'];
 
$inputFile= fopen("optumRxInputFile.sql", "a+") or die("Unable to open file!");

for($i=0;$i<count($invdate);$i++)  {

	 if($acctfor[$i]='Enter AcctFor') $acctfor[$i]='p';  // default value
 	if($refills[$i]="Enter ReFills") $refills[$i]=0;          // default value
 	 
   	$str = "insert into rxdata values('".$acctfor[$i]."','".$invdate[$i]."','".$orderno[$i]
      ."','".$drugno[$i]."','".$description[$i]."',".$cost[$i].",".$refills[$i].")"; 
      
	echo $str."</br>"; 
       
 	  fwrite($inputFile, $str);
 
 } // for
 
fclose($inputFile);
 
} // isset
?>

I created a test file that works ! It appears that this happens only when you try to run 'action' program on the <form>.

Code:
<?php

error_reporting (E_ALL ^ E_NOTICE);
include("../myPhpFunctions.inc");

$inputFile= fopen("optumRxInputFile.sql", "a+") or die("Unable to open file!");


   $str = "insert into rxdata values()"; 
      
 	     echo $str."\n"; 
       
   fwrite($inputFile, $str);

  
 
fclose($inputFile);
 

?>
Don't know where to go here to fix this.
 
Old 02-15-2020, 05:19 PM   #2
boughtonp
Senior Member
 
Registered: Feb 2007
Location: UK
Distribution: Debian
Posts: 3,597

Rep: Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545Reputation: 2545
Are you saying your first code block fails with the error "failed to open stream: Permission denied" but your second code block works as expected?

Actually, looking at what you're doing... you're writing SQL queries to a file?!

1) Why are you not just executing the queries directly in PHP?

2) Your queries are vulnerable to SQL injection attacks.

3) If you're trying to build some kind of online store, there are numerous existing working solutions.

 
Old 02-16-2020, 08:44 AM   #3
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,856
Blog Entries: 1

Rep: Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869
@OP You should do some debugging, getuid, getgid, getcwd and alike. Here's an example-script:
Code:
<?php
    function printfilestat ($fname) {
        $st= stat ($fname);
        if (! $st) {
            printf ("\n%s: 'stat' failed\n", $fname);
            return;
        }
        $userdata= posix_getpwuid ($st['uid']);
        $groupdata= posix_getgrgid ($st['gid']);
        printf ("file '%s': owner=%d(%s) group=%d(%s) access=%o\n",
            $fname,
            $st['uid'], $userdata['name'],
            $st['gid'], $groupdata['name'],
            $st['mode']);
    }

    printf ("<PRE>\n");
    $uid= posix_getuid ();
    $userdata= posix_getpwuid ($uid);
    $gid= posix_getgid ();
    $groupdata= posix_getgrgid ($gid);
    $cwd= posix_getcwd ();

    printf ("posix_pwuid=%d(%s) posix_getgid=%d(%s)\n",
        $uid, $userdata['name'],
        $gid, $groupdata['name']);
    printf ("posix_getcwd=%s\n", $cwd);

    printfilestat ($cwd);
    printfilestat (__FILE__);
    printfilestat (dirname (__FILE__));

    printf ("</PRE>\n");
?>
example output:
Code:
posix_pwuid=33(www-data) posix_getgid=33(www-data)
posix_getcwd=/local/home/projects/public_html
file '/local/home/projects/public_html': owner=1000(projects) group=1000(devel) access=40755
file '/local/home/projects/phptest/web/access.php': owner=1000(projects) group=1000(devel) access=100755
file '/local/home/projects/phptest/web': owner=1000(projects) group=1000(devel) access=40755

Last edited by NevemTeve; 02-16-2020 at 09:52 AM.
 
Old 02-16-2020, 10:55 AM   #4
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Quote:
Are you saying your first code block fails with the error "failed to open stream: Permission denied" but your second code block works as expected?
Yes, 'fopen()' does not work in Browser! DOES work from command line!
Quote:
Actually, looking at what you're doing... you're writing SQL queries to a file?!
Yes
Quote:
1) Why are you not just executing the queries directly in PHP?
Building file to import into Sqlite3.
Quote:
2) Your queries are vulnerable to SQL injection attacks.
Nobody will see this code but me.
Quote:
3) If you're trying to build some kind of online store, there are numerous existing working solutions.
See 1.
 
Old 02-16-2020, 01:51 PM   #5
michaelk
Moderator
 
Registered: Aug 2002
Posts: 25,678

Rep: Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892Reputation: 5892
The user that runs the apache process does not have write permissions to the document root directory. That is why it works from the command line.

What directory did you change to 777?

Last edited by michaelk; 02-16-2020 at 01:53 PM.
 
1 members found this post helpful.
Old 02-16-2020, 02:58 PM   #6
smallpond
Senior Member
 
Registered: Feb 2011
Location: Massachusetts, USA
Distribution: Fedora
Posts: 4,138

Rep: Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263Reputation: 1263
There is no path on the filename so it will try to append or create it in the current directory of the running process. This is probably not what you want. If your root is "/var/www" then create a directory "/var/www/tmp" with write permission to the apache user and open tthe file "/tmp/optumRxInputFile.sql"
 
Old 02-17-2020, 12:51 PM   #7
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
I'm running this from a virtual host. Maybe that makes a difference?

Code:
<VirtualHost *:80>

	ServerName mysqlite.com
	ServerAlias www.mysqlite.com
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html/DB-sql
	
	<Directory /var/www/html/DB-sql >
	
	Options Indexes FollowSymLinks
	Require all granted
	
	</Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined


</VirtualHost>
Here are some permissions that I have:

rick@rick-Latitude-E6510:/var/www/html$ ll
total 24

drwxr-xr-x 2 root root 4096 Dec 7 10:55 ./
drwxr-xr-x 3 root root 4096 Jul 17 2019 ../
lrwxrwxrwx 1 root root 17 Dec 7 10:55 DB-sql -> /home/rick/DB-sql/
lrwxrwxrwx 1 root root 17 Jul 18 2019 DB-Web -> /home/rick/DB-Web/


rick@rick-Latitude-E6510:~/DB-sql/PHP-Forms2$ ll
total 192

-rwxrwxrwx 1 rick rick 2364 Feb 15 11:32 optumRxForm.html~*
-rwxrwxrwx 1 rick rick 1675 Feb 17 11:00 test.php*
 
Old 02-17-2020, 01:26 PM   #8
scasey
LQ Veteran
 
Registered: Feb 2013
Location: Tucson, AZ, USA
Distribution: CentOS 7.9.2009
Posts: 5,725

Rep: Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211
What smallpond said.
Your code will try to create a file in /var/www/html/DB-sql -- all files are relative to the defined DocumentRoot in the VirtualHost container. Where do you want the file to go? Set the path in your script.

In order for a web application to create a file, the web user (www-data?) must have write access to the file* I usually do that by creating a sub-directory owned by the web user with 755 permissions and putting the path on the file name in the code. I then suppress DirectoryIndex on that directory and don't put an index.html there so that it can't be accessed with a browser.

*Putting 777 permissions on any directory, let alone a web accessable one, is a really bad idea! As you've seen, it didn't solve your problem (because you didn't do it on the directory your code was writing to). If all you're going to use DB-sql for, chown it to the web user and set the perms to 755, then add the path to the filename.
 
Old 02-17-2020, 01:30 PM   #9
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
Code:
rick@rick-Latitude-E6510:~/DB-sql/PHP-Forms2$ ll
total 192

-rwxrwxrwx  1 rick rick  2364 Feb 15 11:32 optumRxForm.html~*
-rwxrwxrwx  1 rick rick  1675 Feb 17 11:00 test.php*
Your user and group are rick, the web server has no permissions in that path.

One way to deal with that would be to add rick to the web server group and make the owner:group of that path rick:www-data (example is www-data, may be apache or something else, check your system).

Also note that even though you have very inadvisedly set the permissions to 777 on that path, the file optumRxInputFile.sql does not exist. If you create the empty file then the web server should be able to write to it even now.

And please, NEVER, EVER revert to setting 777 permissions, even if you are the only user on that machine - it is among the worst of the bad habits you can form working with a web server - unlearn it now and do things right!
 
1 members found this post helpful.
Old 02-17-2020, 08:06 PM   #10
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Quote:
One way to deal with that would be to add rick to the web server group and make the owner:group of that path rick:www-data (example is www-data, may be apache or something else, check your system).
Since I almost never deal with users and groups how do I do this???
 
Old 02-17-2020, 10:42 PM   #11
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
For your existing user, assuming you do not want everything in their home directory to belong to the web server group...

Code:
usermod -a -G web-group login-name
chown -R login-name:web-group /path/to/vhost/directory
On the other hand, if you want the default group for the user to be the web-group so that everything now and future in their home directory will belong to the web-group by default...

Code:
usermod -g web-group login-name
That will set the web-group as the default for that user and every file in their home directory will belong to the web-group.

In the above examples web-group will be the name of the group the web server runs under on your system, and login-name will be the user name, rick in your examples.

Assuming that "rick" has things in his home directory which he does not want to be accessible by the web server, I would suggest creating a new user just for the purpose of owning the vhost path, and make that user's default group be the web-group. Then, when you want to work on the web code, log in as that user and keep the web server out of your own home directory.

Last edited by astrogeek; 02-17-2020 at 10:47 PM.
 
Old 02-18-2020, 10:48 AM   #12
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Thanks astrogeek,

I'll give this a try.
I find all this very puzzling in that it is only fopen() that seems to behave this way I have many other scripts that behave 'normally'.

R
 
Old 02-18-2020, 11:07 AM   #13
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
Quote:
Originally Posted by pizzipie View Post
Thanks astrogeek,

I'll give this a try.
I find all this very puzzling in that it is only fopen() that seems to behave this way I have many other scripts that behave 'normally'.

R
Well, it is only fopen() because only fopen() is trying to open the file for writing which bumps into the permissions barrier, as it should.

Normally, those permission barriers are the core of the idea of separation of privileges, not allowing a single user to access or do absolutely anything on the system, which is the reason Unix/Linux is fundamentally more secure than others in many ways.

"Normally" is when you understand how and why those permissions work a certain way and use that for your advantage instead of fighting against them.

You are getting there!
 
Old 02-18-2020, 01:47 PM   #14
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
This is totally frustrating.

I have another Virtual Host mydb.com (DB-Web). I copied the scripts from mysqlite.com(DB-sql) which is the problem child to a directory in DB-Web and the scripts run fine. The only difference that I can find in all the directories and files is in the permissions of directories DB-Web and DB-sql.

Quote:
drwxrwxrwx 10 rick rick 4096 Feb 18 09:51 DB-sql/
drwxr-sr-x 36 rick rick 4096 Feb 17 10:15 DB-Web/
I changed the permissions of dir DB-sql to drwxr-sr-x 10 rick rick 4096 Feb 18 09:51 DB-sql. Unfortunately this didn't work either.

R
 
Old 02-18-2020, 01:56 PM   #15
scasey
LQ Veteran
 
Registered: Feb 2013
Location: Tucson, AZ, USA
Distribution: CentOS 7.9.2009
Posts: 5,725

Rep: Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211Reputation: 2211
RepeatIng what I said in #7:
In order for a web application to create a file, the web user (www-data?) must have write access to the file* I usually do that by creating a sub-directory owned by the web user with 755 permissions and putting the path on the file name in the code. I then suppress DirectoryIndex on that directory and don't put an index.html there so that it can't be accessed with a browser.

There’s nothing wrong with what astrogeek is suggesting. My suggestion is another way that I’ve used successfully for a long time.
 
1 members found this post helpful.
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] Apache 2 Warning: Unknown: failed to open stream: Permission denied madsovenielsen Linux - Server 2 06-14-2010 11:04 AM
Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0 migabriel.84 Linux - Server 1 11-25-2009 03:36 PM
move_uploaded_file failed to open stream: Permission denied zawmn83 Linux - Server 3 05-04-2009 03:36 AM
udevd - rmdir(/dev/.udev/failed) failed: Permission denied pbhj Slackware 20 03-21-2008 10:46 AM
Failed to send mail : Write failed : Permission denied shawnbishop Linux - Software 1 03-27-2006 01:50 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:44 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration