I want to set session id - php

public function admin_login()
{
$this->form_validation->set_rules('email','E-mail','required|trim');
$this->form_validation->set_rules('password','Password','required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>"," </p>");
if( $this->form_validation->run())
{
$email=$this->input->post('email');
$password=$this->input->post('password');
$link='http://api.amid.tech/admin/'.$email.'/'.$password;
$data = (array) json_decode(file_get_contents($link,true));
if($email== $data['email'] && $password== $data['password'])
{
var_dump($data = (array) json_decode(file_get_contents($link,true)));
echo $userid=$this->session->set_userdata('name',$data);
exit;
$this->load->view('admin/dashboard');
}
else
{
// echo"false";
$this->load->view('index');
//echo validation_errors('');
}
}
}
I want to set session id in this code through api

Codeigniter 2.X's session management is NOT implemented on top of PHP Sessions. So if you were trying to print $_SESSION, it will show up an empty array. Instead you should use $this->session->userdata('key'). $_SESSION should however work just fine if you are using CI 3.X.
Have a look at this:
https://www.codeigniter.com/userguide3/installation/upgrade_300.html#step-6-update-your-session-library-usage

Not Exactly sure what you want but if you have refereed CI's user guide then, this can help you set session and save them in database.
First Load The Session Library:
$this->load->library('session');
Now If you have some value in variable and want to store it into session then you can do this:
$this->session->set_userdata('string', $variable);
If there is an array of data then as mentioned in user guide:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
And if you want a specific item from session then you can do:
echo $this->session->userdata('session-variable-name');
For all session data do:
var_dump($this->session->all_userdata());
And if you want to save your sessions to database then simply create a table called ci_sessions
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
Like so.
I suggest you to read the user guide it has lot more.

Related

MySQL/PHP Multilanguage form

How can I build multilanguage form with Translations from database using pdo object?
for example, there is my code to create pdo object:
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMEssage();
die();
}
$sql = "SELECT FROM `lang_content` `id`, `:lang`";
$query = $pdo->prepare($sql);
if($query->execute(array(
':lang' => $_GET['lang'].'_content'
))){
// Show content
}
MySQL table structure:
CREATE TABLE `lang_content` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`en_content` VARCHAR(1000) NULL DEFAULT NULL,
`lv_content` VARCHAR(1000) NULL DEFAULT NULL,
`ru_content` VARCHAR(1000) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COMMENT='All translations'
ENGINE=MyISAM
;
MySQL table data example:
id en_content lv_content ru_content
1 MOD KASKO КАСКО
2 MTPL OCTA ОСАГО
And I would like to use it like:
if lang en
<?= $result->1 ?> // Echo MOD
Will return MOD,
<?= $result->2 ?> // Echo MTPL
Will return MTPL
Honestly that is not good practice to do your translation via database. Many big platforms do it through some sort of text format. For example magento does it through csv files.
You could start your development with the following code.
Your Spanish translation file es.csv
'Home', 'Inicio'
'Page 1', 'Pagina 1'
'Page 2', 'Pagina 2'
'Page 3', 'Pagina 3'
The first column of words would be your default language which would be defined within a function.
<a href="#"><?php __("Home"); ?>
Then you would use a switch statement like the one you have on top to capture which language the user choose. The __() function would look something like this. Where input would be "home"
$csv = array_map('str_getcsv', file($file));
// Logic (where it would do the translation)
// It could look for the input in the $cvs variable if it exist then use the next value of the current array. Else keep the text the same.
Your cvs file would need to make the exact words to be translated.

cakephp multilingual dynamic content from database

I want to develop website with option to select language
at the time I do not know about how to structure my database tables i.e
either I should add separate fields for each language e.g
tbl_posts
id, title_en,title_fr,description_en,description_fr,....
or should I get help of google translate at run time
or there is something else easy to do this
secondly I will need to have URLs like
www.domain.com/en/posts/ & www.domain.com/fr/posts/
third what other things should I keep in mind to develop multilingual website.
looking for standardized, more optimized, easy manageable and fully dynamic solution.
Cakephp
Step 1: In your lib/Cake/basic.php add function
if (!function_exists('__dbt')) {
function __dbt($text, $args = null) {
if($text==null){
return null;
}else{
$languageUse = Configure::read('Config.language');
if($languageUse!='en-us' && $languageUse!='eng'){
$modelName = ucfirst($languageUse)."Translation";
$model = ClassRegistry::init($modelName);
$data = $model->find('first',array('fields'=>array('translation'),'conditions'=>array("text"=>"$text")));
if(!empty($data[$modelName]) && $data[$modelName]['translation']!=''){
return $data[$modelName]['translation'];//die('1');
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}
}
}
Step 2: create table on basis of language you want to use
Note: table name should be prefix locale + _tranlations
example: hin_translations, tha_translations etc.
CREATE TABLE IF NOT EXISTS `hin_translations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` text NOT NULL,
`translation` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
In above table add english string in your text column and its translation in translation column.
Step 3: where ever you want to change language string either from database or locale po file just use
__dbt("Write your string here");
:) enjoy your multilingual site

Delete mysql records is not working in codeIgniter

This is my controller function:
function delete_article($title){
if ($this->session->userdata('User') && $this->session->userdata('User') == 'admin#example.com') {
$this->load->model('Article', 'Article', TRUE);
$this->Article->delete_article_db($title);
redirect('admin/user_article');
} else {
redirect('');
}
}
And this is my model function for deleting the database record:
function delete_article_db($title) {
$this->db->where('Title', $title);
$this->db->delete('article');
}
When I run this code, nothing gets deleted. However, the code does not fire any errors or warnings.
This is my MySQL table structure:
CREATE TABLE IF NOT EXISTS `article` (
`Name` text NOT NULL,
`Email` text NOT NULL,
`Phone` text NOT NULL,
`Address` text NOT NULL,
`Literature` text NOT NULL,
`Title` text NOT NULL,
`Submission_Name` text NOT NULL,
`Additional_Name` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
A bit of a wild guess, but looking at your controller method, and the variable names, I'm assuming you're passing the title via url, something like
http://example.com/admin/delete/Title to be deleted
Which leads me to think your query is not working because of encoding of the spaces in the url (or other characters) which won't match the not encoded spaces in your db.
Try with:
function delete_article_db($title) {
$this->db->where('Title', rawurldecode($title) );
$this->db->delete('article');
}

laravel session returning null inspite of setting it

Just a simple function in native php
protected function some_function(){
session_start();
if(!isset($_SESSION['a']))
{
$_SESSION['a'] = 'some value';
return true;
} else {
return $_SESSION['a'];
}
}
on the 1st run, it will return bool(true) and then "some value" as expected.
Applying the same to laravel session,
protected function some_function(){
$a = Session::get('abc');
if(is_null($a)){
Session::put('abc', 'some value');
//return Session::get('abc');
return true;
} else {
return $a;
}
}
By logic, on the 1st run, $a will be null. and then puts "some value" in abc key and returns bool(true) as expected.
However on consequent access, the Session::get('abc') returns null every time. so every attempt returns bool(true).
I assumed may be session wasn't writing properly so i checked with getting the key value right after setting it.
by commenting out the line in the above code, it returns whatever value i put in Session::put('abc'). So there is no error in writing the data.
Problem here is trying to retrieve the value always returns null though i have set after the 1st request.
Am i missing something here?
EDIT
Using database as the driver, The sessions does not get save in database. No error is outputted. Database implementation has been correct with sessions table schema as described in docs.
Try this snippet. Untested, but pretty sure it works.
if(Session::has('abc'))
{
return Session::get('abc');
} else {
Session::put('abc', 'some value');
return true;
}
After going through many forum to solve same issue, I solved it by setting my session driver to database.
'driver' => 'database',
and created table in database
CREATE TABLE `sessions` (
`id` varchar(40) NOT NULL,
`last_activity` int(10) NOT NULL,
`data` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

External linking and cakephp's routing engine (multilingual)

I recently build a tiny routing 'extension', that calls the routes from a MySQL table (structure downwards). I think it's worth to be mentioned, that this page runs in multiple languages (German and English). So - relying on the cookie, that's currently set in the client's browser - the corresponding routings get connected.
The problem is, that if the user cannot (externally) be linked to a german content page, if his browser's language cookie was set to the English language (because the english routes got connected).
Does anyone got a proper solution for this? To be honest, I don't really know, how to programmatically extend the Router-class' functionality.
The MySQL table's structure looks like this:
CREATE TABLE `routes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`language` varchar(5) COLLATE latin1_general_ci NOT NULL DEFAULT 'de',
`route` varchar(64) COLLATE latin1_general_ci NOT NULL,
`controller` varchar(64) COLLATE latin1_general_ci NOT NULL,
`action` varchar(64) COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (`id`)
)
Use p28n - http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial
It works well, I use it a lot and it's part of my standard build now.
I also have a script that will return translated urls depending on the chosen language. I can't remember where I found the script it's based on, but if it helps I can try to send you a clean version.
EDIT: Okay, here's the bones:
This script will translate urls so that they remain SEO friendly across languages. The language switching and message translation is handled by p28n (above) and po.
Put this line in your app/config/bootstrap.php file:
include_once("translate.php");
Put this as the first line of code in app/config/routes.php:
$fromUrl = translate($fromUrl,true);
Now you need to create the file app/config/translate.php which contains all of the routing information:
function translate($str = null,$total = false)
{
// If this is an RSS route, ignore it and bounce straight out
if (strpos($str,".rss")!==false)
return $str;
$translatetable = array(
'some-url-in-german' => array('/articles/msome-url-in-german',1),
'some-url-in-english' => array('/articles/some-url-in-german',2),
'a-german-article' => array('/posts/a-german-article',1),
'an-english-article' => array('/posts/a-german-article',2)
);
if($str)
{
if($total)
{
$old = explode('/',$str);
$lastone = end($old);
if(empty($lastone)) array_pop($old);
$new = array();
/* translate each part or leave untranslated part */
for($i = 0 ; $i <sizeof($old) ; $i++)
{
$new[$i] = translate($old[$i]);
}
/* construct the translated url. This also adds
a trailing "/" even if it wasn't in the original */
$new_url="";
foreach($new as $n)
{
$new_url .= $n."/";
}
return $new_url;
}
else
{
foreach ($translatetable as $orig => $new)
{
if($str == $orig)
{
$str = $new[0];
switchLanguage($new[1]);
}
}
return $str;
}
}
}
function switchLanguage($lang)
{
if($lang>0)
{
$translatetable = array(
'1' => 'de',
'2'=> 'eng'
);
Configure::write(array('Config.language'=>$translatetable[$lang]));
}
}
It's quite straightforward really - the trick is getting it to feed into CakePHP at the right places. I hope it is of some use to you.

Categories