Error with session ini setting modification - codeigniter-3

A PHP Error was encountered
Severity: Warning
Message: ini_set(): A session is active. You cannot change the session module's ini settings at this time
Filename: Session/Session.php
Line Number: 316
Backtrace:
File: C:\xampp\htdocs\testing\index.php
Line: 315
Function: require_once
<?php
session_start(); //we need to start session in order to access it through CI
class Adminlogin extends CI_Controller {
public function _construct(){
parent::_construct();
//Load form helper library
$this->load->helper('form');
//Load form validation library
$this->load->library('form_validation');
//Load session library
$this->load->library('session');
//Load database
$this->load->model('login_database');
}
//show login page
public function index()
{
$this->load->view('admin_login');
}
//show registration page
public function user_registration_show(){
$this->load->view('admin_signup');
}
//Validate and store registration data in database
public function new_user_registration(){
//Check Validation for user input in SignUp form
$this->form_validation->set_rules('admin_username', 'Username','trim|required|xss_clean');
$this->form_validation->set_rules('admin_password', 'Password','trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$this->load->view('admin_signup');}
else{
$data = array(
'admin_username' => $this->input->post('username'),
'admin_password' => $this->input->post('password'));
$result = $this->login_database->registration_insert($data);
if($result == TRUE){
$data['message_display'] = 'Registration Successfully !';
$this->load->view('admin_login', $data);
}else{
$data['message_display'] = 'Username already exist';
$this->load->view('admin_signup',$data);
}
}
}
//Check for user login process
public function user_login_process(){
$this->form_validation->set_rules('admin_username','Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('admin_password','Password', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
if(isset($this->session->userdata['loggen_in'])){
$this->load->view('Admin/admin_dashboard');
}else{
$this->load->view('admin_login');
}
}else{
$data = array(
'admin_username' => $this->input->post('username'),
'admin_password' => $this->input->post('password'));
$result = $this->login_database->login($data);
if($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if($result != false){
$session_data = array(
'username' => $result[0]->admin_username,
'password' => $result[0]->admin_password);
//Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('Admin/admin_dashboard');
}else{
$data = array(
'error_message' => 'Invalid Username or Password');
$this->load->view('admin_login',$data);
}
}
}
}
}
?>

Please remove the 1st line session_start(); or change it to..
// session_start(); //I do Not need this as I am using CI Sessions.
You are using CodeIgniters Sessions which you have loaded in your code...
$this->load->library('session');
As an Aside:
You don't need the end ?> in your PHP files where it is the last tag in the file.

Related

Phalcon MongoDb save

I have problem with save method of collections in Phalcon.It doesn't work and doesn't give me any errors or something.I want to create a Micro App with mongoDb:
Phalcon version: 1.3.4
php : 5.5.9
Here are the registered services:
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Assets\Manager as AssetsManager,
Phalcon\Mvc\Collection\Manager as CollectionManager,
Phalcon\Mvc\View\Simple as View,
Phalcon\Mvc\View\Engine\Volt,
Phalcon\Mvc\Url as UrlResolver,
Phalcon\Flash\Session as Flash,
Phalcon\Flash\Direct as FlashDirect,
Phalcon\Session\Adapter\Files as Session;
$di = new FactoryDefault();
$di['url'] = function () {
$url = new UrlResolver();
$url->setBaseUri('/dasshy/');
return $url;
};
/**
* Flash service with custom CSS classes
*/
$di['flash'] = function () {
return new Flash(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
/**
* Flash service with custom CSS classes
*/
$di['flashDirect'] = function () {
return new FlashDirect(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
$di['session'] = function () {
$session = new Session(array(
'uniqueId' => 'dasshy-'
));
$session->start();
return $session;
};
$di['mongo'] = function () {
$mongo = new MongoClient();
return $mongo->selectDb("stats");
};
$di->set('collectionManager', function () {
return new Phalcon\Mvc\Collection\Manager();
});
I want to use the ODM, so here is the model Collection:
<?php
namespace Dasshy\Models;
class Messages extends \Phalcon\Mvc\Collection
{
public $content;
public $senderId;
public $receiverId;
public $date;
}
And here how i use it at handlers.php:
<?php
use Dasshy\Models\Messages;
use Phalcon\Mvc\Micro\Collection;
$app->map('/send/{receiverId}/{senderId}/{content}', function ($receiverId, $senderId, $content) use ($app) {
$messageModel = new Messages();
$messageModel->receiverId = $receiverId;
$messageModel->senderId = $senderId;
$messageModel->content = $content;
$messageModel->date = date('Y-m-d H-i-s', time());
$messageModel->save();
if ($messageModel->save() == false) {
echo "Umh, We can't store robots right now: \n";
foreach ($messageModel->getMessages() as $message) {
echo $message, "\n";
}
} else {
echo "Great, a new robot was saved successfully!";
}
});
$app->map('/messages', function () use ($app) {
var_dump(Messages::find());
exit;
});
you need to setup the mongo connection on the service...
$config = $di->getShared('config')->mongo;
$connect_data = $config->username . ':' . $config->password . '#' . $config->host . ':' . $config->port . '/' . $config->dbname;
$mongo = new \MongoClient("mongodb://" . $connect_data);
return $mongo->selectDB($config->dbname);
...since you are not connecting to any mongo server

Jquery Notification on Ajax POST Success

I have an issue with a some of the jQuery notifications I have created to trigger based on information echo'd from a PHP file after a user submits a sign up HTML form via AJAX. The notifications for errors work, but not for a successful post to the database. I know that the success notification should show because the data is validated and written to the database and AJAX post is successful. However the success notification does not want to work. What could be the reason for this technicality?
I have the following set up:
signup.html (contains the following ajax within the page*):
function registerUser(formKey) {
$.ajax({
type:"POST",
url:"engine/new_user.php",
data: $("#"+formKey).serialize(),
cache:false,
success: function(data) {
if(data == -3){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#user-exists-notification").fadeIn(1000);
}
if(data == -4){
$("#account-created").fadeIn(1000);
}
if(data == -1){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#fields-complete-notification").delay(1000).fadeIn(1000);
}
if(data == -2){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#pw-confirm-notification").delay(1000).fadeIn(1000);
}
},
error: function(data) {
}
});
}
new_user.php
require("register-classes.php");
$register=new Register($_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['sex'], $_POST['birthdate'], $_POST['phone'], $_POST['country'], $_POST['alias'], $_POST['handle'], $_POST["password"], $_POST["cpassword"], $_POST['network']);
if($register->checkFields()== false){
echo -1;
} else if($register->confirmPasswords()== false){
echo -2;
}else if($register->registerUser()!=false){
echo -4;
} else if($register->registerUser()==false){
echo -3;
}
and register-classes.php (which contains classes for processing sign up form)
class Register {
public function __construct($fname, $lname, $mail, $sex,
$birthday, $phonenumber, $regCountry, $alias, $username,
$password, $conf_password, $network_site) {
//Copy Constructor
$this->site=$network_site;
$this->firstname=$fname;
$this->lastname=$lname;
$this->email=$mail;
$this->sex=$sex;
$this->birthdate=$birthday;
$this->phone=$phonenumber;
$this->country=$regCountry;
$this->displayname=$alias;
$this->handle=$username;
$this->salt="a2cflux9e8g7ds6ggty589498j8jko007876j89j8j7";
$this->password=crypt($this->salt.$password);
$this->joindate=date("Y-m-d H:i:s");
$this->confirm_password1=$password;
$this->confirm_password2=$conf_password;
}
public function registerUser(){
$database=new Database();
$database->getConnection();
$database->startConnection();
//Check database to insure user and email address is not already in the system.
$checkUsers= mysql_query("SELECT network_users.network_id
FROM network_users, network_profile
WHERE network_users.handle = '$this->handle'
OR network_profile.email = '$this->email'");
$numRecords= mysql_num_rows($checkUsers);
if($numRecords == 0){
$addUser= mysql_query("INSERT INTO network_users(handle, password, date_created, parent_network, site_created, active, account_type, del)
values('$this->handle', '$this->password', '$this->joindate',' fenetwork', 'network', 'active', 'standard', 'F')") or die(mysql_error());
$networkId=mysql_insert_id();
$addProfile= mysql_query("INSERT INTO network_profile(network_id, first_name, last_name, email, sex, birthdate, phone, country, display_name, del)
values('$networkId', '$this->firstname', '$this->lastname', '$this->email','$this->sex', '$this->birthdate', '$this->phone', '$this->country', '$this->displayname', 'F')") or die(mysql_error());
$this->addUser;
$this->addProfile;
return true;
}
else{
return false;
}
}
public function checkFields(){
if(($this->firstname)!="" && ($this->lastname)!="" && ($this->email)!="" && ($this->sex)!="" &&
($this->birthdate)!="" &&($this->country)!="" && ($this->handle)!="" && ($this->password)!=""){
return true;
} else {
return false;
}
}
public function confirmPasswords(){
if($this->confirm_password1==$this->confirm_password2){
return true;
} else {
return false;
}
}
private $site, $firstname, $lastname, $email,
$sex, $birthdate, $phone, $country, $displayname,
$handle, $password, $salt, $joindate, $confirm_password1, $confirm_password2;
protected $addUser, $addProfile;
}
I found the issue. The issue was due to printf() functions that were apart of a few class members in the database class. They were causing an interruption with the function completing and returning the boolean value true or false in registerUser();
Thank you all for your help and assistance. I would give up a vote up, but I don't have enough reputation points. haha.

Identical field checking is not working properly for zend form

I have created a zend form where I have a password and confirm password filed. I am using same form for add and update/edit the database. My code is working fine when I want to add a new password but don't work when I want to edit already existing one.
My form:
$password = new Zend_Form_Element_Password('password');
$password->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags')
->addValidator('NotEmpty', false, array('messages'=>'password cannot be empty'))
->addValidator('StringLength', false, array(5, 25, 'messages'=>'password must be 5-30 character'))
->setLabel('Password:');
$this->addElement($password);
$confirmPassword = new Zend_Form_Element_Password('confirmPassword');
$confirmPassword->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags')
->addValidator('NotEmpty', false, array('messages'=>'password don\'t match'))
->addValidator(new School_Validate_PasswordConfirmation())
->setLabel('Confirm Password');
$this->addElement($confirmPassword);
my School_Validate_PasswordConfirmation class:
class School_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
const NOT_MATCH = 'notMatch';
protected $_messageTemplates = array(
self::NOT_MATCH => 'Password confirmation does not match'
);
public function isValid($value, $context = null)
{
$value = (string) $value;
$this->_setValue($value);
if (is_array($context)) {
if (isset($context['password'])&& ($value == $context['password']))
{
return true;
}
} elseif (is_string($context) && ($value == $context)) {
return true;
}
$this->_error(self::NOT_MATCH);
return false;
}
}
When I want to edit other fields other than password the it gives the below error messages. But this messages will only be shown when I enter the user for the first time.
Errors:
password cannot be empty
password don't match
Thanks in advance.
When the form is in edit mode, just remove the validators from the element.
public function someAction()
{
$form = new Application_Form_YourForm();
if ('in edit mode') {
$form->getElement('password')->clearValidators();
$form->getElement('confirmPassword')->clearValidators();
}
if ($this->getRequest()->isPost()) {
$valid = $form->isValid($this->getRequest()->getPost());
if ($valid) {
// ...
} else {
// ...
}
}
}
If you allow someone to change their password by filling in those fields, add an additional check to see if anything is entered into the password field when in edit mode. If they have filled in the password, leave the validators, otherwise remove them.
Hope that helps.

Facebook Payment dialogue not working

Here's the error code:
"The app you are using is not responding. Please try again later."
The callback is set to the php file (via https). I have no idea why it's not working.
Here's the JS (binded to var dr):
dr.buyCoins = function(){
var obj = {
method: 'pay',
order_info: order_info,
action: 'buy_item',
dev_purchase_params: {'oscif': true}
};
FB.ui(obj, dr.coinCheck);
}
dr.coinCheck = function(d){
if (d['order_id']) {
return true;
} else {
return false;
}
}
and here's the PHP:
<?php
$app_secret = '...';
// Validate request is from Facebook and parse contents for use.
$request = parse_signed_request($_POST['signed_request'], $app_secret);
// Get request type.
// Two types:
// 1. payments_get_items.
// 2. payments_status_update.
$request_type = $_POST['method'];
// Setup response.
$response = '';
if ($request_type == 'payments_get_items') {
// Get order info from Pay Dialog's order_info.
// Assumes order_info is a JSON encoded string.
$order_info = json_decode($request['credits']['order_info'], true);
// Get item id.
$item_id = $order_info['item_id'];
// Simulutates item lookup based on Pay Dialog's order_info.
if ($item_id == '1a') {
$item = array(
'title' => '100 some game cash',
'description' => 'Spend cash in some game.',
// Price must be denominated in credits.
'price' => 1,
'image_url' => 'http://some_image_url/coin.jpg',
);
// Construct response.
$response = array(
'content' => array(
0 => $item,
),
'method' => $request_type,
);
// Response must be JSON encoded.
$response = json_encode($response);
}
} else if ($request_type == "payments_status_update") {
// Get order details.
$order_details = json_decode($request['credits']['order_details'], true);
// Determine if this is an earned currency order.
$item_data = json_decode($order_details['items'][0]['data'], true);
$earned_currency_order = (isset($item_data['modified'])) ?
$item_data['modified'] : null;
// Get order status.
$current_order_status = $order_details['status'];
if ($current_order_status == 'placed') {
// Fulfill order based on $order_details unless...
if ($earned_currency_order) {
// Fulfill order based on the information below...
// URL to the application's currency webpage.
$product = $earned_currency_order['product'];
// Title of the application currency webpage.
$product_title = $earned_currency_order['product_title'];
// Amount of application currency to deposit.
$product_amount = $earned_currency_order['product_amount'];
// If the order is settled, the developer will receive this
// amount of credits as payment.
$credits_amount = $earned_currency_order['credits_amount'];
}
$next_order_status = 'settled';
// Construct response.
$response = array(
'content' => array(
'status' => $next_order_status,
'order_id' => $order_details['order_id'],
),
'method' => $request_type,
);
// Response must be JSON encoded.
$response = json_encode($response);
} else if ($current_order_status == 'disputed') {
// 1. Track disputed item orders.
// 2. Investigate user's dispute and resolve by settling or refunding the order.
// 3. Update the order status asychronously using Graph API.
} else if ($current_order_status == 'refunded') {
// Track refunded item orders initiated by Facebook. No need to respond.
} else {
// Track other order statuses.
}
}
// Send response.
echo $response;
// These methods are documented here:
// https://developers.facebook.com/docs/authentication/signed_request/
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
Check your server logs and make sure you're receiving the request and responding to it correctly - note that if your callback is HTTPS your certificate needs to be fully valid including all intermediate certificates
In your case sslchecker said you're possibly missing the intermediate chain - https://www.sslshopper.com/ssl-checker.html#hostname=https://drawabble.com

Problem defining what to do with 'guest' user in Zend_Acl

I'm getting the following error on every view available for the 'guest' user:
Notice: Trying to get property of non-object in /home/fiodorovich/public_html/gisele/library/Federico/Plugin/Acl.php on line 35
the line it's referring to is '$role = $this->_auth->getStorage()->read()->role;' in:
public function preDispatch (Zend_Controller_Request_Abstract $request)
{
$role = $this->_auth->getStorage()->read()->role;
if($role === null) {
$role = self::DEFAULT_ROLE;
}
$action = $request->getActionName();
$controller = $request->getControllerName();
if($this->_acl->has($controller)) {
if(!$this->_acl->isAllowed($role, $controller, $action)) {
$request->setActionName('error');
$request->setControllerName('error');
}
}
}
I know it's just a notice, and that it won't show in production since errors will be disabled... however it's kind of bugging me. So how could I solve this?
Use $this->_auth->hasIdentity() before request data from storage.
if ($this->_auth->hasIdentity()) {
// user is logged in and we can get role
$role = $this->_auth->getStorage()->read()->role;
} else {
// guest
$role = self::DEFAULT_ROLE;
}