Catch session creation error in PHP - php

I wanted to be able to catch the error in session creation in PHP. My primary target is to be able to know which causes the problem. Is it because we don't have wrtie access to the folder where the session is written or because we don't have free disk space already.
So of course we will start with this.
session_start();
and from this post Check if session is set or not, and if not create one? I did try to add
if(session_id() == '')
{
// session has NOT been started
session_start();
echo "Session is started";
}
else
{
// session has been started
}
And to test this I have remove writing permissions for the group and others in /tmp/ by using this command
chmod 755 tmp/
But base on my test I still see that the session is started. And the funny thing is I can login but when I try to logout I can't.
Any insights on how to properly get the reason on session creation error would be greatly appreaciated. Thanks!
EDIT:
I have tried Frederik's suggestion and done this.
try{
// Start session
session_start();
echo "Session started. " . session_id();
}catch(Exception $e){
echo "Session not started. " . $e->getMessage();
}
But I still see this
Session started. fa505cbf4b232773669008495fd08b9f
even if I have remove write permission to /tmp already. It seems that the try catch was not able to properly catch the problem.

You might want to try the is_writable function.
Something like:
<?php
$dirname = '/tmp';
if (is_writable($dirname)) {
echo 'The folder is writable';
} else {
echo 'The folder is not writable';
}
?>
You can use it with files or folders.
More information: http://id1.php.net/is_writable

With Frederik's suggestion to check if the /tmp do have write permission I was able to decide to just check for write permission and disk space before checking for username and password. So I wrote this code
if (is_writable(session_save_path())){
if ( $diskfree is <= 0){
// check for authentication here
}else{
header("Location: login.php?error=true&nodisk=true");
return;
}
}else {
header("Location: login.php?error=true&nowrite=true");
return;
}
and then in login.php I have this to catch the error code.
// If we have an error show error message
if ( isset($_GET["error"]) && $_GET["error"] ) {
//If not enough disk space show disk space message
if( isset($_GET["nodisk"]) && $_GET["nodisk"] ){
alert("disk free problem");
}
//If we don't have permission to session save path show session creation error
if( isset($_GET["nowrite"]) && $_GET["nowrite"] ){
alert("write permission error");
}

Related

Validate admin is logged in php

I have a php script that generates an RSS feed, but I only want it to be accessible by admins. I currently use this method
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
}
It works on other pages but for some reason it not working here.
I want it the page to, validate the user is an admin ($_SESSION['isAdmin] == true), execute the script updating the RSS file, the redirect back to the regular admin page.
Here is a basic skeleton of the page. I removed all the stuff that doesn't matter
<?php
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
}
$file = fopen('rss.xml', "w") or die("Unable to open file");
try {
// Connect to db
$conn = new PDO("mysql:host=" . SERVERNAME . ";" . "dbname=" . DBNAME, USERNAME, PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $conn->query('SELECT * FROM * ORDER BY upload_date DESC ');
$result = $query->fetchAll(PDO::FETCH_OBJ);
$rssfeed = 'This gets set based on what the db returns';
} catch (PDOException $e) {
echo $e->getMessage();
}
fwrite($file, $rssfeed);
fclose($file);
header("Location: /admin.php");
In my testing, when I'm not logged in, it still executes the script (generating the rss.xml file), then redirects me back to the admin page. Which I'm not logged in so that redirects me back to / with the error saying I'm not allowed to access admin.php
You need to exit after sending the Location header.
The header function just adds a header to the result that will be sent eventually. As you don't exit, all the code that follows is still executed, and the output from that code is sent to the client, together with the Location header.
Add exit() to the end of the location header redirect. This will prevent the code after that from being executed.
<?php
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
exit(); // It will stop here.
}
// The rest of the code
.........
After reading the comments I realized I never started the session with session_start();🤦
However I also added exit(); to the end of the redirect because that seems like good practice I guess.
Still learning a lot about php so any advice you guys give me is much appreciated. Thanks for the help!!

My PHP code not creating a directory

<?php
error_reporting(0);
$title='New Account'; /*This is a page that creates new account*/
include('header.php'); /*header file included*/
extract($_POST);
if(isset($r9)) /*$r9 is submit */
{
if(!empty($r1) && !empty($r2) && !empty($r3) && !empty($r4) && !empty($r5) && !empty($r6) && !empty($r7) && !empty($r8) )
{
if(is_dir("user/$r3")) //$r3 is the email the person is providing
{
echo "User already registered";
}
else
{
mkdir("user/$r3"); /*directory creation*/
file_put_contents("user/$r3/details.txt","$r1\n$r2\n$r4\n$r5\n$r6\n$r7\n$r8");
header("location:welcome.php"); /*the next page it must go after this*/
}
}
}
?>
This is my PHP code and it is not creating the directory. Please help me out.
Please turn on the error reporting to see the error messages, that will help you to solve this problem. Please check if your web server has permissions to creating a new directory. If your web server has the permissions already to write in the folder user then try to edit the following code:
mkdir("user/$r3");
to
mkdir("/THE_HOLE_URL_TO_THIS_FOLDER/user/$r3");
for example mkdir("/opt/lampp/htdocs/myhomespace/user/$r3");

PHP IF Statement Problems With isset & !empty

I am just stuck today at a wall of confusion and I'm hoping someone will be able to assist :)
I have a database full of basic projects, and within that table are attributes like Project Name, Project Number, Project Image, etc. I am able to enter new projects / display existing projects / etc. without issue.
My problem seems to come up when I want to Edit a project. My thoughts were that I would have to create an IF statement to find out if there's a new file uploaded or not, and either set the new file name in the database if there is, or keep the old in the database if there isn't.
I've been playing around with this for days, and I think I started off a bit too far ahead of myself. I've started breaking down to basics and I'm getting stumped with my IF statement, it feels like it's backwards? Does this make sense?
Examples:
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($OldProjectImage1)){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
Now in searching StackExchange I found that we have to do the statement on the COOKIE portion instead of the Variable as I did above, but it also similarly fails.
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(!empty($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
And I've also tried with isset
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
I've tried both with my script, and they're both behaving similarly. Perhaps I am just confused at the overall process?
When I run my tests with and without cookies enabled, it always seems to skip the first part of the IF statement (with both isset and !empty) and jump to the next section. Then, similarly, it feels like the IF statement is backwards (if that makes any sense) - if I set a file to upload which populates ProjectImage1, I get "Image1 FILES empty". If I set no file to upload and submit the form, I get "Image1 FILES isset".
I thought it would essentially be, in plain English,
If cookie is empty then echo "Your Browser Cookies are not enabled"
Else if ProjectImage1 Name is set, echo "Image1 FILES isset"
Else if ProjectImage1 Name is Empty, echo "Image1 FILES empty"
but it's feeling to me like it's backwards? Am I understanding this wrong?
Thanks in advanced for any responses!
Problem lays with:
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
}
You check if the cookie exist, and if it does, then you say that cookies are not enabled. A bit weird. Add ! before the isset. Then the if-statement and the text are correct.
I think, but I can only assume, you want this in the end:
if (isset($_COOKIE["OldProjectImage1"])){
// I believe the variable below can also be put between the else { and } down below
$OldProjectImage1 = $_COOKIE["OldProjectImage1"];
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is not set';
} else if(empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is empty';
}else {
// upload file here
}
I think you want to check the browser cookie is enabled or not?
Detect if cookies are enabled in PHP
Answer by Shiplu Mokaddim:
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
Detect cookie in Javascript
Check if cookies are enabled
So, combine with your code and my own explanation:
<?php
session_start();
//check if a cookie test is started
if (isset($_GET['check']) && $_GET['check'] == true) {
//cookie test is started
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//cookie test success, go back to the previous page
header("location: {$_SESSION['page']}");
} else {
//cookie test fail, echo the message and continue
echo 'Your Browser Cookies are not enabled';
}
} else {
//start cookie test if a cookie test wasn't done
//check if a cookie test was done.
if (!isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//start a cookie test if a cookie test wasn't done
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
setcookie('foo', 'bar', time() + 3600);
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo "OldProjectImage1 doesn't exists in cookies.";
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is not set";
} else if(empty($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is empty";
}
?>

Not able to create new directory with variable (PHP)

Hello I'm trying to create a directory in the users/ folder. When the user registers a vpb_save_details.php is being opened. And mkdir is ran to create a user with the username as directory name.
The user is being registered as normal but the problem that no directory is created, not even the /user directory.
If i run this code:
<?php
mkdir("blah", 0777);
?>
The directory bla is created, but if I run my code vpb_save_details.php, nothing happens.
This is a part of the code:
//If the user is validated and every thing is alright, then save the user details and display success message to the user
//otherwise, display error message to the user
if ($vpb_error == '')
{
//Encrypt user information with Base64 before saving them to a file
if(fwrite($vpb_database, "\r\n".base64_encode($fullname)."::::::::::".base64_encode($username)."::::::::::".base64_encode($email)."::::::::::".base64_encode($encrypted_user_password).""))
{
echo '<font style="font-size:0px;">completed</font>';
echo '<div class="info">Congrats <b>'.$fullname.'</b>, you have registered successful. <br>You may now click on the login button to log into your account.<br>Thanks.</div>';
//
// HERE! I create a folder in the users directory with the variable $username as username
//
$newUserName = $username;
$userPath = "users/".$newUserName;
mkdir("$userPath", 0777);
//copy("index.php",$userPath/index.php);
}
else
{
echo '<div class="info">Sorry, your account creation was unsuccessful, please try again (1).</div>';
}
}
else
{
echo $vpb_error;
}
fclose($vpb_database);
I have absolutely no idea what the problem could be? the code:
$newUserName = $username;
$userPath = "users/".$newUserName;
mkdir("$userPath", 0777);
Should work just fine, or am I missing a small detail?
Remove the quotes.
mkdir($userPath, 0777);

PHP---if(!session_is_registered deprecated?

This if statement has been deprecated
if(!session_is_registered('firstname')){
header("location: index.php"); // << makes the script send them to any page we set
} else {
print "<h2>Could not log you out, sorry the system encountered an error.</h2>";
exit();
}
I replaced it with
if ( isset( $_SESSION['firstname'] ) ){
header("location: index.php"); // << makes the script send them to any page we set
} else {
print "<h2>Could not log you out, sorry the system encountered an error.</h2>";
exit();
the initial code is attached to my logout.php script. When i then go to the link logout.php, this is displayed "Could not log you out, sorry the system encountered an error."
Is that the right solution since i had no problem with the code
Based on your first snippet, I think you are failing in logic.
Try:
if ( !isset($_SESSION['firstname']) ){
header("location: index.php"); // << makes the script send them to any page we set
} else {
exit('<h2>Could not log you out, sorry the system encountered an error.</h2>');
}
Do you have session_start(); on your page?
http://php.net/manual/en/function.session-start.php

Categories