Upload and retrieve image in CakePHP - cakephp

I have following code to upload a file in cakephp
class UsersController extends AppController {
var $name = 'Users';
function index() {
$this->set('users', $this->User->find('all'));
}
function add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your user data has been saved.');
$this->redirect(array('action' => 'index'));
}
$this->User->create();
if ($this->uploads() && $this->User->save($this->data)) {
$this->Session->setFlash(_('Upload saved', true));
} else {
$this->Session->setFlash(_('Upload not saved.Please try again', true));
}
}
}
function uploads() {
$uploads_dir = '/uploads';
$users = $this->request->data['Upload']['file'];
if ($users['error'] === UPLOAD_ERR_OK) {
if (move_uploaded_file($users['User']['file'], $uploads_dir)) {
$this->User->saveAll($this->data);
return true;
}
}
return false;
}
function edit($id = null) {
$this->User->id = $id;
if (empty($this->data)) {
$this->data = $this->User->read();
} else {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your user details has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id) {
$this->User->delete($id);
$this->Session->setFlash('This user has been deleted.');
$this->redirect(array('action' => 'index'));
}
}
When I'm trying to upload, the file is uplaoding but I need the file uploaded to be viewed when the hyperlink given for each .jpeg to be displayed but I'm getting the error as
" The requested address '/Users/app/webroot/index.php/uploads' was not found on this server."
Also please help me how to store the uploaded image in another folder
PS:: code should b purely in CakePHP
Please help,
Thanks in advance

Make sure the folder used for uploading files have sufficient permissions and you can use Cakephp Media view to download files. For your reference,check this.
Downloading files using media view in CakePHP
Use image name or image id as an argument in function download and change path to
'path' => APP . 'uploads' . DS
"uploads" folder should be inside webroot directory.

Related

How to encrypt a password in cakephp 2.x version

Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.

CakePHP 3.0 Save data in to tables

I'm trying to create a log system for users add and notificate the admins when a new user has been added, asking him permissions to let the new user login.
Anyone knows if there is a plugin for it available? Or how can I save this data in two tables.
I've tried this
public function add() {
$user = $this->Users->newEntity();
$log = $this->Logs->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$user->criado_por = $this->Auth->user('nome');
$user->modificado_por = $this->Auth->user('nome');
$user->userstatus = 'waiting for permitions';
$log->date = date::now();
$log->newuser = $user->name;
$log->whocreate = $this->Auth->User('name');
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
Here's a notification plugin for CakePHP: Notifier

trying to display an image using cakephp mysql

i am trying to display an image using cakephp and mysql..my code is running but it is not displaying an image
uploadsController is::
<?php
class UploadsController extends AppController{
var $name='Uploads';
function share_video($stu_id=null)
{
$this->set('stu',$stu_id);
$tut=$this->Session->read('tutor_id');
$data=$this->Upload->query("select * from tutors AS Tutor where tutor_id='$tut'");
$this->set('val1',$data);
if (!empty($this->data)) {
$this->Upload->create();
if ($this->uploadFile() && $this->Upload->save($this->data)) {
$this->Session->setFlash(__('The upload has been saved', true));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
}
}
$data=$this->Upload->find('all');
$this->set('val2',$data);
$this->layout='tutor';
}
function uploadFile() {
$id = mysql_insert_id();
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
//$id = String::uuid();
if (move_uploaded_file($file['tmp_name'], APP.'webroot/uploads'.DS.$file['name'])) {
$this->request->data['Upload']['upload_id'] = $id;
$this->request->data['Upload']['filename'] = $file['name'];
$this->request->data['Upload']['filesize'] = $file['size'];
$this->request->data['Upload']['filemime'] = $file['type'];
return true;
}
}
return false;
}
function download($filename=null)
{
$data=$this->Upload->find('all',array('conditions'=>array('filename'=>$filename)));
$this->set('val1',$data);
}
}
?>
and my download.ctp file is:
Html->image('uploads/'.$val1[0]['Upload']['filename']);
//echo 'Html->url(array('controller' => 'uploads','action' => 'download',$val1[0]['Upload']['filename'])).'" width="100" height="100"/>';
?>
if (move_uploaded_file($tmp_name['tmp_name'],WWW_ROOT."/img/uploads/".$file['name']‌​)) { /* conditions*/ }
$data=$this->Upload->find('first',array('conditions'=>array('filename'=>$filenam‌​e)));
echo $this->Html->image('uploads/'.$val1['Upload']['filename'],array('class'=>'media-‌​‌​object img img-thumbnail','alt'=>$val1['Upload']['filename']) );

CakePHP Ajax delete

I am trying to delete cakephp data by ajax.Here I have changed postlink button to simple html button like as
<button class="del" id=<?php echo $user['User']['id']; ?>>Delete </delete>
Here now I am able to get user id by bellow code
$('document').ready(function(){
$('.del').click(function(){
var x=$(this).attr("id");
alert(x);
});
});
I have successfully get id of the user.Now I am trying to sent it for userscontroller in delete action.So I have coded like
$('document').ready(function(){
$('.del').click(function(){
var x=$(this).attr("id");
alert(x);
jQuery.get("<?php echo $this->webroot . $this->params["users"]; ?>/delete",{"id":x},function(data,stat){
jQuery("#success").load("success.ctp");
});
});
});
Now in controller in delete action I have tried
public function delete($id=NUll) {
$id=$_GET['id'];
$this->User->id = $id;
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
}
return $this->redirect(array('action' => 'index'));
}
Here it's not working.In controller how can I defined it ?
If u use before filter,
function beforeFilter()
{
//Here set Which pages should be accessable to various users
$adminPages =array('delete');
$this->Auth->allow($adminPages);
......
}
Allow it to be executed using Auth allow.
If thats also working fine,Check if AJAX string is proper. Check using MANUAL DELETE like abc.com/Users/delete/id:2 Just copy paste string u get in jQuery.get(). Does it delete properly??
IF ALL DOESNT Work TRY following : :)
public function delete($id=NUll) {
$id=$_GET['id'];
$this->User->id = $id;
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
}
return $this->redirect(array('action' => 'index'));
}
And ajax :
jQuery.get("<?php echo $this->webroot . $this->params["users"].'/delete/';?>"+x+"",{"id":x},function(data,stat){
jQuery("#success").load("success.ctp");
});
Here the wrong was only url, I have changed it and now it's working fine
echo $this->webroot . $this->params["users"]; ?>/delete"
TO
echo Router::url(array('controller'=>'users','action'=>'delete'));?>"
try this if you want to use ajax
public function delete_user() {
$this->autoRender = false;
if ($this->request->data) {
$this->User->id = $this->request->data['id'];
$update = $this->User->saveField($this->request->data['field'], $this->request->data['value']);
if ($update) {
$repsonce['success'] = '1';
$this->Session->setFlash(__d('User', 'User Deleted successfully'), 'default', array('class' => 'alert alert-success'));
} else {
$repsonce['success'] = '0';
}
} else {
$repsonce['success'] = '0';
}
echo json_encode($repsonce);
}

Login Redirect with cakephp

I am current using Usermgmt Plugin for the login function and the users management. What I want to do is to redirect the specific pages based on the group_id after they login. I am current lost with the cake.
This is the code from AppController.
var $helpers = array('Form', 'Html', 'Session', 'Js', 'Usermgmt.UserAuth');
public $components = array('Session','RequestHandler', 'Usermgmt.UserAuth');
function beforeFilter(){
$this->userAuth();
}
private function userAuth(){
$this->UserAuth->beforeFilter($this);
}
This is the login function from UsersController.
public function login() {
if ($this->request -> isPost()) {
$this->User->set($this->data);
if($this->User->LoginValidate()) {
$email = $this->data['User']['email'];
$password = $this->data['User']['password'];
$user = $this->User->findByUsername($email);
if (empty($user)) {
$user = $this->User->findByEmail($email);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
// check for inactive account
if ($user['User']['id'] != 1 and $user['User']['active']==0) {
$this->Session->setFlash(__('Your registration has not been confirmed please verify your email or contact to Administrator'));
return;
}
$hashed = md5($password);
if ($user['User']['password'] === $hashed) {
$this->UserAuth->login($user);
$remember = (!empty($this->data['User']['remember']));
if ($remember) {
$this->UserAuth->persist('2 weeks');
}
$OriginAfterLogin=$this->Session->read('Usermgmt.OriginAfterLogin');
$this->Session->delete('Usermgmt.OriginAfterLogin');
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
$this->redirect($redirect);
} else {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
}
}
Any help is appreciated. Thank you.
If you want to redirect them somewhere else, then change the redirect line. This assumes your User model is related to a Group model and the recursive level lets your find call pull the data.
// original
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
// new redirect, eg: /groups/view/3
$redirect = array(
'controller' => 'groups',
'action' => 'view',
$user['Group']['id']
);
$this->redirect($redirect);

Resources