/    Sign up×
Community /Pin to ProfileBookmark

Handle errors with $_SESSION array

I am working on creating user profile access and modifying information (like password, email or username- which obviously should be limited). The function itself works, but when trying to grab information from the username to check if it meets standards (which just 6 letters or longer isnt the best limiter). It hits the if statement, for if it is too short, but the array is not adding the new parameter/value when it hits it (I used a var_dump to double check on both pages). I tried array_push, but that just brought errors, and many posts say that the way I am doing it is right (if I set it up right). The array itself is created with just the value [“created” => “created”] if it does not exist (checked on every page load),

Profile.php:

[code=php]
<form action=”/ChangeUsername.php” method=”post”>
<input type=”text” name=”username”><br>
<input type=”submit” value=”Change Username”>
<?php if (isset($_SESSION[‘Errors’][‘UsernameChange’])){
echo “<p class=’errortext’>” . $_SESSION[‘Errors’][‘UsernameChange’] . “</p>”;
unset($_SESSION[‘Errors’][‘UsernameChange’]);
} ?>
</form>
[/code]

ChangeUsername.php:

[code=php]
<?php
session_start();
$DBaccess = parse_ini_file(“../Users.ini”);

$NewUsername = $_POST[‘username’];
if (strlen($NewUsername) < 6){
$_SESSION[‘Errors’][‘UsernameChange’] = “Username is shorter than 6 characters”;
header(“location: /Profile.php”);
die();
} elseif(!isset($NewUsername)){
$_SESSION[‘Errors’][‘UsernameChange’] = “Username is empty”;
header(“location: /Profile.php”);
die();
} else {

echo “<br>”;
echo $NewUsername;
echo “<br>”;
echo $_SESSION[‘UserID’];

$dbhost = $DBaccess[‘dbhost’];
$username = $DBaccess[‘username’];
$password = $DBaccess[‘password’];
$dbname = $DBaccess[‘dbname’];
$pdo = new PDO(“mysql:host=$dbhost;dbname=$dbname;”, $username, $password);
$sql = “UPDATE Profiles SET Username=:newusername WHERE ID=:ID”;
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
“:newusername”=>$NewUsername,
“:ID” => $_SESSION[‘UserID’]
));
$_SESSION[‘Username’] = $NewUsername;
header(“location: /Profile.php”);
die();
}
?>
[/code]

I am not fully sure on arrays, as I have only used them by accessing pre-created or $_SESSION, but not an array in array. I want to use an array in session since it will refresh in every new session and it is easily accessible.

to post a comment
PHP

17 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — Why don't you read up on arrays in the official php manual? A great resource that you really need to get familiar with.
Copy linkTweet thisAlerts:
@PCEntrailsauthorMay 31.2017 — I did read up on it, and it looks like what I am doing is correct:

$_SESSION[ArrayToAccess][NewParameterOfArray]
Copy linkTweet thisAlerts:
@NogDogMay 31.2017 — If doing a header() redirect, I've found that for some reason you often need to do a session_write_close() before doing the header()/die().
[code=php]
if($somethingorother) {
$_SESSSION['foo'] = 'bar';
session_write_close();
header("location: /Profile.php");
die();
}
[/code]


Not guaranteeing this is the issue/fix, but might be worth a try. Otherwise we'd probably need some more debug info.
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — You missed the part in the reading that discusses how to present the indices in array nomenclature. The example you posted, while it WILL work, is not the preferred (and popular) method.

$_SESSION['ArrayToAccess']['NewParameterOfArray']

PS - it is much wiser to stick to one case in php variable names. You'll be kicking yourself later for using upper and lower case names.
Copy linkTweet thisAlerts:
@PCEntrailsauthorMay 31.2017 — I could not find anything about "present the indices in array nomenclature" for arrays in the official PHP manual. And the session_write_close() did not help.
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — Did you read it at least to see what I was talking about? Jeez!
Copy linkTweet thisAlerts:
@PCEntrailsauthorMay 31.2017 — I have read what you have posted, and I don't see anything pointing to a solution.
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — Ignoring your array difficulties, let me ask you what this text means:

"

The function itself works, but when trying to grab information from the username to check if it meets standards (which just 6 letters or longer isnt the best limiter). It hits the if statement, for if it is too short, but the array is not adding the new parameter/value when it hits it

"

1 What function - I don't see any user-supplied function here.

2 It hits the if statement (and) if it is too short..... What array is not adding what new parameter? I don't see that code here.

Basically - other than being sloppy coding - I don't see anything going wrong with what you have shown us.
Copy linkTweet thisAlerts:
@PCEntrailsauthorMay 31.2017 — the first if statement or ChangeUsername.php where is checks the length, it adds to the "Error" array in the $_SESSION array, but it does not actually add it. I have turned error reporting on with ini_set , and used var_dump on both the "Error" array and $_SESSION, but it does not show the new parameter/index/value of "Error" in var_dump or when I call it to echo in Profile.php .
Copy linkTweet thisAlerts:
@benanamenMay 31.2017 — You are way, way over complicating a simple task and your logic is wrong. Also, the code should be in one page. Displaying a message when the user does not enter anything is pointless. Nobody expects anything to happen if they do not enter anything.


[code=php]<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!empty(trim($_POST['new_username'])))
{
if (strlen($_POST['new_username']) < 6)
{
echo '6 Character Minimum';
}
else
{
//UPDATE DB
echo 'DB update';
}
}
}
?>
<form method="post">
<input type="text" name="new_username"><br>
<input type="submit" value="Change Username">
</form>[/code]
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — How do you know it doesn't add it? Nothing here shows us that you are even checking! PUt an echo right there and prove what you think is happening. Yes - I know the header will fail, but at least we can move forward after seeing what is supposedly not working.

How do you expect us to help you with such small tidbits of code that don't show us what you are seeing?
Copy linkTweet thisAlerts:
@NogDogMay 31.2017 — Does profile.php have a call to session_start() before (a) anything is output to the browser and (b) before you do anything with the $_SESSION array in that script? If the answer is "no", then that needs to be addressed first.
Copy linkTweet thisAlerts:
@benanamenMay 31.2017 — Gentlemen, SESSIONS should not even be part of this equation. See post #11
Copy linkTweet thisAlerts:
@PCEntrailsauthorMay 31.2017 — I clearly only put a small portion that is pertinent to the problem from profile.php because there is a lot of extra that is not needed to be known that I do not want to over complicate - which obviously does have an input/submit to be used.

All my main web pages (that the user actually sees, unlike quick script pages like ChangeUsername.php) import a header that contains session_start. There are no errors generated with the error reporting, as the page is blank (with just error reporting, not var_dump). With var_dump on $_SESSION['Errors'], nothing shows up at all (even though in the header I have this small script to create the Errors array in $_SESSION if it does not exist). (header is obviously not placed into ChangeUsername.php ).

These are the full scripts of the pages.


Header.php
[code=php]
<?php
session_start();
$CPDatabase = parse_ini_file("../Database.ini");

if (!isset($$_SESSION['Errors'])){
$Errors = array("Created" => "Created");
$_SESSION['Errors'] = $Errors;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>PC Entrails</title>
<meta charset="utf-8" />
<meta name="keywords" content="PCEntrails, Build Computers Online, Build Computer, Computer Parts, DIY Computers, Computer Hardware">
<meta name="description" content="Build computers online that will fit your needs">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/images/Favicon.png" type="image/x icon">
<link rel="stylesheet" href="/css/main.css">
</head>

<body>

<div id="Header">
<h1>PC Entrails</h1>
</div>

<?php
if ($_SESSION['LogInAttempts'] < 4 && $_SESSION['LoggedIn'] != 1){
echo '
<div id="Login">
<form action="/login.php" method="post">
<input type="text" name="username"><br>
<input type="text" name="password"><br>
<input type="submit" value="Login">
</form>
</div> ';
} else {
echo '
<div id="Login">
'. $_SESSION['Username'].'
<form action="/logout.php" method="post">
<input type="submit" value="Logout">
</form>
</div>';
}
?>
[/code]



Profile.php
[code=php]
<?php include '/PageParts/header.php' ?>
<?php include '/PageParts/menu.php' ?>

<?php
if ($_SESSION['LoggedIn'] != 1){
header("location: /Logout.php");
die();
}
$DBaccess = parse_ini_file("../Users.ini");
$dbhost = $DBaccess['dbhost'];
$username = $DBaccess['username'];
$password = $DBaccess['password'];
$dbname = $DBaccess['dbname'];
$UserName = $_SESSION['Username'];

$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;", $username, $password);
$sql = "SELECT Email,Password FROM Profiles WHERE Username=:username";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(":username" => $UserName));
$UserInformation = $stmt->fetch();
?>

<h1>
<?php
echo $UserName;
?>
</h1>
<br><br><br>
<h2>
<?php
echo "Email: " . $UserInformation['Email'] . "<br>";
echo "Password: " . $UserInformation['Password'];
?>
</h2>
<br><br><br>
<form action="/ChangeUsername.php" method="post">
<input type="text" name="username"><br>
<input type="submit" value="Change Username">
<?php if (isset($_SESSION['Errors']['UsernameChange'])){
echo "<p class='errortext'>" . $_SESSION['Errors']['UsernameChange'] . "</p>";
unset($_SESSION['Errors']['UsernameChange']);
} ?>
</form>
<br><Br>
<form action="/ChangeEmail.php" method="Post">
<input type="email" name="Email"><br>
<input type="Submit" value="Change Email">
<?php if (isset($_SESSION['Errors']['EmailChange'])){
echo "<p class='errortext'>" .$_SESSION['Errors']['EmailChange'] . "</p>";
unset($_SESSION['Errors']['EmailChange']);
} ?>
</form>
<br><br>
<form action="/ChangePassword.php" method="post">
<input type="text" name="password1"><br>
<input type="text" name="password2"><br>
<input type="submit" value="Change Password">
<?php if (isset($_SESSION['Errors']['PasswordChange'])){
echo "<p class='errortext'>" .$_SESSION['Errors']['PasswordChange'] . "</p>";
unset($_SESSION['Errors']['PasswordChange']);
} ?>
</form>


<?php include '/PageParts/footer.php' ?>
[/code]



ChangeUsername.php
[code=php]
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$DBaccess = parse_ini_file("../Users.ini");

$NewUsername = $_POST['username'];
if (strlen($NewUsername) < 6 or strlen($NewUsername) > 32){
$_SESSION['Errors']['UsernameChange'] = "Username is shorter than 6 characters";
session_write_close();
//header("location: /Profile.php");
die();
} elseif(!isset($NewUsername)){
$_SESSION['Errors']['UsernameChange'] = "Username is empty";
session_write_close();
//header("location: /Profile.php");
die();
} else {

echo "<br>";
echo $NewUsername;
echo "<br>";
echo $_SESSION['UserID'];

$dbhost = $DBaccess['dbhost'];
$username = $DBaccess['username'];
$password = $DBaccess['password'];
$dbname = $DBaccess['dbname'];
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;", $username, $password);
$sql = "UPDATE Profiles SET Username=:newusername WHERE ID=:ID";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
":newusername"=>$NewUsername,
":ID" => $_SESSION['UserID']
));
$_SESSION['Username'] = $NewUsername;
session_write_close();
//header("location: /Profile.php");
die();

var_dump($_SESSION['Errors']);
}
?>
[/code]
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — $$_session ??????
Copy linkTweet thisAlerts:
@ginerjmMay 31.2017 — Can't seem to correct my above mistake.

You have "$$_SESSION" referenced.
Copy linkTweet thisAlerts:
@benanamenMay 31.2017 — So much wrong here. Lets just start with this: if (!isset([B][COLOR="#FF0000"]$[/COLOR][/B]$_SESSION['Errors'])){

The code really needs a complete rewrite. Patching it so it "works" is just going to allow you to keep building on very flawed code.

Your naming is all over the place. Lowercase, Mixed case, variables for nothing....
×

Success!

Help @PCEntrails spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...