# How to read a user's /var/mail/ file with PHP



## Anonymous (Jan 5, 2010)

I already tried to ask this in the php forums but got no response so I figured someone would know the answer here.
I am trying to write a script that takes a username (corresponding with a user on the server) and then reads the appropriate /var/mail file for that user and prints it.

I've already tried something like

```
1.  
   2. <?php
   3. $username = $_POST["username"];
   4. $output = shell_exec("cat /var/mail/$username");
   5. echo $output;
   6. ?>
   7.
```
but it returns a blank page with only a "4" printed.
I am not sure if the problem is the code, permissions, or what.
Thanks.


----------



## J65nko (Jan 5, 2010)

'/usr/mail/$username" ? Didn't you say the mail was in "/var/mail/"?


```
$ ls -l /var/mail
total 400
-rw-------  1 j65nko  j65nko  152201 Jan  5 01:30 j65nko
-rw-------  1 robert  robert   49947 Dec 25 03:21 robert
```

You need to find a way to handle the permission issue


```
j65nko@hercules[~]cat /var/mail/robert
cat: /var/mail/robert: Permission denied
```


----------



## Anonymous (Jan 5, 2010)

Do php scripts run as the "www" users permissions by default? Would it be dangerous to try setting the setuid bit in order for the script to run as root?


----------



## SirDice (Jan 5, 2010)

mharvey87 said:
			
		

> Would it be dangerous to try setting the setuid bit in order for the script to run as root?



You can but it won't work. You will also set yourself up to get pw3d big time. Running web scripts as root is a serious no-no.


----------



## dennylin93 (Jan 5, 2010)

Why not try other solutions such as IMAP or webmail (Dovecot and Roundcube are quite good)?

A crude but perhaps more secure method is available by using sudo for the script. Something like `$ sudo cat foo`.


----------



## Alt (Jan 5, 2010)

Then someone call it like this
`wget --post-data=username=../../etc/master.passwd 'http:/blabla.com/im-teh-php-programmer.php'`


----------



## Anonymous (Jan 6, 2010)

Thanks for the heads up on the security issue, I would have overlooked that. 
I thought about using sudo but I'd like to figure out a way where I could run a script from the php script above that would read the user's mail file by running as the user that is provided by "username", this way the required privileges would be minimal. Does anyone know how this could be done?


----------



## dennylin93 (Jan 7, 2010)

Is there any reason why you don't want to use webmail/IMAP? It seems like the best solution in my opinion.


----------

