Printing session variable content in PHP - php

Hi I have the following as my login script. (The script is not yet sanitized.) But I have an issue here. Once a successful log in attempt is made I need to echo the loggedUser but the information doen't get printed once echoed. Can someone pls help me understand where I have gone wrong?
Code as follows;
<?php
SESSION_start();
?>
<!doctype html>
<html>
<head></head>
<body>
<div>
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo '<div>User :'.$_SESSION['loggedUser'].'</div>';
}
else
{
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1'>
<tr>
<td>User Name: </td>
<td><label for='textfield'></label>
<input type='text' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td> Password: </td>
<td><label for='txss'></label>
<input type='password' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
if(isset($_POST['loggedUser']))
{
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "Empty fields"; return;}
$SQLSz = "SELECT pword FROM users WHERE username='$un'";
$rVz = mysqli_query($db,$SQLSz) or die ("SQL Error!!!");
$roVz = mysqli_fetch_array($rVz);
if($pw == $roVz['pword'])
{
$result = mysqli_query($db,"SELECT Lname AS Lna FROM users WHERE username='$un'");
$row11 = mysqli_fetch_assoc($result);
$sum = $row11['Lna'];
$_SESSION['loggedUser'] = $sum;
echo $_SESSION['loggedUser'];
}
else
{
echo "No user found";
}
}
}
?>
<div></body></html>

I think problem is in your variable. It can be array but u cant echo array. try dump your variable with var_dump.

As already mentioned - SESSION_start() shall be session_start()
Try another statement for displaying your SESSION array - for example:
echo '<pre>';
print_r($_SESSION);
echo '</pre'>;
This will show you all session keys in a nice and readable way

Related

Button function for all fetch row

I am doing project for my university. I create a page where user can send friend request. Here I fetch data from another table and put button for each row data.
My problem is that when one button click other row button also was change to friend request. I need a solution for it.
How to make one add friend request button is equal to one row id and how to avoid other button affected whenever click particular row.
My code is included below. I hope you guys will help me. Thanks in advance.
<?php
session_start();
$_SESSION['myid'];
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID ORDER BY
tutor_register.register_ID='".$_SESSION['myid']."'desc";
$result= mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
$username = $row['username'];
$profile = $row['profile'];
$email = $row['email'];
$address=$row['address'];
$gender=$row['gender'];
$main_subject=$row["main_subject"];
$subject_add=$row["subject_add"];
$rate_main=$row["rate_main"];
$rate_add=$row["rate_add"];
$qualification=$row["qualification"];
?>
<table><form method="post">
<tr class="border_bottom">
<td height="230"><img src='<?php echo $profile;?>'width="200" height="200"/> </td><td><td></td></td>
<?php
if($register_ID == $_SESSION['myid']){
?>
<td><label>Your Profile</label></td>
<?php
} else {
?>
<form method="post">
<td><button class='friendBtn unfriend' name="" data-type="unfriend">Unfriend</button>
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/></td> </form>
<?php
}
}
?>
</tr>
</div>
</table>
</form>
<?php
if(isset($_POST['id']) ) {
$user_id = $_SESSION['myid'];
$friend_id = $_POST['id'];
$sql="INSERT INTO friends(user_id,status,friend_id)" ."VALUES('$user_id','yes','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['id']=$row['id'];
} else {}
}
}
?>
</body>
</html>
You need to replace the following block in your code:
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>
With the one mentioned below. This will solve your problem.
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes' && $row['register_ID']==$_SESSION['id']){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>

Data transfer between php pages using sessions

I am trying to transfer data between php pages using session. My code is as below:
check_code.php:
<?php
session_start();
echo "<form action=\"check_code.php\" method=\"post\">";
echo "<h2>Your Name. *</h2><input type='text' name='user_name'>";
echo "<br><br>";
echo "<h2>Your age. *</h2><input type='text' name='age'>";
echo "<br><br>";
echo "<br><br><br>";
echo "<div><input type='submit' value='Review'></div>";
echo "</form>";
?>
<?php
if((empty($_POST['user_name'])) || (empty($_POST['age'])) ) {
echo "<h2>Please enter your user name and age</h2>";
} else {
echo "<form action=\"page2.php\" method=\"post\">";
$user_name = $_POST['user_name'];
$age = $_POST['age'];
echo "Below are the details entered:<br>";
echo "Name: $user_name";
echo "Age: $age";
echo "Select any one: ";
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Science">Science</td>';
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Math">Math</td>';
echo "<br>";
$_SESSION['user'] = $_POST['user_name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['subject'] = $_POST['subject'];
echo "<input type=\"submit\" value='Add to DB' >";
echo "</form>";
}
?>
page2.php:
<?php
session_start();
$user_name = $_SESSION['user'];
$age = $_SESSION['age'];
$subject = $_SESSION['subject'];
echo "<h2>Below are the details entered:</h2><br>";
echo "<h2>Name: </h2>$user_name";
echo "<h2>Age: </h2>$age";
echo "<h2>Subject selected: </h2>";
for ($i=0;$i<sizeof($subject);$i++) {
echo " $subject[$i] ";
}
?>
The name and age get displayed in the final page (page2.php). The subject does not get passed to the next page. What mistake am I making here?
Any help would be appreciated!!!
The code you gave had some issues, so I rewrote your code and you might try the one below:
check_code.php file:
<?php session_start(); ?>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Your name</label>
<input type="text" name="name" />
<br>
<label>Your age</label>
<input type="number" name="age" />
<hr>
<button type="submit" name="review">Review</button>
<?php if(isset($_SESSION['details'])) { ?>
<button type="submit" name="unset">Unset</button>
<?php } ?>
</form>
<?php
if(isset($_SESSION['details'])) {
if(isset($_POST['unset'])) { // If pressed "unset", remove the session and the values and restart
unset($_SESSION);
session_destroy();
}
}
if(isset($_POST['review'])) {
if(!empty($_POST['name']) && !empty($_POST['age'])) { // If fields are not empty
?>
<p>Your Details:</p>
<table>
<tr>
<td>Name<td>
<td><?php echo $_POST['name']; ?></td>
</tr>
<tr>
<td>Age<td>
<td><?php echo $_POST['age']; ?></td>
</tr>
</table>
<?php
$_SESSION['details'] = array(
'name' => $_POST['name'],
'age' => $_POST['age']
// Storing them in array as $_SESSION['details'][name/age/whatever]
);
}
else {
echo 'Please fill in the fields.';
}
}
if(isset($_SESSION['details'])) {
?>
<p><?php echo $_SESSION['details']['name']; /* Stored name in session */ ?>, Please Select Subject:</p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Science</label>
<input type="checkbox" name="subject[]" value="science" />
<br>
<label>Math</label>
<input type="checkbox" name="subject[]" value="math" />
<hr>
<button type="submit" name="send">Remember My Choice</button>
</form>
<?php
if(isset($_POST['send'])) { // If you send the second form, then...
if(isset($_POST['subject'])) { // If selected subject
$_SESSION['subject'] = array();
for($i = 0; $i < count($_POST['subject']); $i++) {
$_SESSION['subject'][] = $_POST['subject'][$i]; // store all values of "subject" in the session
}
}
header('location: page2.php');
}
}
Explanation:
You wanted the user to choose a subject after submitting the form, and defined it when the user can not check subject - line 33. when the user can not define the variable, you can continue - but with errors - and that's what I got when I tried your code.
So what I did was the following steps:
Send the first form with the name and the age
Define $_SESSION variable named "details" (as array that held the required information)
If this variable exists - then allow the user to select a subject.
Then, when you choose one (or more) subjects, they're saved too in the session:
page2.php file:
<?php
session_start();
if(isset($_SESSION['details'])) {
?>
<p>Your name is <?php echo $_SESSION['details']['name']; ?> and your age is <?php echo $_SESSION['details']['age']; ?></p>
<?php if(isset($_SESSION['subject'])) { ?>
<p>And your subject(s) are <?php echo implode(', ', $_SESSION['subject']); ?></p>
<?php } else { ?>
<p>You don't have any subject</p>
<?php
}
}
else {
die('An Error Occurred');
}
On page2.php I checked if the details are set. if they are, then we can proceed and check if the subject(s) are set too. In case details are not set, the connection will die and print an error message. If you don't set the subject, you'll get a message about it, too.
Important note:
Your code, and this one too are vulnerable. Do not use these in a server, unless you take care about XSS protection. You may escape characters and use Regular expressions to "Sanitize" the input.
You can replace your current code with this one.
I hope it will be helpful

Building a checkbox list from a database query and retaining the checkbox after a form submit

I am trying to build a simple form which queries a database, grabs a list of email addresses and then creates a table based on the results. What I would like it to do is retain the checked boxes after a submission but am having trouble figuring it out based on the way I've created my table. I can do it no problem if I manually build the table but that defeats the purpose. Here is the code I am working with, again the only change I would like it to do is retain the checked boxes.
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
</head>
<body>
<?php include('include/connect.php'); ?>
<h1>This is a test</h1>
<div class="emailform">
<form action="" method="post">
<table id="emails">
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
</table>
<br/><br/>
<input id="manual" type="text" name="select[]"><br/><br/><br/>
<button type="submit" name="SubmitButton">Select Email Addresses</button>
</form>
</div>
<?php
if(isset($_POST['SubmitButton'])){
if(isset($_POST['select'])){
$shift = $_POST['select'];
if (count($shift) > 1 ){
$list = implode(", ", $shift);
echo $list;
} else {
echo "$shift[0] <br/>";
}
}
}
?>
</body>
</html>
Help would be appreciated, thanks
Just check if the current email in the loop exists in $_POST['select'], if it is, you check it, if it is not, clear the check. This check will be displayed in the input checkbox as <?php echo $checked;?> :
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
// IF EMAIL EXISTS IN $_POST, CHECK IT.
$checked = "";
if(isset($_POST['select'])){
$shift = $_POST['select'];
$list = implode(", ", $shift);
if (strpos($list,$email)===false)
$checked = ""; // EMAIL NOT IN $_POST.
else $checked = "checked"; // EMAIL IS IN $_POST.
}
?>
<tr><td><input type="checkbox" name="select[]" <?php echo $checked;?>
value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
Check if $row['Email'] isn't empty, then output "checked" attribute.
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"<?php if($row['Email'] != false) { echo ' checked'; } ?>><?php echo $email; ?></td></tr>
<?php
}
?>

Session variable content changes when form refreshes in PHP

suppose I have two users in the SQL database. In the table column authority one is the Administrator and the other is user.
My issue is if I log in as the Administrator, before the form refreshes, the $_SESSION['Authentication'] echoes 'Administrator', but after the form refreshes $_SESSION['Authentication']` echoes as 'user'.
Where have I gone wrong in my code which result the $_SESSION['Authentication'] = 'user' whereas it should be $_SESSION['Authentication'] = 'Administrator' after the form refreshes?
Code :
Session started at the beginning....
then this follows.
<?php
include ("connect_db/index.php");
if(isset($_SESSION['loggedUser']))
{
echo "<form action='signoff/index.php'><div id='four'>Welcome&nbsp". $_SESSION['loggedUser']." !
<input type='submit' name='soff' id='soff' class='sout' value='Sign off'></div></form>";
echo "You are the : ".$_SESSION['Authentication']." of the site.";
}
else
{
?><div id='one'><?php
echo "
<div id='u2'>
<form name='form1' method='post' action='''>
<table border='1' style='width:520px; bordercolor:#FFFFFF;'>
<tr>
<td style='width:30px;'>User Name: </td>
<td style='width:80px;'><label for='textfield'></label>
<input type='text' maxlength='12' name='UnameZoom' id='UnameZoom' class='txss'></td>
<td style='width:30px;'> Password: </td>
<td style='width:80px;'><label for='txss'></label>
<input type='password' maxlength='12' name='PwordZoom' id='PwordZoom' class='txss'></td>
<td> <input type='submit' name='loggedUser' id='loggedUser' class='mylog' value='Login'></td>
</tr>
</table>
</form>
<p> </p>
<p> </p>
</div>";
?></div><?php
if(isset($_POST['loggedUser']))
{
?><div id='two'><?php
$un = $_POST['UnameZoom'];
$pw = $_POST['PwordZoom'];
if($un=='' || $pw == '')
{echo "<div id='three'>Empty Fields</div>";}
else {
$SQL = "SELECT pword FROM users WHERE username='$un'";
$resultA = mysqli_query($db,$SQL) or die ("SQL Error!!!");
$row = mysqli_fetch_array($resultA);
if($pw == $row['pword'])
{
$resultB = mysqli_query($db,"SELECT fname AS Lna FROM users WHERE username='$un'");
$rowB = mysqli_fetch_assoc($resultB);
//$sum = $rowB['Lna'];
$_SESSION['loggedUser'] = $rowB['Lna'];
$resultC = mysqli_query($db,"SELECT authority AS Auth FROM users WHERE username='$un'");
$rowC = mysqli_fetch_assoc($resultC);
unset($_SESSION['Authentication']);
$_SESSION['Authentication'] = $rowC['Auth'];
header("refresh:3;");
//echo "<div id='four'>Welcome&nbsp". $_SESSION['loggedUser']."&nbsp!</div>";
}
else
{
echo "<div id='three'>No user found</div>";
}
}
?></div><?php
}
}
?>
// this is where I'm trying to echo
<div id="contentLog">
<?php
if(isset($_SESSION['Authentication']))
{echo $_SESSION['Authentication'];}
?>
Your header("refresh:3;"); makes me suspicious. This might be relevant. Add session_write_close() before you call header()? Echo session_id() to see if the refresh creates a new blank session or if you have a logic error.
please use this condition
if($_POST['loggedUser'] != "")
{
}

php form submit - Q2

i am sorry for the dummy question. Here is my simple PHP form with two SQL tables and with the ADD submit button I would like to move people from Test1 to Test2. Many thing are fine:( only the submit button does't work therefore no feedback from Test2 table.
Revised: Submit now works great
Q2 - still don't get the checkboxs to work:( - please
Could somebody show me how to track back such an error like this please?
<?php include("db_connect.php");?>
<html>
<head></head>
<body>
<form method="post" action="moving.php">
<table border="1">
<tr>
<td>
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1)) {
?>
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php } ?>
</td>
<td><input type="submit" id="add" name="add" value="Add" /></td>
<td>
<?php
$rigth='SELECT * FROM test2,test1 WHERE test2.collect=test1.id ORDER BY test1.name ASC';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2)) {
echo $resultb['id'] ;
echo "<br />";
}
?>
</td>
</tr>
</table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($i=0;$i<$count;$i++) {
$add_id = $checkbox[$i];
if ($add_id=='1') {
$sql = "INSERT INTO test2 (status, collect) VALUES(1, 1)";
$result = mysql_query($sql);
}
}
// if successful redirect to delete_multiple.php
if ($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=moving.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>
thanks:) from a beginner
where does $count come from?
Try using count($_POST['checkbox']) instead on your INSERT statement. Then you can iterate over the checkboxes using:
for ($c = 0; $c < count($_POST['checkbox']); $c++){
$checkbox = $_POST['checkbox'][$c];
...INSERT action...
}
In the sample code, you store the statement in a variable named $rigth, but you (try to) execute a statement stored in a variable named $right.
There are a couple things you can do to catch errors.
Try static code analysis; some tools can tell you if a variable is used only once (an indication it may be a typo).
Handle errors. Some functions return a special value if there's an error (False is a common one); for these functions, there is usually a related function that will return error information. Some functions will throw an exception; catch them where they can be appropriately taken care of. System error messages shouldn't be displayed to non-admin users so you don't disclose too much information.
Use an interactive debugger. For example, install the Xdebug extension on your development server (you do use a dev server, right?) and use an Xdebug compatible debugger.
the solution - not nice but it works - thanks for all the comments and help!!!
<?php include("db_connect.php");?>
<html>
<head>
</head>
<body>
<form method="post" action="test.php">
New:
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1))
{
?>
<input name="checkbox_add[]" type="checkbox" id="checkbox_add[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php
}
?>
</td> <td><input type="submit" id="add" name="add" value="Add" /><br /><input type="submit" id="delete" name="delete" value="Del" /></td><td>
<?php
$right='SELECT test2.id, test1.name FROM test2, test1 WHERE test1.id=test2.collect AND test2.status=1';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2))
{
?>
<input name="checkbox_del[]" type="checkbox" id="checkbox_del[]" value="<?php echo $resultb['id']; ?>"/>, <?php echo $resultb['id']; ?>, <? echo $resultb['name']; ?>
<br />
<?php
}
?>
</td></tr></table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($c = 0; $c < count($_POST['checkbox_add']); $c++){
$checkbox_add = $_POST['checkbox_add'][$c];
$sql = "INSERT INTO test2 (status, collect) VALUES(1, ".$checkbox_add.")";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['delete'])) {
for ($c = 0; $c < count($_POST['checkbox_del']); $c++){
$checkbox_del = $_POST['checkbox_del'][$c];
echo date("Y-m-d");
$sql = "UPDATE test2 SET status='2', log='".date('Y-m-d')."' Where id=".$checkbox_del;
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['new'])) {
$sql = "INSERT INTO test1 (status, name) VALUES(1, '".$_POST['newitem']."')";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>

Categories