Check if username exists in database with codeigniter and ajax - sql

Can anyone help me check if a username is in my database using ajax and code igniter?
I can't use the form_validation method as I have modal windows which interfere with the checking.
Currently my controller looks like:
function filename_exists(){
$username = $this->input->post('username');
$data['exists'] = $this->User_model->filename_exists($username);
}
My Model:
function filename_exists($username)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $username);
$query = $this->db->get();
if ($query->num_rows() == 0) {
return true;
} else {
return false;
}
}
and my ajax post:
function check_if_exists() {
<?php $username = $this->input->post('username');
?>
var username = '<?php echo $username ?>';
var DataString=$("#form1").serialize();
$.ajax({
url: "<?php echo base_url(); ?>index.php/Files/filename_exists/",
type: "post",
data: DataString + '&username=' + username,
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">'+msg+"</span>");
}
else {
$('#msg').html('<span style="color:red;">Value does not exist</span>');
}
}
});
}
UPDATE
<form name = "form1" id = "form1" method ="post"> <!--action="<?php echo base_url()."index.php/Admin/create_user"; ?>"-->
<?php echo validation_errors(); ?>
<label for="userID" class = "labelForm">User ID:</label>
<input type="text" id="userID" name="userID" class = "input2">
<label for="first_name" class = "labelForm">First Name:</label>
<input type="text" id="first_name" name="first_name" class = "input2">
<label for="last_name" class = "labelForm">Last Name:</label>
<input type="text" id="last_name" name="last_name" class = "input2">
<label for="username" class = "labelForm">Username:</label>
<input type="text" id="username" name="username" class = "input2" onblur="check_if_exists();">
<label for="password" class = "labelForm">Password:</label>
<input type="password" id="password" name="password" class = "input2" onblur="checkPasswords();">
<label for="passconf" class = "labelForm">Password:</label>
<input type="password" id="passconf" name="passconf" class = "input2" onblur="checkPasswords();">
<label for="email" class = "labelForm">Email:</label>
<input type="text" id="email" name="email" class = "input2">
<button type="button" id = "new_user_submit">Add New User</button>

Try this
In Ajax
function check_if_exists() {
var username = $("#username").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/files/filename_exists",
data:{ username:username},
success:function(response)
{
if (response == true)
{
$('#msg').html('<span style="color: green;">'+msg+"</span>");
}
else
{
$('#msg').html('<span style="color:red;">Value does not exist</span>');
}
}
});
}
In Controller
function filename_exists()
{
$username = $this->input->post('username');
$exists = $this->User_model->filename_exists($username);
$count = count($exists);
// echo $count
if (empty($count)) {
return true;
} else {
return false;
}
}
In Model
function filename_exists($username)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $username);
$query = $this->db->get();
$result = $query->result_array();
return $result
}

If you are just trying to see if the user already exists, there is no reason to query with the get() function. just do the count_all_results() it will return a number if the user is found, 0 if not.
function filename_exists($username) {
$this->db->where('username', $username);
return $this->db->count_all_results('users');
}
All this will do is return a number greater than zero if the username exists in your db.

Just another approach with same result
MODEL
function filename_exists($username) {
$this->db->select()->from('users')->where('username', $username);
$query = $this->db->get();
return $query->first_row('array'); // returns first row if has record in db
}
CONTROLLER
function filename_exists() {
$username = $this->input->post('username');
$user = $this->user_modal->filename_exists($username);
return !empty($user); // not empty returns true else false
}
AJAX
Inside the check_if_exists function.
$.post('<?php echo base_url(); ?>index.php/files/filename_exists', { username: $('#username').val() }, function(response) {
var html = '<span style="color:red;">Value does not exist</span>';
if (response == true) {
html = '<span style="color: green;">' + msg + '</span>';
}
$('#msg').html(html);
});

Related

Adding İtems in Shopping cart

I've been working on my shopping cart program, but I keep having problems with adding an item to the shopping cart
here is my code;
HomeController class
[HttpPost]
public ActionResult AddToBasket(int id)
{
var basketJson = HttpContext.Session.GetString(SESSION_KEY);
List<SepetProduct> sepet;
if (basketJson == null)
{
sepet = new List<SepetProduct>();
}
else
{
sepet = JsonSerializer.Deserialize<List<SepetProduct>>(basketJson);
}
if (sepet.Any(x=> x.id == id))
{
sepet.Single(x => x.id == id).Toplam++;
}
else
{
sepet.Add(new SepetProduct { id = id, Toplam = 1 });
}
basketJson = JsonSerializer.Serialize(sepet);
HttpContext.Session.SetString(SESSION_KEY, basketJson);
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = sepet });
}
'''
and here is my Button action code
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" name="Id" value="#urun.UrunId" />
<button type="submit" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
The problem is that, when ı press to "sepete ekle" button, item was added to cart, but it directs us to a new page called "https://localhost:44302/Home/addToBasket"
and show us those data
'''
status true
msg "Ürün Sepete Eklendi"
data
0
id 2
toplam 1
'''
I would like to when ı press to 'sepete ekle ' button, the page remains the same, but the product is added to the basket. it just shows us a message saying added.
How can ı do that. thank you for interesting and helping
You can try to use ajax to replace form post.Here is a working demo:
TestBasket.cshtml(I use value="1" to test.And add id="Id" to hidden input.Also,I need to change the type of button,so that when click it,it will not submit form,it will go to submitData() function.):
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" id="Id" name="Id" value="1" />
<button type="button" onclick="submitData()" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
<script>
function submitData() {
$.ajax({
type: "POST",
url: '#Url.Action("addToBasket","Home")',
data: { "id": $("#Id").val() }
}).done(function (data) {
console.log(data.msg);
});
}
</script>
HomeController:
public IActionResult TestBasket()
{
return View();
}
[HttpPost]
public ActionResult AddToBasket(int id)
{
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = new List<SepetProduct>() });
}
result:

Mvc Fileupload controler not save in document

How do i save a image in folder in mvc 4.
Here is the code:
<form method="post" class="form-horizontal" name="NewLabelform" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Ticket</h4>
</div>
<div class="modal-body">
<p>
<span>Type:</span>
<select class="form-control" id="addtype">
<option value="1">Technical Issue</option>
<option value="2">Bug</option>
<option value="3">Feature Request</option>
<option value="4">Sales Question</option>
<option value="5">How To</option>
</select>
<span id="errortype" style="color: Red;"></span>
</p>
<p>
<span>Title:</span>
<input type="text" class="form-control" id="addTitle" />
<span id="errorTitle" style="color: Red;"></span>
</p>
<p>
<span>description:</span>
<textarea rows="4" cols="50" class="form-control" id="addDesc"></textarea>
<span id="errorDesc" style="color: Red;"></span>
</p>
<p>
<span>Importancy:</span>
<select class="form-control" id="addimportancy">
<option value="1">High</option>
<option value="2">Medium</option>
<option value="3">Low</option>
</select>
<span id="errorimportancy" style="color: Red;"></span>
</p>
<p>
<span>Attached Documents:</span>
<input type="file" name="fileuploader" class="form-control" id="fileuploader" />
<span id="errorAttach" style="color: Red;"></span>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="CreateLabeData()">Create</button>
</div>
</form>
Here is the Ajax Method:
<script>
var $al = jQuery.noConflict();
function CreateLabeData() {
debugger
var errortype = document.getElementById('errortype');
var addtype = document.getElementById('addtype');
if (addtype.length == "0") {
errortype.innerHTML = "Type is required.";
addtype.focus();
return false;
}
else {
errortype.innerHTML = "";
}
var errorTitle = document.getElementById('errorTitle');
var addTitle = document.getElementById('addTitle');
if (addTitle.value == '') {
errorTitle.innerHTML = "Title is required.";
addTitle.focus();
return false;
}
else {
errorTitle.innerHTML = "";
}
var errorDesc = document.getElementById('errorDesc');
var addDesc = document.getElementById('addDesc');
if (addDesc.value == '') {
errorDesc.innerHTML = "Description is required.";
addDesc.focus();
return false;
}
else {
errorDesc.innerHTML = "";
}
var errorimportancy = document.getElementById('errorimportancy');
var addimportancy = document.getElementById('addimportancy');
if (addimportancy.length == "0") {
errorimportancy.innerHTML = "Importancy is required.";
addimportancy.focus();
return false;
}
else {
errorimportancy.innerHTML = "";
}
//var foldername = document.getElementById("fname").value;
var readdtype = document.getElementById('addtype').value;
var readdTitle = document.getElementById('addTitle').value;
var readdDesc = document.getElementById('addDesc').value;
var readdimportancy = document.getElementById('addimportancy').value;
//var fname = document.querySelector('input[type=file]').files[0].name;
//var doc = $al("#fileuploader").val();
//var filename = doc.replace(/^.*[\\\/]/, '');
//var formData = new FormData();
//var totalFiles = document.getElementById("fileuploader").files.length;
//for (var i = 0; i < totalFiles; i++) {
// var file = document.getElementById("fileuploader").files[i];
// formData.append("fileuploader", file);
//}
//formData.append("fileuploader", file);
$.ajax(
{
//url: "/Ticket/InsertTicket/",
url: '#Url.Content("~/TicketTemplate/InsertTicket")',
type: "POST",
cache: false,
async: true,
datatype: "json",
contentType: 'application/json; charset=utf-8',
//data: JSON.stringify({ 'Addtype': readdtype, 'AddTitle': readdTitle, 'AddDesc': readdDesc, 'Addimportancy': readdimportancy, 'FileName': filename,' FormData': formData }),
data: JSON.stringify({ 'Addtype': readdtype, 'AddTitle': readdTitle, 'AddDesc': readdDesc, 'Addimportancy': readdimportancy }),
success: function (result) {
debugger;
if (result.isSuccess) {
window.location.reload(true);
}
else {
alert('!');
}
},
error: function (result) {
debugger;
alert('');
}
});
}
Here is the controller:
public ActionResult InsertTicket(HttpPostedFileBase FileName, string Addtype, string AddTitle, string AddDesc, string Addimportancy, string FormData)
//public ActionResult InsertTicket( string Addtype, string AddTitle, string AddDesc, string Addimportancy)
{
string isSuccess = "0";
AppTicket models;
AppTicket model = new AppTicket();
model.Type = Convert.ToInt32(Addtype);
model.Title = Convert.ToString(AddTitle);
model.Description = Convert.ToString(AddDesc);
model.Importancy = Convert.ToInt32(Addimportancy);
//obj.Title = Convert.ToString(AddTitle);
int CompanyId = 1;
int status = 1;
//if (FileName != null)
//{
// string saveto = string.Empty;
// // var File = FileName;
// //saveto = Path.Combine(Server.MapPath("~/Content/Areas/Ticket/Content"), FileName);
// // File.SaveAs(saveto);
//}
//var file = Request.Files;
////string saveto = string.Empty;
//string name = string.Empty;
//if (Request.Files.Count > 0)
//{
// var File = Request.Files[0];
// Random rnd = new Random();
// name = rnd.Next(111, 9999).ToString() + "_" + System.IO.Path.GetFileName(File.FileName);
// saveto = Path.Combine(Server.MapPath("~/Content/Areas/Ticket/Content"), name);
// File.SaveAs(saveto);
// // Session["File"] = name;
// Session["File"] = saveto;
//}
Int64? res = _apiTicket.Posts(model.Title, (model.Type), model.Description, (model.Importancy), "", (UserId), CompanyId, false, status);
if (res > 0)
{
isSuccess = "1";
}
return Json(isSuccess, JsonRequestBehavior.AllowGet);
}
How do i save uploaded file in folder??
I have tried a lot but this is not working for me...any suggestion??
In a model popup i need to show the form having all these component.
When click on save it need to save on the folder and name in db.
But it is not working??
So any one can try or give me some solutions??

Opencart Multi Store login with same store customer not others

I am using opencart Multi store , as per my code we are having up to 10 stores , every store we have customers , the customers who is registered with particular store he can able to login to that store only, if he tries to login with any other store which he not registered there must be a error message like you are not registered with this store or else something else...
as per my code if customer login with other store which not registered he is redirecting to his store only but not login, it should not redirect and he should get error message...
Below is my controller :
<?php
class ControllerAccountLogin extends Controller {
private $error = array();
public function index() {
//echo 44; exit;
$this->load->model('account/customer');
// Login override for admin users
if (!empty($this->request->get['token'])) {
$this->event->trigger('pre.customer.login');
$this->customer->logout();
$this->cart->clear();
unset($this->session->data['wishlist']);
unset($this->session->data['payment_address']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['shipping_address']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
$customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);
if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
// Default Addresses
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
$this->event->trigger('post.customer.login');
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
$this->load->language('account/login');
$this->document->setTitle($this->language->get('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
//echo $this->config->get('config_store_id'); exit;
if ($this->config->get('config_store_id')) {
// echo 'sravz';
// echo $this->customer->getStoreId(); exit;
if ($this->customer->getStoreId() != 0) {
if ($this->customer->getStoreId() != $this->config->get('config_store_id')) {
$this->load->model('setting/store');
// $store_info = $this->model_setting_store->getStore($this->customer->getStoreId());
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store where store_id=".$this->customer->getStoreId()."");
$store_info = $query->row;
$this->response->redirect($store_info['url']);
}
}
}
unset($this->session->data['guest']);
// Default Shipping Address
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $this->customer->getId(),
'name' => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
);
$this->model_account_activity->addActivity('login', $activity_data);
// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
$this->response->redirect(str_replace('&', '&', $this->request->post['redirect']));
} else {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_login'),
'href' => $this->url->link('account/login', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_new_customer'] = $this->language->get('text_new_customer');
$data['text_register'] = $this->language->get('text_register');
$data['text_register_account'] = $this->language->get('text_register_account');
$data['text_returning_customer'] = $this->language->get('text_returning_customer');
$data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
$data['text_forgotten'] = $this->language->get('text_forgotten');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_password'] = $this->language->get('entry_password');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_login'] = $this->language->get('button_login');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = $this->url->link('account/login', '', 'SSL');
$data['register'] = $this->url->link('account/register', '', 'SSL');
$data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');
// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
$data['redirect'] = $this->request->post['redirect'];
} elseif (isset($this->session->data['redirect'])) {
$data['redirect'] = $this->session->data['redirect'];
unset($this->session->data['redirect']);
} else {
$data['redirect'] = '';
}
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$data['account'] = $this->load->controller('module/account');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/login.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/login.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/login.tpl', $data));
}
}
protected function validate() {
//echo $this->request->post['email'];exit;
$this->event->trigger('pre.customer.login');
// Check how many login attempts have been made.
$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);
if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
$this->error['warning'] = $this->language->get('error_attempts');
}
// Check if customer has been approved.
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
//print_r($customer_info);exit;
if ($customer_info && !$customer_info['approved']) {
$this->error['warning'] = $this->language->get('error_approved');
}
//print_r( $this->error); exit;
if (!$this->error) {
if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
//echo 44; exit;
// $this->error['warning'] = $this->language->get('error_login');
// $this->model_account_customer->addLoginAttempt($this->request->post['email']);
} else {
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->event->trigger('post.customer.login');
}
}
return !$this->error;
}
}
Below is my View :
<?php echo $header; ?>
<div class="container">
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ul>
<?php if ($success) { ?>
<div class="alert alert-success"><i class="fa fa-check-circle"></i> <?php echo $success; ?></div>
<?php } ?>
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?></div>
<?php } ?>
<div class="row"><?php echo $column_left; ?>
<?php if ($column_left && $column_right) { ?>
<?php $class = 'col-sm-6 no-pad'; ?>
<?php } elseif ($column_left || $column_right) { ?>
<?php $class = 'col-sm-9'; ?>
<?php } else { ?>
<?php $class = 'col-sm-12'; ?>
<?php } ?>
<div id="content" class="<?php echo $class; ?>"><?php echo $content_top; ?>
<div class="panel panel-primary">
<div class="top">
<div class="panel-heading title-heading search-head"><?php echo $heading_title; ?></div>
</div>
<div class="panel-body">
<div class="row">
<!-- <h2></h2>-->
<div class="col-sm-6">
<b style="margin-bottom: 2px; display: block;"><?php echo $text_new_customer; ?></b>
<div class="well left">
<!-- <p><strong><?php echo $text_register; ?></strong></p>-->
<p><?php echo $text_register_account; ?></p>
<!-- <?php echo "Go to Shopping"; ?> --></div>
</div>
<div class="col-sm-6">
<b style="margin-bottom: 2px; display: block;"><?php echo $text_returning_customer; ?></b>
<div class="well">
<!-- <h2><?php echo $text_returning_customer; ?></h2>-->
<p><?php echo $text_i_am_returning_customer; ?></p>
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email"> <strong> <?php echo $entry_email; ?></strong></label>
<input type="text" name="email" value="<?php echo $email; ?>" placeholder="<?php echo $entry_email; ?>" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password"> <strong> <?php echo $entry_password; ?></strong></label></strong>
<input type="password" name="password" value="<?php echo $password; ?>" placeholder="<?php echo $entry_password; ?>" id="input-password" class="form-control" />
<?php echo $text_forgotten; ?></div>
<input type="submit" value="<?php echo $button_login; ?>" class="btn btn-primary" />
<?php if ($redirect) { ?>
<input type="hidden" name="redirect" value="<?php echo $redirect; ?>" />
<?php } ?>
</form>
</div>
</div>
</div>
</div>
<?php echo $content_bottom; ?></div></div>
<div class="clearfix hidden-sm hidden-md hidden-lg"></div>
<?php echo $column_right; ?>
<div class="hidden-sm hidden-md hidden-lg"><div class="container"><?php echo $account; ?></div></div>
</div>
</div>
<?php echo $footer; ?>
To give back an error message to the customer you must check that the customer is part of the Customer Group assigned to that store. Use this at the start of the validate() method in catalog/controller/account/login.php:
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
$customerGroupId = isset($customer_info['customer_group_id']) ? $customer_info['customer_group_id'] : -1;
$allowedCustomerGroups = $this->config->get('config_customer_group_display');
if(!is_array($allowedCustomerGroups) || !in_array($customerGroupId, $allowedCustomerGroups)) {
$this->error['warning'] = $this->language->get('error_login');
return false;
}
Remember that this will not take care if your customer logs in into the right store and then goes to another store.
If you want to log customer out when they change store use this code and paste after the $data variable declaration in catalog/controller/common/header.php at around line 90:
if ($this->customer->isLogged() && ($this->config->get('config_store_id') != $this->customer->getStoreId())) {
$this->url->link('account/logout', '', true);
$this->customer->logout();
}
Then
You will have to add this method in the system/library/cart/customer.php file:
public function getStoreId() {
return $this->store_id;
}
Hope this helps :)

PDO and OOP login

I'm programming my first website using PDO and OOP right now. I've only used MySQL/ MySQLi and standard PHP before.
I created a login/register system using phpacademy's OOP register/login tutorial series.
Now I have a question about this. How do I add an isOwner or something that I can use to check if the logged in user is on it's own profile etc. I'm going to try creating a pm system and then I need this to make sure that you can't send a pm to yourself :)
Here's the code:
login.php
<?php
require_once 'core/init.php';
$user = new User();
if ($user->isLoggedIn()) {
Redirect::to('index.php');
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Log in</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/global.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome.css">
<script src="js/main.js"></script>
</head>
<body>
<?php require_once 'includes/header.php'; ?>
<form action="" method="post">
<h1>Log in</h1>
<div class="inset">
<?php
if (input::exists()) {
if (Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'name' => 'Username'
),
'password' => array(
'required' => true,
'name' => 'Password'
)
));
if ($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if ($login) {
Redirect::to('index.php');
} else {
echo '<p>Sorry, logging in failed </p>';
}
} else {
foreach ($validation->errors() as $error) {
echo '<i class="fa fa-exclamation-triangle"></i> ', $error, '<br>';
echo '<br />';
}
}
}
}
?>
<p>
<label for="username">USERNAME</label>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
<p>
<input type="checkbox" name="remember" id="remember">
<label for="remember">Remember me for 1 month</label>
</p>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<p class="p-container">
<span>Forgot password?</span>
<input type="submit" name="go" id="go" value="Log in">
</p>
</form>
</body>
</html>
Validate.php
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
public function check($source, $items = array()) {
foreach ($items as $item => $rules) {
foreach ($rules as $rule => $rule_value) {
$value = trim($source[$item]);
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$this->addError("{$rules['name']} is required");
} else if(!empty($value)) {
switch ($rule) {
case 'min':
if (strlen($value) < $rule_value) {
$this->addError("{$rules['name']} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if (strlen($value) > $rule_value) {
$this->addError("{$rules['name']} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if ($value != $source[$rule_value]) {
$this->addError("{$rule_value} must match {$rules['name']}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if ($check->count()) {
$this->addError("{$rules['name']} already exists.");
}
break;
}
}
}
}
if (empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
User.php
<?php
class User {
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if (!$user) {
if (Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if ($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// process logout
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null) {
if (!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if (!$this->_db->update('users', $id, $fields)) {
throw new Exception('There was a problem updating');
}
}
public function create($fields = array()) {
if (!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account.');
}
}
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($username = null, $password = null, $remember = false) {
if (!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if ($user) {
if ($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if ($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if (!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
}
}
}
return false;
}
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if ($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if ($permissions[$key] == true) {
return true;
}
}
return false;
}
public function exists() {
return (!empty($this->_data)) ? true : false;
}
public function logout() {
$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
Could someone please help me with this?
Thanks in advance,
Busarna

C# MVC API send values using GET queryString?

This is first time I have tried to make an API using MVC4. So far it is working ok.
For practice I want to try and send my model using a queryString in the GET method instead of my current POST send method.
As I have no clue how to start, and whats need to be done ? Can you come with some advices ?
Can I have the Index view as it is ? or anything need to be changed ?
I also would like to keep the curent GET method I have to show the list, I guess that will interfere if I add a new GET method fot sending querystring ?
All advices is helpful here ^_^
namespace MessageHandler.Models
{
public class Message
{
public int Id { get; set; }
public double Amount { get; set; }
public string PaymentMessage { get; set; }
public string Name { get; set; }
public string Adress { get; set; }
}
}
namespace MessageHandler.Services
{
public class MessageRepository
{
private const string CacheKey = "MessageStore";
public MessageRepository()
{
var ctx = HttpContext.Current;
if (ctx != null)
{
if (ctx.Cache[CacheKey] == null)
{
var messages = new Message[]
{
new Message
{
Id = 1, PaymentMessage = "payment for order 23434",
Name = "Christer Glenning", Adress = "Grenvagen 24",
Amount = 2300
},
new Message
{
Id = 2, PaymentMessage = "payment for order 24354",
Name = "Carl Ingemar", Adress = "Regnbagen 446",
Amount = 44
}
};
ctx.Cache[CacheKey] = messages;
}
}
}
public Message[] GetAllMessages()
{
var ctx = HttpContext.Current;
if (ctx != null)
{
return (Message[])ctx.Cache[CacheKey];
}
return new Message[]
{
new Message
{
Id = 0,
Name = "placeHolder"
}
};
}
public bool SaveMessage(Message message)
{
var ctx = HttpContext.Current;
if (ctx != null)
{
try
{
var currentData = ((Message[])ctx.Cache[CacheKey]).ToList();
currentData.Add(message);
ctx.Cache[CacheKey] = currentData.ToArray();
return true;
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
return false;
}
}
return false;
}
}
}
using MessageHandler.Models;
using MessageHandler.Services;
namespace MessageHandler.Controllers
{
public class MessageController : ApiController
{
private MessageRepository repo;
public MessageController()
{
this.repo = new MessageRepository();
}
public Message[] Get()
{
return repo.GetAllMessages();
}
public HttpResponseMessage Post(Message message)
{
this.repo.SaveMessage(message);
var response = Request.CreateResponse<Message>(System.
Net.HttpStatusCode.Created, message);
return response;
}
}
}
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
API</p>
</div>
</div>
</header>
<div id="body">
<ul id="messages"></ul>
<form id="saveMessageForm" method="post">
<h3>Create a new Message</h3>
<p>
<label for="messageId">Id:</label>
<input type="text" name="Id" />
</p>
<p>
<label for="messagePaymentMessage">Message:</label>
<input type="text" name="PaymentMessage" />
</p>
<p>
<label for="messageName">Name:</label>
<input type="text" name="Name" />
</p>
<p>
<label for="messageAdress">Adress:</label>
<input type="text" name="Adress" />
</p>
<p>
<label for="messageAmount">Amount:</label>
<input type="text" name="Amount" />
</p>
<input type="button" id="saveMessage" value="Save" />
</form>
</div>
#section scripts
{
<script type="text/javascript">
$(function()
{
$.getJSON('/api/message', function (messagesJsonPayload) {
$(messagesJsonPayload).each(function (i, item) {
$('#messages').append('<li>' + item.PaymentMessage + '</li>' +
'<li>' + item.Name + '</li>' +
'<li>' + item.Adress + '</li>' +
'<li>' + '$' + item.Amount.toFixed(2) + '</li>' + '<br>');
});
});
});
</script>
<script type="text/javascript">
$('#saveMessage').click(function()
{
$.post("api/message",
$("#saveMessageForm").serialize(),
function(value)
{
$('#messages').append('<li>' + value.PaymentMessage + '</li>' +
'<li>' + value.Name + '</li>' +
'<li>' + value.Adress + '</li>' +
'<li>' + '$' + value.Amount.toFixed(2) + '</li>');
},
"json"
);
});
</script>
}
Well, I'm not expert for build an API, but I think you need to step back and learning concept for building an API (specially the REST one).
here's the link that maybe useful for you:
build-restful-apis-with-aspnet-web-api
REST API Tutorial