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.
Related
Currently I have a permissions table where the user can use a checkbox to give access or revert access for a URL link to a user with a particular role. So for this I've made it so that when a checkbox is pressed, the id of that checkbox and the role of the user are inserted in my database, but I'm unable to insert it in the database for some reason. I've tried the following code:
Controller Class:
public function permission()
{
if ($this->form_validation->run() == FALSE)
{
$main['permissions']=$this->users_model->get_permission_array();
$main['roles']=$this->users_model->get_roles_array();
foreach($main['roles'] as $key => $val):
$main['access'][$val['roles_id']]=$this->users_model->get_access_array(array('roles_id'=>$val['roles_id']));
endforeach;
$main['page'] = 'crm/users/permission';
$this->load->view('crm/index', $main);
}
if($this->input->post())
{
$loginid=false;
foreach($main['roles'] as $key => $val):
if(isset($_POST['roleid'.$val['roles_id']])){
$this->users_model->clear_access(array('roles_id'=>$val['roles_id']));
foreach($_POST['roleid'.$val['roles_id']] as $id => $access):
$data=array('roles_id'=>$val['roles_id'],'permissions_id'=>$access);
$loginid=$this->users_model->permission_access($data);
endforeach;
}
endforeach;
if($loginid){
$this->session->set_flashdata('message', '<p>Permission updated Successfully.</p>');
redirect('users/permission');
} else {
$this->session->set_flashdata('message', '<p>Error!! - Permission not updated.</p>');
redirect('users/permission');
}
}
}
Model Class:
function get_permission_array()
{
$query = $this->db->get("crm_client_permissions");
return $query->result_array();
}
function get_access_array($cond)
{
$this->db->select("permissions_id");
$this->db->where($cond);
$query = $this->db->get("crm_client_role_access");
return $query->result_array();
}
function clear_access($cond)
{
return $this->db->delete("crm_clients_access",$cond);
}
function permission_access($data)
{
return $this->db->insert("crm_clients_access",$data);
}
function get_roles_array($cond='')
{
if($cond !='') $this->db->where($cond);
$query = $this->db->get("crm_client_roles");
return $query->result_array();
}
View Class:
<div <?php echo form_open_multipart('users/permission'); ?>>
<table>
<?php if($permissions) $i=0;foreach($permissions as $key => $permission): ?>
<tr>
<td class="align-center"><?php echo ++$i; ?></td>
<td><?php echo $permission['page']; ?></td>
<td><?php echo $permission['url']; ?></td>
<?php foreach($roles as $rolekey => $role):
if($role['roles_id'] == 1)$checked = 'checked';
if(in_array($permission['permissions_id'],array_map('current',$access[$role['roles_id']])))
$checked = 'checked';
else
$checked = ''; ?>
<td align="center"><div class="checkbox checkbox-success m-t-0"><input type="checkbox" class="accessbox"
id="role<?php echo $rolekey ?>-<?php echo $key ?>" name="roleid<?php echo $role['roles_id']; ?>[]"
<?php echo $checked?> <?php echo ($role['roles_id'] == 1) ? 'disabled="disabled"' : '' ?> value="<?php echo $permission['permissions_id']; ?>" />
<label for="role<?php echo $rolekey ?>-<?php echo $key ?>"></label></div></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<div class="text-center">
<button type="submit" class="btn btn-info">Save Permission</button> Cancel
</div>
<?php echo form_close(); ?> </div>
But here I always get Error!! - Permission not updated. in my view class which means it jumps to the else part of my controller. I'm not sure where I'm going wrong here
It seems problem is here $loginid=$this->users_model->permission_access($data); and here return $this->db->insert("crm_clients_access",$data);.
My advise is to:
use XDebug to debug your code and see what insert function returns and why.
Also you may look for php log to see if there is any database errors. To use error logs you need to find php.ini config file and enable line 'error_log = /path/to/fige.log'.
Also you may to lookup the database data to determine if insert function makes new row in table crm_clients_access, if it doesn't? you need to check your connection config to database host:port, so database process must be available at theese host:port.
I am unable to display data from a table from a MYSQL database using PHP OOP. However, I'm not sure if I'm unable to display the data because I'm not actually fetching the data in the first place.
I've tried fetching and displaying the data using only a PHP array and no HTML in my method and I figured this wouldn't be working because I wasn't using HTML list tags to format the data from the database. I've considered using a HTML table but I have seen displays from databases using lists work a few times before and I want to know why this doesn't work how it should.
I've tested for MYSQL connection and it does exist.
* M_PRODUCTS.PHP *
<?php
class Products
{
private $Conn;
private $db_table = "toys";
function __construct() {
// here we're making sure that the connection from $conn in "init.php" is transferred
// into our own private $conn property for usage in this object
global $Conn;
$this->Conn = $Conn;
}
// fetches and displays all products from db
public function fetch_all_products($id = NULL)
{
if ($id == NULL)
{
$data = [];
if ($result = $this->Conn->query("SELECT * FROM " . $this->db_table . " ORDER BY name"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data = array(
"id" => $row["product_id"],
"name" => $row["name"],
"price" => $row["price"],
"image" => $row["image"]
);
}
return $data;
}
else
{
return "<h1>Oops... Something went wrong!</h1>";
}
}
}
}
}
* INDEX.PHP *
<?php include("init.php");
include("models/m_products.php");
?>
<body>
<div id="whitespace">
<?php
$products = fetch_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I expect the images of my products to be displaying in my index.html file. However, nothing appears.
I also get this error message in the JavaScript console: Failed to load resource: the server responded with a status of 404 (Not Found). This would explain a lot but as I said I tested my database connection and it works. I'm not sure how or why this message is coming from the JavaScript console if I'm not using JavaScript. I thought it would be worth mentioning anyway.
According to your code the function returns some data, but the thing is that you have not printed it, so instead of return in the function you can use echo or just put
echo $Products->fetch_all_products();
Strange code, I would do something like that.
1. First the function find all()
2. index.php echo - output
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" width="200" /></td>
</tr>
<?php } ?>
There are 2 major issues I can see in your code
1) you need to update your comparison operator from
if ($id = NULL)
to
if ($id == NULL)
2) you need to update your code in index.php from
<body>
<div id="whitespace">
<h1><?php echo shop_name ?></h1>
<?php
echo $Products->fetch_all_products();
?>
</div>
</body>
to
<body>
<div id="whitespace">
<?php
$products = find_all_products();
?>
<?php foreach($products as $row) { ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->price; ?></td>
<td><img src="<?php echo $row->image_path(); ?>" alt="<?php echo $row->name; ?>" width="100" /></td>
</tr>
<?php } ?>
</div>
</body>
I hope it will sort out your issue
Correct your comparison operator it should be.
if ($id == NULL)
instead of
if ($id = NULL)
in your function fetch_all_products().
correct the code in index.php to print an array use print_r() or loop through the result array.
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.
I am trying to make a site using cakephp and twitter bootsrap. For the gallery I am making I am trying to display, using foreach, multiple images , but they simply don't show up. Everything is working, the foreach and the variable data, but the echos don't display anything. Could anyone help please?
Thanks in advance.
(code bellow from my show_images.ctp view)
<table >
<tr>
<?php
$i=0;
foreach( $gallery_images as $gallery_image ):?>
<td align=center>
<?php echo "<a id=\"single_1\" href=\"test/".$gallery_image['GalleryImage']['path']." ";?>
<?php echo "<img src=\"test/".$gallery_image['GalleryImage']['path'].", alt=\"".$gallery_image['GalleryImage']['path']."";?>
<?php echo "</a>";?>
</td>
<?php $i++;?>
<?php
if($i==4){
echo "</tr><tr>";
$i=0;
}
?>
<?php endforeach ?>
</tr>
you haven't close your tag inside echotry to change this:
<?php echo "<a id=\"single_1\" href=\"test/".$gallery_image['GalleryImage']['path']." ";?>
<?php echo "<img src=\"test/".$gallery_image['GalleryImage']['path'].", alt=\"".$gallery_image['GalleryImage']['path']."";?>
<?php echo "</a>";?>
to this:
<?php echo '<a id="single_1" href="test'.$gallery_image['GalleryImage']['path'].' >';?>
<?php echo '<img src="test'.$gallery_image['GalleryImage']['path'].'" alt="'.$gallery_image['GalleryImage']['path'].'" />';?>
<?php echo '</a>';?>
<marquee behavior="alternate" scrolldelay="1" scrollamount="2">
<?php do { ?>
<?php echo $row_Recordset1['Name']; ?>:
<?php echo $row_Recordset1['Text']; ?>
•
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</marquee>
<?php mysql_free_result($Recordset1); ?>
Print a friendly message to the user instead of NULL:
<?php echo (NULL === $row_Recordset1['Text']) ? "No value" : $row_Recordset1['Text']; ?>
As xil3 illustrates, you can also use this pattern (from the docs):
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
The way you have it written right now, $row_Recordset1 will be null the first time it goes into the loop.
I've rewritten it for you:
<marquee behavior="alternate" scrolldelay="1" scrollamount="2">
<?php while($row_Recordset1 = mysql_fetch_assoc($Recordset1)) { ?>
<?php echo (($row_Recordset1['Name'] != null) ? $row_Recordset1['Name'] : 'n/a'); ?>:
<?php echo (($row_Recordset1['Text'] != null) ? $row_Recordset1['Text'] : 'n/a'); ?>
•
<?php } ?>
</marquee>
<?php mysql_free_result($Recordset1); ?>