I’m building a system that captures info from a POST method and adds them into a PHP $_SESSION. The basic logic I want to follow is:
Check the method and call the relevant function
Check if $_SESSION data already exists via a function
Check if the $post_id variable is already in the $_SESSION's array via a function
Based on the outcomes on these functions, add to the array, create a new array, or do nothing
Here is the code I have written to handle this logic so far. I am looking to get just the add_to_lightbox() function working first, and will move onto the other two after.
session_start();
// set variables for the two things collected from the form
$post_id = $_POST['id'];
$method = $_POST['method'];
// set variable for our session data array: 'ids'
$session = $_SESSION['ids'];
if ($method == 'add') {
// add method
add_to_lightbox($post_id, $session);
} elseif ($method == 'remove') {
// remove method
remove_from_lightbox($post_id);
} else ($method == 'clear') {
// clear method
clear_lightbox();
}
function session_exists($session) {
if (array_key_exists('ids',$_SESSION) && !empty($session)) {
return true;
// the session exists
} else {
return false;
// the session does not exist
}
}
function variable_exists($post_id, $session) {
if (in_array($post_id, $session)) {
// we have the id in the array
return true;
} else {
// we don't have the id in the arary
return false;
}
}
function add_to_lightbox($post_id, $session) {
if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
// add the id to the array
array_push($session, $post_id);
var_dump($session);
} else {
// create a new array with our id in it
$session = [$post_id];
var_dump($session);
}
}
It's stuck in a state where it's always getting to add_to_lightbox() and following the array_push($session, $post_id); each time. I’m unsure whether this code I’ve written is possible because of the nested functions, and how I can refactor it to get the functionality working.
Correction from before, seems like $session is an array of ids..
The problem you are having is that you're modifying the local copy of that array within add_to_lightbox function. You don't need to specifically instantiate the variable as an array, you can just use the following.
$_SESSION['ids'][] = $post_id;
Related
I am trying to use a php function to get the prices of a tola (11.664 grams) at an order status page. The function uses a php page 'priceApi4CurCtrl.php' that fetches the price data from a website using an external API. My function is as follows:
function tolaPrice($cur_pick) {
require('priceApi4CurCtrl.php');
if($cur_pick == 'pkr') {
$tola_price = $bitprice_pkr*10*11.664;
return $tola_price;
} elseif($cur_pick == 'usd') {
$tola_price = $bitprice_usd*10*11.64;
return $tola_price;
} elseif($cur_pick == 'aed') {
$tola_price = $bitprice_aed*10*11.64;
return $tola_price;
}
}
// Succeeds for the first call as under
$cur_pick = 'pkr';
echo tolaPrice($cur_pick);
// Fails for the second call as under
$cur_pick = 'aed';
echo tolaPrice($cur_pick);
The function works fine for the first call using echo tolaPrice($cur_pick). However, it fails all subsequent calls and hence I am unable to complete the order status of second and subsequent orders.
I am not sure how to work around this.
Instead of trying to wrap an if else loop in a function, I simply calculated the prices in a separate file named tola_price.php as follows:
include('priceApi4CurCtrl.php');
$tola_price_pkr = $bitprice_pkr*10*11.664;
$tola_price_usd = $bitprice_usd*10*11.64;
$tola_price_aed = $bitprice_aed*10*11.64;
And then called the tola_price.php within my script with if else loop as follows:
require_one('tola_price.php');
if($cur_pick == 'pkr') {
$tola_price = $tola_price_pkr;
} elseif($cur_pick == 'usd') {
$tola_price = $tola_price_usd;
} elseif($cur_pick == 'aed') {
$tola_price = $tola_price_aed;
}
And then used the prices to build further script.
Thanks to those who offered help
I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.
I'm trying to create callback script for Coinbase bitcoin payments. Here is the below function from my payment controller. But somehow the key isn't working as it should. I am trying to access it like that: http://www.example.com/payments/callback?key=true but it's not getting affected basically not working. Take a note that the script is working itself but after adding the key function and validating it ... it's not anymore. The issue is caused by that but I don't know what exactly, so what may cause that in the script below?
Thanks for taking the time to check and possibly answer my question.
function is_valid_key($key) {
// logic to check key
$valid = true;
if($valid) {
return true;
}
else {
return false;
}
}
function callback()
{
//Check if key is valid.
$key = $this->input->get('key');
if( ! $this->is_valid_key($key)) {
//If key above is valid order is "completed", please proceed.
$data = json_decode(file_get_contents('php://input'), TRUE);
$status = $data['order']['status'];
$userid = '507';
if (($status === 'completed')) {
$this->db->query( 'update users set user_money=user_money+15, user_credits=user_credits+5 WHERE users_id=' . $userid );
}
}
}
it has to do with your configuration settings. check out this question Enabling $_GET in codeigniter
Also you can use
parse_str($_SERVER['QUERY_STRING'], $_GET);
which would push GET right back on
Im using CodeIgniter to write a site ... I understand $_GET requests are now used like so www.website.com/function/value .. and in the controller getting a url segment is written like so:
$userId = $this->uri->segment(3, 0);
Im just wondering, when a controller loads, i want to check if there is any uri segments, if there is then push to one view, else if there isnt a uri segment push to another.
Is that possible?
cheers.
You can use your controller arguments for that too.
When accessing /user/profile/1 your controller named User will call the method profile() and pass the number 1 as the first argument to your method. Like so:
class User extends CI_Controller {
{
public function index()
{
$this->load->view("user_index");
}
public function profile ( $userId = null )
{
if( (int)$userId > 0 )
$this->load->view("user_profile");
else
$this->load->view("another_view");
}
}
This is a very basic sample and I'm just trying to show the idea.
Seems like your asking two questions...
First, to check if the request is get
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
echo "GET";
}
else
{
//do something not get
echo "NOT GET";
}
}
The next question seemed to be checking uri segments
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
//echo "GET";
if($this->uri->segment(3)) //is true as is not empty
{
echo $this->uri->segment(3);
}
else
{
echo "I am nothing without my URI Segment";
}
}
else
{
//do something not get
echo "NOT GET";
}
}
As I understand you can use PHP default value.
function myFunction($var1 = NULL) {... if($var1 === NULL) ...}
Now if you do not pass the param you will get the NULL value.
I am still not using version 2 of codeigniter but this framework do not accept get requests; unless you mess with the configuration. Theres a function $this->input->get('myGet') you should look around at de the codeigniter.com/user_guide
I'm gonna make this too complicated, just going to break it down to the main parts.
I have a form that changes the boolean of a variable when the form gets submitted, however it gets called by a function, the function has to change the variable.
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
}
}
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true. When I do var_dump($up->yesno), it says false when it should be true. If I do this:
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
var_dump($this->yesno); // <-- outputs true
}
}
So how come I cannot get the variable to print out true in a seperate script?
EDIT:
$sql = "SELECT boolean
FROM config
WHERE boolean = 'true'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$up->updateBool();
}
else
{
header("Location: index.php?d=none");
}
This is part of the code where it gets called. I can confirm there are more than 1 record in the SQL statement.
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true
You seem to be switching to a new page, where $up will be a new object. Objects do not persist across requests. PHP "loses its memory" when you call a new page, and all variables are started from scratch.
To persist values across page requests, you would need to use something like sessions.
class updates
{
public $yesno;
function __construct(){
$this->yesno = false;
}
function updateBool()
{
$this->yesno = true;
}
}