How can display variable only once? - php

i have a list of page order by id .Example:
example.com/a?id=4
example.com/a?id=3
example.com/a?id=2
In every page a have string {order_id} Now i want first time load page it replace {order_id} with the id in url , from the second time it replace with empty string
in my code , it only work when i refresh the page with the same url ( example.com/a?id=4 and reload it ) but go to ( example.com/a?id=3 then go back example.com/a?id=4 it's not work) . Here is my code :
$id=$_POST['id'];
if(isset($_SESSION['orderid']) && $_SESSION['orderid'] == $id){
$this->mOutPut = str_replace('{order_id}',"", $this->mOutPut);
}else{
$this->mOutPut = str_replace('{order_id}',$id, $this->mOutPut);
}
session_start();
$_SESSION['orderid'] = $id;

Try:
session_start();
$id=$_POST['id'];
if(isset($_SESSION['orderid']) && $_SESSION['orderid'] == $id){
$this->mOutPut = str_replace('{order_id}',"", $this->mOutPut);
}else{
$this->mOutPut = str_replace('{order_id}',$id, $this->mOutPut);
}
$_SESSION['orderid'] = $id;

Related

Add more data into cookie in PHP

I have a cookie and I'm storing multiple checked checkbox values of page1 in this. Now I want to add more checked checkbox values into the cookie of page2 and then page3 and so on (I'm using pagination in my code). How can I do that in PHP?
<?php
$cookiename = "emp";
if (isset($_GET['check_list']) ) {
setcookie($cookiename , implode(',' , $_GET['check_list']) ,
time()+(86400/86400*30) );
}
?>
//to print the values
<?php
if (isset($_COOKIE[$cookiename]) ) {
print_r($_COOKIE);
}
?>
Maybe in this way:
<?php
$page = $_GET['page'];
$cookiename = "emp";
// GET COOKIE TO NOT OVERWRITE.
$cookie = isset($_COOKIE[$cookiename]) ? unserialize($_COOKIE[$cookiename]) : [];
if (isset($_GET['check_list']) ) {
$cookie[$page] = $_GET['check_list'];
setcookie($cookiename , serialize($cookie), time()+(86400/86400*30) );
}
?>
//to print the values
<?php
if (isset($_COOKIE[$cookiename]) ) {
print_r(unserialize($_COOKIE[$cookiename]));
}
?>
With unserialize you can store a multiple dimension array into a cookie with no problem.

Passing array of data to other page using session in PHP

I have some problem passing array of data in Php using session:
In my class, I have this function:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
if($this->num_rows == 1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id = $this->row[0];
return $dup_id;
}
}
}
This code checks for duplicate ID of a student. Now, the reason for this is that I uploaded the file in the database using ".csv" file.
Before Uploading it I put all the data in the csv file into an array. Now, I check it one by one:
//created the variable for checking
$id = $check->check_dupID($array[0]);
if($id == TRUE)
{
session_start();
$_SESSION['id']; = $id;//passing it to the next back to array again.
$redirect->page($error);
}
Now when it redirect it gives me the result of an "Array" and if I parse it using foreach it shows only one id but there is more than of that. I want to know how to display it all.
This code will return the duplicate id when it is found for the first time. If you want to return all the duplicate ids, then add them into an array using the while loop and then return it.
To do this modify your code like this:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
$dup_id = array();// added here to prevent invalid argument supplied to foreach loop error if nothing is found
if($this->num_rows >1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id[] = $this->row[0];// adding duplicates into the array
}
return $dup_id;
}
}
This code fixes my problem:
if($id == TRUE)
{
$get_id = array();
$get_id[] = $id;
session_start();
$_SESSION['id']; = $get_id;//passing it to the next back to array again.
$redirect->page($error);
}

Creating an unlock/lock page feature

I am trying to create something like a lock and unlock pages feature. The user has to go thorugh the pages in this order:
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
So what should happen is that if the user is on a page a they SHOULD BE on, then that page shold be unlocked (or in other words the if statement is met where it shows the page's code), if the user accesses a page which they should not be on, then that page beocmes locked (the else statement is met where it displays the div with the Continue hyperlink`).
The problem is that even though the user is on the correct page, the page is still "locked" when it should be unlocked so the user can use the page. At moment all pages accessed are locked so my question is that how can I unlock a page when the user is on a correct page?
Below is an example create_session.php:
<?php
session_start();
include ('steps.php'); //exteranlised steps.php
?>
<head>
...
</head>
<body>
<?php
if ((isset($username)) && (isset($userid))) { //checks if user is logged in
if (allowed_in() === "Allowed") {
//create_session.php code:
} else {
$page = allowed_in() + 1;
?>
<div class="boxed">
Continue with Current Assessment
<?php
}
} else {
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
//show above echo if user is not logged in
}
?>
Below is the full steps.php:
<?php
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
function allowed_in($steps = array()){
// Track $latestStep in either a session variable
// $currentStep will be dependent upon the page you're on
if(isset($_SESSION['latestStep'])){
$latestStep = $_SESSION['latestStep'];
}
else{
$latestStep = 0;
}
$currentStep = basename(__FILE__);
$currentIdx = array_search($currentStep, $steps);
$latestIdx = array_search($latestStep, $steps);
if ($currentIdx - $latestIdx == 1 )
{
$currentIdx = $_SESSION['latestStep'];
return 'Allowed';
}
return $latestIdx;
}
?>
Something like this, though this probably won't work as is:
$allowed_page = $_SESSION['latestStep'];
if ($steps[$allowed_page] == $_SERVER['SCRIPT_NAME']) {
... allowed to be here ...
}
Basically, given your array of "steps", you store the index of the allowed page in the session as you. As they complete a page and "unlock" the next page, you increment that index value in your session and redirect to the next page in the sequence.
if ($page_is_done) {
$_SESSION['latestStep']++;
header("Location: " . $steps[$_SESSION['latestStep']]);
}
Keep it simple, seems that you are over complicating the goal. It seems like you simply want to ensure that the user completes previous steps of a process before they can continue on to the next. Why not try something more like...
// General Idea
$completedArr = array('1' => false, '2' => false ...);
$pageMap = array('page1.php' => '1', 'page2.php' => '2' ...);
// On Page1
$completedArr = $_SESSION['completedArr'];
$locked = true;
$currentStep = $pageMap[$_SERVER['SCRIPT_NAME']]; // '1'
if($currentStep > 1)
{
if($completedArr[$currentStep - 1] === true)
$locked = false;
}
else
{
$locked = false;
}
$completedArr[$currentStep] = true;
$_SESSION['completedArr'] = $completedArr;
Use this as needed for continuous pages also. The idea is that the pageMap you would define to give index numbers to script names. Then you would simply check to see that the previous index was marked as completed before "unlocking" this page.

PHP/SQL syntax: passing variable to SQL query

I am getting tired trying to see what is wrong. I have two php. From the first I am sending a variable 'select1' (basically the id) to the second and than I want to update that record uploading a pdf file.
$id = "-1";
if (isset($_GET['select1'])) {
$id = mysql_real_escape_string($_GET['select1']);
}
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file
mysql_query(sprintf("UPDATE sarcini1 SET file_name = '%s' WHERE id_sarcina = '%s'", $my_upload->file_copy, $id));
}
}
If I put a line with a valid id, like:
$id = 14;
it is working. What I am doing wrong? Thank you!
If you need to accept both post & get, then you should try something like the code below to retrieve the variable.
$var = 'select1';
if( isset( $_POST[$var] ) ) {
$id = $_POST[$var];
} else if( isset( $_GET[$var] ) ) {
$id = $_GET[$var];
} else {
$id = -1;
}
You are using both GET and POST at the same time. As far as I can see, this condition is not returning True
if (isset($_GET['select1']))
Edit: If you don't find any answer in above; maybe some more information/code can help getting to a solution.

How do you maintain page number after redirect in CakePHP?

I have an index view that lists items, and it's a long list so I use Paginator to limit items to 50-to-a-view.
Each item has an "edit" link that goes to an edit view with inputs/validations/etc. When that form is submitted, I redirect the use back to the index view.
So far so good, but here's the rub:
If a user is on page N of the index and they click edit and edit an item, I want them to be redirected back to page N of the index. If I knew the page number, I could just stick "/page:N" on to end of the URL, but I have no idea how I can get the page number. (N could be any page number, but especially >=2)
Any ideas would be appreciated.
The page number should be part of the $params var in the list view. Just tack it onto the end of the edit link and handle it from there. On the edit page you will need a way to take in the optional page number, store it during any form submission, and forward back to the list with the same page number.
I created a component that saves the page in the session. Then in the app_controller.php, I check to see if there is anything in the session for the particular model being used and then add that to the url. If you are interested in the code for the component, message me. I also store the order, if the user changed the sort order in the index page before editing.
See here for the source:
http://github.com/jimiyash/cake-pluggables/blob/a0c3774982c19d02cfdd19a2977eabe046a4b294/controllers/components/memory.php
Here is the gist of what I am doing.
//controller or component code
if(!empty($params['named']) && !empty($params['controller']) && $params['action'] == 'admin_index'){
$this->Session->write("Pagem.{$params['controller']}", $params['named']);
}
//app_controller.php
$redirectNew = "";
if(is_array($redirectTo)){
if(!empty($params['prefix']) && $params['prefix'] == 'admin'){
$redirectNew .= '/admin';
}
if(!empty($params['controller'])){
$redirectNew .= "/" . $params['controller'];
}
if(!empty($redirectTo['action'])){
$redirectNew .= "/" . $redirectTo['action'];
}
} else {
$redirectNew = $redirectTo;
}
$controller = $params['controller'];
if($this->Session->check("Pagem.$controller")){
$settings = $this->Session->read("Pagem.$controller");
$append = array();
foreach($settings as $key=>$value){
$append[] = "$key:$value";
}
return $redirectNew . "/" . join("/", $append);
} else {
return $redirectNew;
}
If I understand correctly, the above is fine for editing, but not for adding. This solution should work for both situations:
In your controllers or your /app/app_controller.php, put in something like this for adding:
$insertID = $this->{$this->modelClass}->getLastInsertID();
$page = $this->{$this->modelClass}->getPageNumber($insertID, $this->paginate['limit']);
$this->redirect("/admin/{$controllerName}/index/page:{$page}");
...and something like this for editing:
$page = $this->{$this->modelClass}->getPageNumber($id, $this->paginate['limit']);
$this->redirect("/admin/{$controllerName}/index/page:{$page}");
In your /app/app_model.php, put in this:
/**
* Work out which page a record is on, so the user can be redirected to
* the correct page. (Not necessarily the page she came from, as this
* could be a new record.)
*/
function getPageNumber($id, $rowsPerPage) {
$result = $this->find('list'); // id => name
$resultIDs = array_keys($result); // position - 1 => id
$resultPositions = array_flip($resultIDs); // id => position - 1
$position = $resultPositions[$id] + 1; // Find the row number of the record
$page = ceil($position / $rowsPerPage); // Find the page of that row number
return $page;
}
Hope that helps!
Does a simple
$this->redirect($this->referer());
works?
In view with paginator:
<?php
if ($this->Paginator->hasPage(null, 2)) {
$pag_Start = $this->Paginator->counter('{:start}');
$pag_End = $this->Paginator->counter('{:end}');
if( $pag_Start == $pag_End ){
$pageToRedirect = $this->Paginator->current('Posts');
}else{
$pageToRedirect= '';
}}?>
Then link to edit page
<?php
echo $this->Form->postLink(
'Edit',
array('action' => 'edit', $subscription['Post']['id']));
?>
In controller:
public function edit($post_id, $pageToRedirect = false){
//after all editing its done redirect
if($pageToRedirect){
// if record was last in pagination page redirect to previous page
$pageToRedirect = $pageToRedirect -1;
return $this->redirect(array('action' => 'index/page:'.$pageToRedirect ));
}else{
// else redirect to the same pagination page
$this->redirect($this->referer());
}
}

Categories