PHP - /tmp permission error - php

Basically, I have an .htaccess file, with php_value session.auto_start set to 1.
So my session will start in any file.
However, now I have a script in my /functions folder, but it gives an error about the permissions of the /tmp, resulting in "Failed to write session data", though it doesn't use, start or do anything with the session.
Yet this produces an error, and to me, it looks like it cannot find the /tmp folder, which I do have. Files directly in my root folder (/) don't have this a problem.
I also tried setting the permissions of /tmp to 777, to no avail.
Thanks in advance
The error I'm getting
Warning: Unknown: open(/tmp/sess_cfed7db100fd58b62eaca2a519ebaf7a, O_RDWR) failed: Permission denied (13) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
The script itself:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php'); //This file doesn't use any sessions as well
if(isset($_POST['signupemail'])){
$email = mysqli_real_escape_string($link, $_POST['signupemail']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));
if($thearray[0] > 0){
echo '"This emailaddress is already in use"';
exit;
}
echo "true";
} else if(isset($_POST['uname'])){
if(!preg_match('/^[a-zA-Z0-9_-]{3,16}$/ ',$_POST['uname'])){
echo '"<small>Please only use alphanumeric characters, underscores and hyphens</small>"';
exit;
}
$uname = mysqli_real_escape_string($link, $_POST['uname']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
$forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');
if(in_array(strtolower($_POST['uname']), $forbiddennames)) {
echo '"'.$_POST['uname'].' is a forbidden username"';
exit;
}
if($thearray[0] > 0){
echo '"This username is already in use, please choose another"';
exit;
}
echo "true";
}
?>
I get the error when I just browse manually to my script, so without any $_POST parameters set. I use this script to verify one's email and/or password, and when checking, it stops, not knowing what to do with the result (gotten by AJAX).

I think i remember some php.ini setting that prevents access to files that are not in the webserver's directory tree. I don't know if that applies to files that are generated internally by php, though.
If you're running on Red Hat Enterprise linux, or some derivative like CentOs or Scientific Linux, it might also be a problem with selinux. Check if the problem goes away if you set selinux to permissive (sudo setenforce Permissive). If that "fixes" the problem, think twice about leaving selinux in Permissive mode, especially if your server is reachable from the internet, better learn about selinux and relabeling.

Uhm, it turned out to be browser-related.
When I tested it in FireFox, no problem.
In Google Chrome, big problem.
I don't know what it was, but after deleting the cache, cookies, everything from my site, it worked perfectly. Seemed like it was searching for an old session.

Related

Can't upload files in Phabricator

This is on a private server. I have one outstanding issue from the install, my guess has been I need to fix that. It's the "Large File Storage Not Configured". However, I've changed all the parameters it asks for. I have:
nginx:
client_max_body_size 32
php.ini:
post_max_size = 32
memory_limit = -1 (disabled)
max_input_vars = 200000
upload_max_filesize = 32
I want it to use the default, to store things in MySQL, so I also have storage.mysql-engine.max-size at 8M.
But I also found this, that does not seem to be right:
PhabricatorChunkedFileStorageEngine writable: No
I have no idea how to change it though, or if I should.
The actual error message I get when I try to upload files (no matter what size) is:
Upload Failure
Exception: No configured storage engine can store this file. See "Configuring File Storage" in the documentation for information on configuring storage engines.
I got help from a Phacility staff member. It was just an error of mine, but they will update the documentation now to prevent more people from making that mistake - ´silverlining! :) https://secure.phabricator.com/D17037
I had storage.mysql-engine.max-size 8, as I thought that would give me 8MB. I've changed it to 8388608 now, which works, as it is supposed to be in bytes.
This might be helpful for anyone else.
In my case I am using, Engine: Local Disk, to store files but after configured it still gives error as mentioned below:
Unhandled Exception ("PhutilAggregateException")
All storage engines failed to write file:
- PhabricatorLocalDiskFileStorageEngine: CommandException: Command failed with error #1!
COMMAND
mkdir -p /var/files/64/66
STDOUT
(empty)
STDERR
mkdir: cannot create directory '/var/files/64': Permission denied
As the error states that permission is denied so I got it working by assigning user to the dir and updating permissions.
sudo chown -R ubuntu:ubuntu /var/files/
sudo chmod 777 /var/files/

Randomly arising "Permission denied" in php mkdir (windows)

I am wrestling with a problem. I stripped the example to this script that can be run as stand-alone application:
<?php
if(file_exists("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
mkdir("x");
If I call it repeatedly (F5 in browser) then sometimes this error occurs:
Deleting dir
Warning: mkdir(): Permission denied in F:\EclipseWorkspaces\Ramses\www\deploy\stripped_example.php on line 9
10-20 times it works OK and next time this error occurs. I googled more users has this problem but without solution.
https://github.com/getgrav/grav/issues/467
My example creates the directory in cwd, where anybody has full control. In addition the mkdir $mode parameter is ignored in windows. After the error the "x" directory truly not exists and in next attempt (F5) it is always created without error. I hopped later added "clearstatcache()" will help but nope.
In my full application I am using full file path. The deleted directory is not empty and I must clean it first. After successfull deleting the error occurs almost always.
My system is Windows 7, PHP 7.0.5, Apache 2.4
Windows doesn't let you delete things if another process is accessing them.
Check if your antivirus or some other process is opening the folder.
You can check this in resource monitor, from task manager.
Try the code with additional check on existing:
<?php
if(is_dir("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
if (!is_dir("x")) {
mkdir("x");
}
Had the same problem with Windows 10, Xampp and PHP 7. Problem was Kaspersky Internet Security, scanning and blocking the directory. Disabling KIS mkdir always works for me. Instead of directly recreating you can try rename, if disabling security software is not an option for you.
$time = time();
mkdir($path . $time);
rename($path . $time, $path);
juste delete espace name folder with Function Trim in php

Setting $_SESSION doesn't work on localhost using XAMPP

I set my session like so in my PHP code : $_SESSION['user_id'] = $login; and this seems to work fine whilst uploaded to my server and carries across different pages, however when I am testing the website on my local machine the session seems to become immediately unset after leaving the script where it is set.
I am testing on my local machine using XAMPP and exactly the same code.
I am not sure why this problem is occurring and would greatly appreciate any helpful answer.
Example that is not working:
$_SESSION['user_id'] = $login;
echo '<META HTTP-EQUIV="refresh" content="0;URL=../home.php">';
EDIT 1:
Here is my entire function in which I log in (it's part of the class):
public function loggingIn(){
session_start();
$db = new Database('localhost','root','','userdata');
$userFunctions = new Users($db);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if(empty($username) || empty($password)){
$this->errors['u&p'] = 'Please Enter Your Username AND Password';
$this->printE();
} elseif($userFunctions->user_exists($username)===false){
$this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
$this->printE();
} else {
$login = $userFunctions->login($username, $password);
if($login === false){
$this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
echo 'Login Failed!';
} else {
if(!$userFunctions->economyTableExistsForUser($login)){
$userFunctions->createEconomyTableForUser($login);
}
if(!$userFunctions->schoolTableExistsForUser($login)) {
$userFunctions->createSchoolTableForUser($login);
}
$_SESSION['user_id'] = $login;
echo $_SESSION['user_id']; // working fine
header('Location: ../home.php');
}
}
}
Let's guess that your home machine is not having:
session.autostart = On
in your php.ini, while your other machine obviously is.
Make sure that you have set in your PHP code:
session_start();
PHP: session_start - Manual
If you don't, then your session is not started, unless my first conjecture is true.
Besides, you must check for you PHP version on your localhost and settings in php.ini. Make sure that the directory where you store you session files is writeable and session files do really exist.
EDIT 1:
You better use PHP solution for redirection:
header("Location: /");
exit();
EDIT 2:
PHP has functions that modify HTTP headers. Some of them:
header
session_start
setcookie
EDIT 3:
Line-breaks and spaces could be a problem but there are also invisible character sequences which can cause Warning: Cannot modify header information, like the UTF-8 BOM (Byte-Order-Mark).
Try re-saving your file making sure that it's saved just as UTF-8 (no BOM).
EDIT 4:
To properly debug your code make sure that PHP displays all warning and notices. Run it before session start:
ini_set('display_errors', -1);
EDIT 5:
You must also check session.gc_maxlifetime setting:
session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.
EDIT 6:
To view white-spaces in Sublime Text, edit the settings:
// Set to "none" to turn off drawing white space, "selection" to draw only the
// white space within the selection, and "all" to draw all white space
"draw_white_space": "selection",
You can set it in Preferences->Settings Default. If you edit your user settings Preferences->Settings - User and add the line as per below:
{
"font_size": 10,
"draw_white_space": "all"
}
Also make sure it shows all other special characters to properly debug your code!
EDIT 7:
Finally try adding session_write_close(); right before redirecting.
EDIT 8:
Set in your PHP file, before session_start();, session.save_path = "/home/username/tmp"; directive.
Create tmp dir outside of public_html. Make sure that tmp dir has chmod 770 and created with the same user/group privileges . Run ls -lsa in your home dir to check if the new directory has the same user/group as other directories, like public_html for instance. If not, make sure changing permissions as root on tmp by running chown username:groupname /home/username/tmp.
A quick update on this. I found this response very useful, however, please note that in my installation of XAMPP, the php.ini entry for session.autostart=On, is slightly different. I found the following:
; Initialize session on request startup.
; http://php.net/session.auto-start
session.auto_start=0
I changed this to:
; Initialize session on request startup.
; http://php.net/session.auto-start
session.auto_start=1
Make sure session cookies are enabled in php.ini (xamp\php\php.ini).
session.use_cookies=1
In your php.ini check:
variables_order contains the letter S
Check that session.save_path exists and is writeable by the user under which PHP is running.
If you are using PHP embedded within .htm/.html documents, you need to ensure that Apache can process them appropriately. This is done by editing the httpd.conf and adding the line
AddType application/x-httpd-php .html .htm
to the section <IfModule mime_module>
I was fighting with this problem but solve...
In your /opt/lampp/etc/php.ini try to change this line:
session.save_path = "/var/lib/php/session"
For this:
session.save_path = "/opt/lampp/var/session"
Note: Maybe you need to create the folder "session" in /opt/lampp/var
Open php.ini
change session.auto_start with "1"
"Stop" Apache if running
"Save" php.ini
"Start" Apache
Session Issue Fixed in Xampp 7.1.6 with following Changes in php.ini
Line #1403 set:
session.auto_start = 1
I had similar problems live site working Xampp not.
The trick in my case was to disable the two lines below.
header('Set-Cookie: same-site-cookie=huis; SameSite=Lax');
header('Set-Cookie: cross-site-cookie=stijl; SameSite=None; Secure');
So check anything that modifies something regarding coockies is my advise.
Please check your "session.cookie_path" in php ini. By default it is "session.cookie_path=/"
Enable session cookies in php.ini (C:\xamp\php\php.ini).
CHANGE
session.use_cookies=0
TO
session.use_cookies=1
AND remember to restart xampp

PHP File_put_contents not working

Check this code:
<?php
$url = 'http://www.example.com/downloads/count.txt';
$hit_count = #file_get_contents($url);
$hit_count++;
#file_put_contents($url, $hit_count);
header('Location: wmwc.zip');
?>
#file_get_contents is working fine and the header location change to the downloaded file also works, but either the hit_count increase or #file_put_contents isn't working, because the number with the file doesnt increase by 1. I've set the file permission to 777, but when I try to set the directory permission to 777 also I get a 500 internal server error saying "The server encountered an unexpected condition which prevented it from fulfilling the request."
You can't write a remote file via http.(If you could do that, every one else could change that file also.)
You need to use the local path.
try changing directory properties
chown www-data:www-data <dirname>
and/or write as follows, if you host on linux
<?php
$var ="hi";
shell_exec('echo "'.$var.'">>log.txt');
?>

Getting around PHP safe mode to write to server. Is it possible?

I have got the following problem since the server has safe mode turned on, and directories are being created under different users:
I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.
New directory is created, but it belongs to 'apache' user.
'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.
Now I have a problem!
One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.
But I have to ask. Is there a programatical solution for my problem?
I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.
I've used this workaround:
instead of php mkdir you can create directories by FTP with proper rights.
function FtpMkdir($path, $newDir) {
$path = 'mainwebsite_html/'.$path;
$server='ftp.myserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "user#myserver.com";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
You might be able to turn safe mode off for a specific directory via a .htaccess file (if on Apache).
php_value safe_mode = Off
You might need to get your hosting provider to make this change for you though in the httpd.conf.
I have had some success with setting the group bit of the upload directory to sticky.
PHP can then create directories inside it and write to it.
http://en.wikipedia.org/wiki/Setuid#setuid_and_setgid_on_directories
chmod g+s directory

Categories