Move Image to another Path from a clicked link; Codeigniter - image

The idea is to move an image selected by the current user to another path that's also in the database. Here is the Controller:
public function makeProfile() {
if (isset($_GET['makeProfile']));
$data['user_id']= $this->session->userdata['user_id'];
$fileName = ('uploads/'.$fileName);
if($this->images_model->makeProfile($data, $fileName)) {
echo "Success";
$msg = 'File successfully moved to profile';
redirect(site_url().'main/');
}else{
echo "Failure";
The Model:
Public function makeProfile ($data, $fileName) {
return $this->db->get_where('images', ['user_id' => $this->session->userdata('user_id')])->row();
move_uploaded_file('uploads/'.$fileName, 'uploads/profile/'.$fileName);
if($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
The VIEW:
<a class="profile" href="<?= base_url('main/makeProfile') ?>">Make Profile</a>
I’m probably going about this all wrong, but hoping someone here might steer me in the right direction. Thanks in advance for any and all input!

Function makeProfile in the model has an issue. You are getting the record and then returning it back. The code below is not executing
Public function makeProfile ($data, $fileName) {
$fileName= $this->db->get_where('images', ['user_id' => $this->session->userdata('user_id')])->row()->image;
// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('uploads/'.$fileName, 'uploads/profile/'.$fileName));
if($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
Quoting a couple of relevant sentences from its manual page :
Makes a copy of the file source to dest.
If the destination file already exists, it will be overwritten.

Related

How to restrict user to add input duplicate data into database using codeigniter

I'd One text_box(txtname) & Add button in View . I've to restrict user to add already existing(duplicate) data in a database . after clicking on Add button. what changes should I've to do in Model & controller.
I tried to copy+ paste my model & controller code but due to some restrictions of website i'm not getting able to display code. please kindly suggest me what should I've to do ?
try this i hope it will help you.
first of all get data by textAddItem
//controller save data function
//get txtAdditem
$txtAddItem = $this->modelname->method_name($this->input->post('textAddItem'));
if (count($txtAddItem) > 0) {
//already existed
}
else{
$data=array(
$name=>$this->input->post('textAddItem')
);
return $query=$this->db->insert('tbl_category',$data);
}
//modele
function method_name($textAddItem) {
return $this->db->where('cat_name', $textAddItem)
->get('tbl_category')->row_array();
}
First, check the cat_name in the DB before inserting in the controller
Controller
public function function_name(){
$this->load->model('CrudModel');
$data = array('cat_name' => $name);
$if_exists = $this->CrudModel->check_category($data);
if($if_exists > 0){
//Already Exists
}else{
//New insertion
}
}
Model
public function check_category($data){
return $this->db->get_where('tbl_cateogry', $data)->num_rows();
}
public function insertMenurecord()
{
$this->load->model('CrudModel');
$this->form_validation->set_rules('txtMenuItem', 'Menu','required|is_unique[tbl_menumaster.menu_name]');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('msg','&nbsp&nbsp&nbsp Inserted record already exist');
redirect('Welcome/displayMasterMenu');
}
else
{
$this->CrudModel->saveMenudata();
$this->session->set_flashdata('msg','You have successfully Inserted record');
redirect('Welcome/displayMasterMenu');
}
}

API REST don't work routes

I'm using codeigniter, for make an api rest, with the library that provide the oficial web site.
The problem is: the file routes.php doesn't redirect well. When i put localhost/API/1 into my browser apear the 404 error.
Here my controller "Apicontroller":
public function __construct() { //constructor //no tocar
parent::__construct();
$this -> load -> model("Modelocontrolador");
}
public function index_get() { //get all the info
$datos_devueltos = $this->Modelocontrolador->getPrueba(NULL, "Usuarios");
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}
public function find_get($id){ //select where
$datos_devueltos = $this->Modelocontrolador->getPrueba($id, "Usuarios");
if($id != NULL){
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}else{
$this->response(array("response" => "No dates for search"), 200);
}
}
public function index_post() { //insert in la table
if(! $this -> post("dato")){
$this->response(array("response" => "No enought info"), 200);
}else{
$datoID = $this -> Modelocontrolador -> save($this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => $datoID), 200);
}else{
$this->response(array("response" => "No found it"), 200);
}
}
}
public function index_put($id) { //"update"
if(! $this -> post("dato") || ! $id){
$this->response(array("response" => "No ha mandado informacion correcta para el update"), 200);
}else{
$datoID = $this -> Modelocontrolador -> update("Uid",$id,$this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => "Dato actualizado"), 200);
}else{
$this->response(array("response" => "Error modify"), 200);
}
}
}
public function index_delete($id) {
if(! $id){
$this->response(array("response" => "Not enought info"), 200);
}else{
$delete = $this-> Modelocontrolador -> delete("Uid",$id,"UsuariosJJ");
}
if(!is_null($delete)){
$this->response(array("response" => "Date delete"), 200);
}else{
$this->response(array("response" => "Error delete"), 200);
}
}}
And my routes file:
$route['default_controller'] = 'Apicontroller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*sub-rutas*/
/*---------*/
$route["Apicontroller"]["get"] = "Apicontroller/index"; //basico
$route["Apicontroller/(:num)"]["get"] = "Apicontroller/find"; //select
$route["Apicontroller"]["post"] = "Apicontroller/index"; //insert
$route["Apicontroller/(:num)"]["put"] = "Apicontroller/index/$1"; //update
$route["Apicontroller/(:num)"]["delete"] = "Apicontroller/index/$1"; //delete
If the browser request literally uses /API then routing needs to 'see' exactly that. Also, the route rules must be explicit with the method to be called. (Hopefully the code shown reflects the mapping you had in mind.)
/*sub-rutas*/
/*---------*/
$route["API"]["get"] = "Apicontroller/index_get"; //basico
$route["API/(:num)"]["get"] = "Apicontroller/find_get/$1"; //select
$route["API"]["post"] = "Apicontroller/index_post"; //insert
$route["API/(:num)"]["put"] = "Apicontroller/index_put/$1"; //update
$route["API/(:num)"]["delete"] = "Apicontroller/index_delete/$1"; //delete
Using the above routes I created some test code. Here are those files.
The much simplified Apicontroller.
class Apicontroller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index_get()
{
echo "API index";
}
public function find_get($id)
{ //select where
echo "API find_get $id";
}
public function index_post()
{
echo 'API index_post';
}
public function index_put($id)
{ //"update"
echo "API put $id";
}
}
I don't believe that because your Apicontroller is extending a different Class the results would change. That may be a drastic assumption.
In order to test POST calls I used these two files.
First a Testpost.php controller
class Testpost extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
public function index()
{
$this->load->view("test");
}
}
The very simple view (test.php) loaded by the above.
<?php
echo form_open("API");
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
Directing the browser to localhost/testpost shows a page with a single submit button. Pressing the button results in a screen with the text "API index_post".
Sending the browser to localhost/API/3 produces a screen with the text "API find_get 3".
localhost/API produces "API index".
Now the interesting thing (not related to your problem, but interesting).
Given the default
$route['default_controller'] = 'Apicontroller';
and the route
$route["API"]["get"] = "Apicontroller/index_get";
I expected that directing the browser to the home page localhost would produce "API index". But it doesn't. It results in a 404. Due to that behavior it might be wise to be more explicit with default_controller
$route['default_controller'] = 'Apicontroller/index_get';
Or add an index() function to Apicontroller that calls $this->index_get().
I did not test PUT or DELETE as my server isn't setup to handle them. But as GET and POST seem to function, in a righteous world, they will work.
seems like you are using PHil's REST_Controller library with CI 2.x, correct ?
If so, I would recommend you to use what I like to call an "index gateway" because you can't do per-Method routing with CI2:
class Apicontroller extends REST_Controller
{
function index_gateway_get($id){
$this->get_get($id);
}
function index_gateway_put($id){
$this->put_put($id);
}
// This is not a "gateway" method because POST doesn't require an ID
function index_post(){
$this->post_post();
}
function get_get($id = null){
if(!isset($id)){
// Get all rows
}else{
// Get specific row
}
}
function put_put($id = null){
if(!isset($id)){
// a PUT withtout an ID is a POST
$this->post_post();
}else{
// PUT method
}
}
function post_post(){
// POST method
}
}
The routing to make this work is really easy:
$route["API/(:num)"] = "Apicontroller/index_gateway/$1";
That's all you need. Phil's REST Library will redirect to the correct index_gateway_HTTPMETHOD depending on which method is used.
Each index_gateway_HTTPMETHOD will then redirect to the correct method.
As far as I know, this trick is the only way to have CI2 use a single /API/ entry point that works for all HTTP Methods.

simple ajax form in cakephp 3.0

As JsHelper is no more in cakephp 3.0 so what i am doing is to save my form data into database using ajax
i just have two input fields.
my files are:
add.ctp
js.js
EmployeesController.php
add.ctp
$this->Form->create('Employees');
$this->Form->input('name', array('id'=>'name'));
$this->Form->input('age', array('id'=>'age'));
$this->Form->button('Add Info', array(
'type'=>'button',
'onclick'=>'infoAdd();'
));
$this->Form->end();
js.js
function infoAdd() {
var name=$("#name").val();
var age=$("#age").val();
$.get('/employees/info?name='+name+"&age="+age, function(d) {
alert(d);
});
}
EmployeesController.php
class EmployeesController extends AppController {
public $components=array('RequestHandler');
public function add() {
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->autoRender=false;
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
echo "Success: data saved";
//echo $result->id;
}
else {
echo "Error: some error";
//print_r($emp);
}
}
}
}
Note : my model only have not empty rule for both fields
all what i am doing is working fine but i dont think i m doing it in right way or as it should be.
please help me what i m missing and what i don't need to do.
Take away the autoRender line and serialize the data you want returned:
public function add() {
$data = [];
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
$data['response'] = "Success: data saved";
//echo $result->id;
}
else {
$data['response'] = "Error: some error";
//print_r($emp);
}
}
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
The serialize function tells Cake that it's not expecting the function to have a view, so autoRender is not needed (http://book.cakephp.org/3.0/en/views/json-and-xml-views.html).

How do I split my HABTM tags?

I want to take a field in the add form of the Post, explode it at the spaces, and save each word as a Tag, which HasAndBelongsToMany Post. So, for each unrecognized tag, it will create a new one, but if the Tag already exists, it will only create a new reference in the posts_tags tables. I've tried using saveAll, saveAssociated, and few foreach hacks, and I am not exactly sure where it went wrong, but I cannot figure out how to save the associate data. Any sort of outline of how to get the tag data from the form to the database would be appreciated.
//in model
public function parseTags($data) {
$str = $data['Tag'][0]['title'];
$tags = explode('',$str);
for ($i=0; $i<count($tags); $i++) {
$data['Tag'][$i]['title'] = $tags[$i];
}
return $data;
}
//in view
echo $this->Form->input('Tag.0.title',array('label'=>'Tags'));
//in controller
public function add() {
if ($this->request->is('post')) {
$this->Question->create();
$this->request->data['Question']['user_id'] = $this->Auth->user('id');
$this->request->data = $this->Question->parseTags($this->request->data);
if ($this->Question->saveAll($this->request->data)) {
$this->Session->setFlash(__('The question has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The question could not be saved. Please, try again.'));
}
}
$users = $this->Question->User->find('list');
$this->set(compact('users'));
}
You must first check if Tag saved before or not, if not saved, You can save it. So before you save your model ,all of your tags is saved before.
something like this:
/* $tag_list is exploded tags*/
foreach ($tag_list as $tag) {
$res = $this->Tag->find('first', array('conditions' => array('Tag.name' => $tag)));
if ($res != array()) {
$tag_info[] = $res['Tag']['id'];
} else {
$this->Tag->create();
$this->Tag->save(array('Tag.name' => $tag));
$tag_info[] = sprintf($this->Tag->getLastInsertID());
}
}
$this->model->data['Tag']['Tag'] = $tag_info;

CodeIgniter Session Userdate seems not to exists

I'm coding my first CI project and try to write a loginscript. Everything works almost fine, except that the session userdata is not available (even not if i check my cookies / sessions in Firefox).
I don't understand why the session userdata only are available after login, but if i load the same page again (not a refresh, but a new load) i would expect i still will be logged in, but i'm logged out ? Even if i try to read the session userdata it doesn't exists.
I simplified my script to an example version for stackoverflow. Who can tell me how this session issue can be solved?
Regards,
Guido
<?php
class Test extends CI_Controller
{
function index()
{
$logged_in = $this->is_logged_in();
if($logged_in) {
echo "You are logged in. <a href='test/logout'>Logout</a> | <a href='../'>Return to index</a>";
}
else {
echo "You are logged out";
echo form_open('test/check_login');
echo "Email: ".form_input('email', set_value('email'));
echo "Password: ".form_password('password', set_value('password'));
echo form_submit('submit','Login');
echo form_close();
}
}
function is_logged_in() // check if user has logged in
{
// AUTOLOAD SESSIONS HAS SET in autoload.php-config >> $autoload['libraries'] = arra y('database', 'session', 'email');
$is_logged_in = $this->session->userdata('is_logged_in');
if($is_logged_in) {
return TRUE;
}
else {
return FALSE;
}
}
function check_login()
{
$client_id = $this->validate();
if(is_numeric($client_id)) // if the user's credentials validated then user exists
{
$data = array(
'client_id' => $client_id,
'is_logged_in' => true
);
$this->session->set_userdata($data);
}
$this->index();
}
// normally we put this function in a model, but for this example we put it here.
function validate() // check if user exists in database
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('client_users'); // this is our user table
if($query->num_rows == 1) // user exists
{
$row = $query->row();
return $row->id_client;
}
else
{
return false;
}
}
function logout()
{
$this->session->sess_destroy(); // kill session, so user will be logged out.
redirect('/test');
}
}
?>
Your validate function's if statement should read:
if($query->num_rows() == 1) // user exists
You left out the () after num_rows.
Edit: After further review, that shouldn't matter. The only other thing I can tell is maybe your result is not equal to 1. Either the user isn't found or you're getting more than one result, both resulting in !== 1.

Resources