Session get another value when navigating thru pages PHP - php

My session is lost when I go to a specific menu on my webpage.
on login.php the session is created, then I am redirected to menus.php which is the main page for my user. If I go into usuarios.php and then select one of those users I am redirect to ver_usuarios.php and carry some variables on the url using get method.
When I get to ver_usuarios.php and if I refresh the page the session just expires it kickes me out of the webpage and I'm not using session_destroy(); never. You can see my webpage runnin here: http://santateclacentral.org/login.php user=alejo pass= 123 go to usuarios and then to each user and see the issue here is my code:
USUARIOS.PHP
<?php
include("../conexion.php");
require_once('../sesion_usuarios.php');
include("../paginacion/paginator.class.php");
$query_usuarios = mysql_query("select usuarios.nick_usuario, roles.rol, miembros.imagen_miembro, usuarios.estado_usuario, usuarios.id_usuario, miembros.nombre_miembro from usuarios join roles on usuarios.id_rol = roles.id_rol join miembros on miembros.id_usuario = usuarios.id_usuario $pages->limit");
$hay = mysql_num_rows($query_usuarios);
if($hay){
while ($datos = mysql_fetch_row($query_usuarios)) {
# code...
?>
<td class="resize"><img src="<?php echo $datos[2]?>" width="50px" height="50px"></td>
<td class="resize"><?php echo $datos[5]?></td>
<td class="resize"><?php echo $datos[0]?></td>
<td><?php echo $datos[1]?></td>
//Take a look at this , here is where i get the variables and redirect to ver_usaurios.php page
<td><a class="btn btn-info" href="ver_usuarios.php?user=<?php echo $datos[2]?>&state=<?php echo $datos[3]?>&e=<?php echo $datos[4]?>">Ver</a></td>
<?php
if ($datos[3] == true) {
# code...
?>
<td><a class="btn btn-success" href="activar_usuarios.php?user=<?php echo $datos[2]?>&state=<?php echo $datos[3]?>&k=<?php echo $datos[4]?>&activate=9468752130_edit" value="Ver"> Activar </a></td>
<?php
} else{
?>
<td><a class="btn " href="desactivar_usuarios.php?user=<?php echo $datos[2]?>&state=<?php echo $datos[3]?>&k=<?php echo $datos[4]?>&deactivate=1679854320_edit">Desactivar</a></td>
<?php
}
?>
<!-- <td><a class="btn btn-danger" onClick="borrar(<?php echo $datos[4]?>)">Borrar</a></td> -->
<tr></tr>
<?php
}
}else{
?>
<tr>No hay registros</tr>
<?php
}
?>
VER_USUARIOS.PHP?user=&e=
<?php
require("../conexion.php");
session_start();
require_once('../sesion_usuarios.php');
$query_menus_usuarios = mysql_query("SELECT m.id_menu, m.menu_url, m.nombre_menu FROM menus m join menus_usuarios mu on m.id_menu = mu.id_menu join usuarios u on mu.id_usuario = u.id_usuario where u.id_usuario = '".$_SESSION['id_usuario']."' and mu.estado = 1");
while($menus_mostrar = mysql_fetch_row($query_menus_usuarios)){
if($menus_mostrar[2] == "Usuarios"){
?>
<li class="active"><?php echo $menus_mostrar[2]; ?></li>
<?php
} else {
?>
<li ><?php echo $menus_mostrar[2]; ?></li>
<?php
}
}
?>
<li class="dropdown">
Administrador<b class="caret"></b>
<ul class="dropdown-menu">
<?php
if (!isset($_SESSION['login'])) {
# code...
?>
<li>Login</li>
<?php
} else {
?>
<li class="">Administrar</li>
<li>Cerrar Sesion</li>
<?php
}
?>

It sounds like you forgot to put session_start() at the top of the (each) admin page.

Related

ID number doesn't change

I've been creating a CMS blog and this is one of the pages that accessible by the admins. I'm trying to implement pagination in it.
As you can see, it shows the latest six posts in the first page with the IDs from 1 to 6, but when I click on the forward button, it shows the IDs 1 and 2 again for the other posts in which it should be 7 and 8. Could someone tell me what's causing this bug?
First page
Second page
<!-- Right Side Area Start -->
<div class="col-lg-10">
<div class="card-body bg-info">
<h2 class="large-georgia-white-bold">Top Posts</h2>
</div>
<table class="table table-striped table-hover">
<thead class="thead-dark small-times-white">
<tr>
<th>No.</th>
<th>Title</th>
<th>Date&Time</th>
<th>Author</th>
<th>Comments</th>
<th>Details</th>
</tr>
</thead>
<?php
$SrNo = 0;
global $ConnectingDB;
// Query When Pagination is Active i.e Dashboard.php?page=1
if (isset($_GET["page"])) {
$Page = $_GET["page"];
if ($Page==0||$Page<0) {
$ShowPostFrom=0;
}else{
$ShowPostFrom=($Page*6)-6;
}
$sql ="SELECT * FROM posts ORDER BY id desc LIMIT $ShowPostFrom,6";
$stmt=$ConnectingDB->query($sql);
}
// The default SQL query
else{
$sql = "SELECT * FROM posts ORDER BY id desc LIMIT 0,6";
$stmt=$ConnectingDB->query($sql);
}
while ($DataRows=$stmt->fetch()) {
$PostId = $DataRows["id"];
$DateTime = $DataRows["datetime"];
$Author = $DataRows["author"];
$Title = $DataRows["title"];
$SrNo++;
?>
<tbody class="small-times-black">
<tr>
<td><?php echo $SrNo; ?></td>
<td><?php echo $Title; ?></td>
<td><?php echo $DateTime; ?></td>
<td><?php echo $Author; ?></td>
<td>
<?php $Total = ApproveCommentsAccordingtoPost($PostId);
if ($Total>0) {
?>
<span class="badge badge-success">
<?php
echo $Total; ?>
</span>
<?php } ?>
<?php $Total = DisApproveCommentsAccordingtoPost($PostId);
if ($Total>0) { ?>
<span class="badge badge-danger">
<?php
echo $Total; ?>
</span>
<?php } ?>
</td>
<td> <a target="_blank" href="FullPost.php?id=<?php echo $PostId; ?>">
<span class="btn btn-info">Preview</span>
</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<!-- Right Side Area End -->
<!-- Pagination -->
<nav>
<ul class="pagination pagination-lg">
<!-- Creating Backward Button -->
<?php if( isset($Page) ) {
if ( $Page>1 ) {?>
<li class="page-item">
«
</li>
<?php } }?>
<?php
global $ConnectingDB;
$sql = "SELECT COUNT(*) FROM posts";
$stmt = $ConnectingDB->query($sql);
$RowPagination = $stmt->fetch();
$TotalPosts = array_shift($RowPagination);
//echo $TotalPosts."<br>";
$PostPagination=$TotalPosts/6;
$PostPagination=ceil($PostPagination);
//echo $PostPagination;
for ($i=1; $i <= $PostPagination ; $i++) {
?>
<li class="page-item">
<?php echo $i; ?>
</li>
<?php } ?>
<!-- Creating Forward Button -->
<?php if ( isset($Page) && !empty($Page) ) {
if ($Page+1 <= $PostPagination) {?>
<li class="page-item">
»
</li>
<?php } }?>
</ul>
</nav>
</div>
</div>
</section>
<!-- Main area end -->
Your script always reassigns $SrNo = 0 when the page is loaded and starts over. You should add the page * 6 value to it so it becomes aware of the offset. In fact, you're already using that logic for $ShowPostFrom, so you can simply assign the same value to $SrNo and it should work:
if ($Page==0||$Page<0) {
$ShowPostFrom=0;
}else{
$ShowPostFrom=($Page*6)-6;
}
$SrNo = $ShowPostFrom; // <- this is what you should add
If you don't mind modifying $ShowPostFrom, you can drop $SrNo completely and just use $ShowPostFrom to show the number.

Clicking view button and nothing happens

After clicking the VIEW button and nothing happening, I started to wonder what's wrong?
GALLERIES NAME POST EDIT DELETE
Slideshow VIEW
SERVICES POST VIEW
Code:
<?php foreach ($gallery as $gallery_item): ?>
<tr>
<td><?php echo $gallery_item['galleries_name']; ?></td>
<td>
<?php if( $gallery_item['galleries_post_type'] == 'post') { echo "#"; }?>
</td>
<td>
<button type="button" class="edit" onclick="location.href = '
<?php
if( $gallery_item['galleries_post_type'] == 'post') {
echo site_url('cpages/galleries/'.$gallery_item['galleries_id']);
} else {
echo site_url('cpages/viewpictures/'.$gallery_item['galleries_id']);
}
?>
';">VIEW</button>
</td>
I think you should use links and describe them as button (role, type, whatsoever) and decore them with CSS. That is:
<?php
$id = $gallery_item['galleries_id']);
?>
<td>
<?php if ($gallery_item['galleries_post_type'] === 'post'): ?>
<a href="<?= site_url('cpages/galleries/'.$id); ?>" class="edit">
<?php elseif (): ?>
<a href="<?= site_url('cpages/viewpictures/'.$id); ?>" class="edit">
<?php endif; ?>
</td>
By searching for a better solution, I found an answer from BalusC that, I think, should solve your problem and help you understand how/what/when questions about buttons, links and so one.

Why does my form get replaced with echo "0"?

I got an error on my page that I can't identify, and when I view the site online it replaces all my site content with the value "0".
How come I can't see the forms, and is it communicating with the SQL server properly?
PS: Login works and session is created, so the connect.php does work properly.
Here is the code for members.php:
<?php
// starting session
session_start();
// check if user is logged in
if (!isset($_SESSION['username']))
{
header('Location: http://wwww.gjertgjersund.com/');
exit();
}
else
{
// database connection
require ('connect.php');
//post record count
$post_count = mysql_query("SELECT * FROM posts");
$post_count_result = mysql_num_rows($post_count);
//comment count
$comment_count = mysql_query("SELECT * FROM comments");
$comment_count_result = mysql_num_rows($comment_count);
if(isset($_POST['submit']))
{
$newcategory = $_POST['newcategory'];
if(!empty($newcategory))
{
$query = mysql_query("INSERT * INTO categories (category) VALUES ('$newcategory')";
if($query)
{
echo 'New category added';
}
}
else
{
echo 'Error';
}
}
else
{
echo 'Missing newcategory';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> Folder </title>
<body>
<div class="wrap">
<div id="menu">
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Create New Post</a></li>
<li><a href='#'>Delete Post</a></li>
<li><a href='logout.php'>Log Out</a></li>
<li><a href='#'>Blog Home Page</a></li>
</ul>
</div>
<div id="maincontent">
<table>
<tr>
<td>Total Blog Post</td>
<td><?php echo $post_count_result ?></td>
</tr>
<tr>
<td>Total Comments</td>
<td><?php echo $comment_count_result ?></td>
</tr>
</table>
<div id="categoryform">
<form action="members.php" method="post">
<label for="category">Add New Category</label>
<input type="text" name="newcategory"/>
<input type="submit" name="submit" value="Create"/>
</form>
</div>
</div>
</div>
</body>
</html>
$query = mysql_query("INSERT * INTO categories (category) VALUES ('$newcategory')";
should be
$query = mysql_query("INSERT INTO categories (category) VALUES ('$newcategory')";

php: session disappears after page navigation

I've read all the posts I could find about this issue, but, to date, none of the solutions have worked for me. Obviously, I'm overlooking something important. I also don't know how to debug sessions. I read one article, PHP session Debugging, but it was over my head.
So, much like the other issues, when I navigate to another page in my app, whether through a link or a form submit, my session disappears. I have no idea why my session vanishes. If someone has the time to help me investigate, it would be greatly appreciated.
These are my php.ini settings
; Name of the session (used as cookie name).
session.name = PHPSESSID
; The path for which the cookie is valid.
session.cookie_path = /
This is the first view to display
<?php
session_start();
if (!isset($_SESSION['session_id'])) {
$_SESSION['session_id'] = session_id();
}
if (!isset($_SESSION['invoices'])) {
$_SESSION['invoices'] = $invoices;
}
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . " in invoiceList.<br />");
} else {
echo 'No session ID set in invoiceList <br />';
}
?>
<div>
<table>
<tr>
<th>Customer Name</th>
<th>Invoice Date</th>
<th>Invoice Number</th>
</tr>
<tr>
<?php
include_once 'form/editInvoice.php';
if (isset($invoices)) {
foreach ($invoices as $invoice) {
?>
<tr>
<td><?php echo $invoice['customer_name'] ?></td>
<td><?php echo $invoice['invoice_date'] ?></td>
<td><?php echo $invoice['invoice_number'] ?></td>
<td><a href='<?php echo $_SERVER['SCRIPT_NAME']; ?>/retrieve?class=InvoiceLineItems&id=<?php echo $invoice['invoice_id']; ?>'><?php echo $invoice['invoice_id']; ?></a></td>
</tr>
<?php
}
} else {
echo 'No invoices retrieved.';
}
?>
</tr>
</table>
</div>
Here is the included form:
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "in editForm<br />");
} else {
echo 'No session ID set in editForm <br />';
}
if (!$_POST) {
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<fieldset>
<legend>Enter Updated PO Number</legend>
<li>PO Number: <input type="text" name="po_number"/></li>
</fieldset>
<input type="submit" value="Submit" />
<input type="button" onclick="alert('Changes Canceled.')" value="Cancel"/>
</form>
<?php }
?>
And finally, the detail page for when the user clicks a link in the main page.
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "<br />");
} else {
echo 'No session ID set invoice<br />';
}
?>
<h1>Invoice Detail</h1>
<div>
<?php
foreach ($partnerInfo as $info) {
switch ($info['role_indicator']) {
case 'remit_to':
?>
<div id="remit">
<ul>
<li>PLEASE REMIT TO:</li>
<li><?php echo $info['partner_name']; ?></li>
<li><?php echo $info['street_name']; ?></li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
</ul>
</div>
<?php break; ?>
<?php case 'seller': ?>
<div id = "seller" >
<ul>
<li>Service Site:</li>
<li><?php echo $info['partner_name']; ?></li>
<?php
if ($info['partner_aux_info'] !== NULL) {
?><li><?php echo $info['partner_aux_info']; ?>
<?php }
?>
</li>
<li><?php echo $info['street_name']; ?></li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
<li>(405)677-0221</li>
</ul>
</div>
<?php break; ?>
<?php case 'sold_to': ?>
<div id="buyer">
<ul>
<li>Bill To: </li>
<li><?php echo $info['partner_name']; ?></li>
<li><?php echo $info['street_name']; ?></li>
<?php
if ($info['suite_info'] !== NULL) {
?><li><?php echo $info['suite_info']; ?>
<?php }
?>
</li>
<li><?php echo $info['city_name']; ?>, <?php echo $info['state']; ?> <?php echo $info['postal_code']; ?></li>
</ul>
</div>
<?php break; ?>
<?php
}
}
?>
<h1>Line Items</h1>
<table>
<th>PO Number</th>
<th>PO Issued Date</th>
<th>Description</th>
<th>Service Start Date</th>
<th>Service End Date</th>
<th>Shipped Date</th>
<?php foreach ($invoiceLineItems as $lineItem) { ?>
<tr>
<td><?php echo $lineItem['po_number']; ?></td>
<td><?php echo $lineItem['po_issued_date']; ?></td>
<td><?php echo $lineItem['line_item_name']; ?></td>
<td><?php echo $lineItem['service_period_start']; ?></td>
<td><?php echo $lineItem['service_period_end']; ?></td>
<td><?php echo $lineItem['request_for_delivery']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
Edit: I've removed the session checks and updated the code sample. I've added session_start() before my <head> tag in index.php. I've verified that I can write to the session temp folder.
When i execute this code in my controller to update the invoices with the new PO number, I reach the model's function, but the session is gone.
//If form is posted, update line items with PO number and date.
if (isset($_POST['po_number'])) {
$this->invoice->update();
}
By the time I reach the session variable assignment, I have no session data:
public function update() {
$con = $this->_getLocalConn();
$invoices = $_SESSION['invoices'];
try {
$sqlUpdate = $con->prepare("UPDATE invoices
SET po_number = ?, po_issued_date = ?
WHERE invoice_id = ?");
foreach ($invoices as $record) {
$sqlUpdate->execute(array(
$_POST['po_number'],
getdate(),
$record['invoice_id']
));
}
} catch (PDOException $e) {
print $e->getMessage();
}
//get the PO number being used to update the records
//perform db update where po_number = input
//notify user of success and display updated records.
}
Each PHP file should start with session_start(); regardless of $_SESSION being set or not. This function will create a new session OR take up the existing one.
No $_SESSION is started to begin with when you check it with your first if. Therefore, it will always FAIL. You must call session_start() PRIOR to doing anything with a $_SESSION variable. Correct your code.
First page:
<?php
session_start();
/* Don't need this unless you really need the debugging
Previously you where assigning variables that did not
exist to the the $_SESSION variables. Not what you want
I imagine.
if (!isset($_SESSION)) {
var_dump($_SESSION);
}
*/
...
Include form:
<?php
session_start();
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "in editForm<br />");
} else {
echo 'No session ID set in editForm <br />';
}
...
Detail page:
<?php
session_start(); //Notice a pattern here??
if (isset($_SESSION['session_id'])) {
print_r($_SESSION['session_id'] . "<br />");
} else {
echo 'No session ID set invoice<br />';
}
?>
All of your code that needs the session information should start with session_start(). session_start() needs to happen before any headers or other output would be written.
Setup and teardown are then handled for you.
I do this:
session_start();
$s = &$_SESSION;
Then you can use read/write $s just like it was $_SESSION
If you are doing self referencing image downloads or other code that may end up wanting to execute in parallel, NOT starting a session or closing it as soon as possible with session_write_close() will give you a significant performance boost.
Without this, sessions essentially make your code run single threaded.
Edit: Saying single threaded was perhaps a bad choice of words.
Lets say you had a page with three iframes in it, each one loading a different (or the same) php script. If you are using sessions, the result would be the iframes loading one at a time instead of all at once. Each one would get a lock on the session and the others would wait at session_start() until the session was available again.

Creating Dynamic Links with PHP/MySQL

i'm creating my first PHP/MySQL site and i'm having difficulty figuring out how to generate dynamic links and creating a new page for those links.
My index page is pulling in certain details from my database as a preview, and when the visitor clicks on that item, i want them to be taken to a page which shows the full information from the database for that row.
The code on my index page for displaying the previews is below, any help on amending it to generate the link and page would be greatly appreciated.
<?php
$query="SELECT * FROM $tbl_name ORDER BY job_id DESC";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"company_name");
$f2=mysql_result($result,$i,"job_title");
$f3=mysql_result($result,$i,"city");
$f4=mysql_result($result,$i,"country");
$job_id=mysql_result($result,$i,"job_id");
?>
<div class = "hjl">
<ul>
<li id = "jobtitle"><?php echo $f2; ?></li><br />
<li id = "compname"><?php echo $f1; ?></li>
</ul>
<ul>
<li id = "city"><?php echo $f3; ?>, <?php echo $f4; ?></li><br />
</ul>
</div>
<?php
$i++;
}
?>
I'm pretty sure what i'm asking is really simple, i just can't get my head around acheieving it.
Thanks to you both for your answers, but i have managed to fix it (or work-around it) with this on my index page:
<?php
$query="SELECT * FROM $tbl_name ORDER BY job_id DESC";
$result=mysql_query($query) or die(mysql_error());
$rsjobinfo=mysql_fetch_assoc($result);
mysql_close();
do {?>
<div class = "hjl"><a href="paging.php?job_id=<?php echo $rsjobinfo['job_id'];?>">
<ul>
<li id = "jobtitle"><?php echo $rsjobinfo['job_title'];?></li><br />
<li id = "compname"><?php echo $rsjobinfo['company_name'];?></li>
</ul>
<ul>
<li id = "city"><?php echo $rsjobinfo['city'];?>,
<?php echo $rsjobinfo['country'];?></li>
</ul>
</a>
</div>
<?php } while ($rsjobinfo=mysql_fetch_assoc($result))?>
</div>
Followed by this on my content page:
<?php
$job_id = $_GET['job_id'];
$query="SELECT * FROM $tbl_name WHERE job_id = $job_id";
$result=mysql_query($query) or die(mysql_error());
$rsjobinfo=mysql_fetch_assoc($result);
mysql_close();
?>
Thanks for your help everyone.
Dan
put mysql_close after you use mysql_result, but once you get it working you might look into a more modern approach like PDO.
to your code add link (which I think you already have somewhere):
//...................
<li id = "jobtitle">
<a href="<?php echo '?id='.$job_id; ?>">
<?php echo $f2; ?>
</a>
</li>
//...................
Read more...
//...................
then your code must check for variable $_GET['id'], so put IF in the beginning of your code:
$where = '';
if( isset($_GET['id']) && strlen($_GET['id']) > 0 ) {
$where = ' job_id = "'. mysql_real_escape_string( $_GET['id'] ) .'"' ;
}
<?php
$query="SELECT * FROM $tbl_name $where ORDER BY job_id DESC";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"company_name");
$f2=mysql_result($result,$i,"job_title");
$f3=mysql_result($result,$i,"city");
$f4=mysql_result($result,$i,"country");
$job_id=mysql_result($result,$i,"job_id");
?>
<div class = "hjl">
<ul>
<li id = "jobtitle">
<a href="<?php echo '?id='.$job_id; ?>">
<?php echo $f2; ?>
</a>
</li><br />
<li id = "compname"><?php echo $f1; ?></li>
</ul>
<ul>
<li id = "city"><?php echo $f3; ?>, <?php echo $f4; ?></li><br />
</ul>
Read more...
</div>
<?php
$i++;
}
?>
edit: Try changing the following line:
$where = " job_id = '". mysql_real_escape_string( $_GET['id'] ) ."'" ;

Categories