PHP Help, not recognizing the different users - php

I have little knowledge with PHP and I was assigned to try to fix some of the things that don't work in a website. The website basically deals with two different users, a trader who can post articles and a blogger who can post blogs. When a user registers to become a trader and tries to submit an article,the page just redirects to base_url.user/blogger/ instead of base_url.user/trader/. I think this is because it isn't recognizing the user as a trader. Can you please look at the codes? If you have any ideas as to why it wouldn't work I'm open to ideas
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Index Page for this controller.
*
* Since this controller is set as the default controller in
* config/routes.php, it's displayed
*
*
* File Controller; location: application/controllers/admin.php
* Author : Pradeep
* Date : Sunday Feb 5th, 2012
**/
class Register extends CI_Controller {
private $user;
private $logData;
function _Register()
{
parent::controller();
$this->config->load('constants.php');
}
public function blogger()
{
//-------------------------SENDING ERROR MESSAGE FOR LOGIN-------------------
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Blogger';
$this->load->view('register-blogger',$data);
}
public function trader()
{
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Trader';
$this->load->view('register-trader',$data);
}
public function activate()
{
$data['pageTitle']='Registration | Succesfully registered';
$this->load->view('register-success',$data);
}
public function process()
{
$date = date('Y-m-d');
$userid = uniqid();
$captchaError = '';
if($this->input->post('Submit'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('mycheck[]', 'Buyer or Supplier','required');
$this->form_validation->set_rules('material[]', 'materials','required');
$this->form_validation->set_rules('company', 'Company name', 'required');
$this->form_validation->set_rules('cname', 'Contact name','required');
$this->form_validation->set_rules('cemail', 'Contact email', 'required|valid_email');
$this->form_validation->set_rules('nation', 'Country', 'required');
$this->form_validation->set_rules('city', 'City','required');
$this->form_validation->set_rules('fax');
$this->form_validation->set_rules('mobile');
$this->form_validation->set_rules('phone');
$this->form_validation->set_rules('website');
$this->form_validation->set_rules('address');
$this->form_validation->set_rules('zip');
$this->form_validation->set_rules('content', 'Tell something about urself', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-trader',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
if($this->input->post('material'))
{
$material = '';
foreach($this->input->post('material') as $value)
{
$material.= $value.',';
}
$material = rtrim($material,',');
}
$mycheck = $this->input->post('mycheck');
$mycheckOne = '';
$mycheckTwo = '';
if(!empty($mycheck[0])){$mycheckOne = $mycheck[0];}
if(!empty($mycheck[1])){$mycheckTwo = $mycheck[1];}
$config['file_name'] = uniqid();
$config['upload_path'] = UP_PATH;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile1'))
{
$error = $this->upload->display_errors();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('name'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
else
{
$data = array('upload_data' => $this->upload->data());
$filepath = $data['upload_data']['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = UP_PATH.$filepath;
$config['new_image'] = UP_PATH.'thumbs/';
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '';
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('fax'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'image'=>$filepath,
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
$this->db->insert(TBL_CLA,$data);
$log_type = 'trader';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>1
);
$this->db->insert(TBL_USE,$dataOne);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
if($this->input->post('Login'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-blogger',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
$date = date('Y-m-d');
$log_type = 'blogger';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>0
);
$this->db->insert(TBL_USE,$dataOne);
$data['link'] = 'http://www.arabrecycling.org/activate/created/'.$userid;
$data['name'] = $this->input->post('fname');
$message = $this->load->view('includes/activate',$data, TRUE);
$subject = 'Account Activation';
$fromTest = 'The Arab Recycling Initiative';
$this->userRegEmail('info#arabrecycling.org',$this->input->post('email'),$message,$subject,$fromTest);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
}
//-------------------------------------------------------CAPTCHA CREATION STARTS HERE------------------------
public function getCaptcha(){
$this->load->library('common');
$this->common = new common();
$this->load->helper('captcha');
$vals = array(
'word' => $this->common->GetRandomCaptchaText(8),
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'font_path' => base_url().'system/fonts/Candice.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
return $cap['image'];
}
//--------------------------------------------------------CAPTCHA CREATION ENDS HERE------------------------------------------------
//--------------------------------------------------------CONFIGURING EMAIL------------------------------------------------
public function userRegEmail($from,$to,$message,$subject,$fromTest){
$email_config['protocol'] = 'mail';
$email_config['mailtype'] = 'html';
$this->email->initialize($email_config);
$this->email->from($from, $fromTest);
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
//--------------------------------------------------------EMAIL CONFIGURATION ENDS HERE------------------------------------------------

Use SESSIONS:
On top of your page set:
<?php
//Check if session has not been started.
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
In the code when defining a trader or blogger:
$_SESSION['USER'] = "trader";
or
$_SESSION['USER'] = "blogger";
Then you can execute the code you want:
//If it has not been set, do trader by default.
if (!ISSET($_SESSION['USER'])
{
$_SESSION['USER'] = "trader";
}
if ($_SESSION['USER'] == "blogger")
{
//Execute code for blogger
}
else if($_SESSION['USER'] == "trader")
{
//Execute code for trader
}
Sessions are stored in your browser as long as your "Page/Session" is open. Those "Variables" are user specific.
Hope this helps :)

You should identify if a user is a trader or a blogger, and then set appropriate session variables accordingly. A simple if statement to check which is logged in depending on which session variable is set should do the trick? If i'm understanding your question correctly.
What I would suggest (it will probably be easier) is
1. add an attribute to your user table in your database that is Account_Type enum('trader','blogger') not null.
2. Add radio buttons to your form when they sign up to choose if they are a trader or blogger
and obviously have this data sent back to your database
3. When they Login (i'm assuming all users have a unique username) do something like
-Set Session variables to 0
$_SESSION['trader'] = 0;
$_SESSION['blogger'] = 0;
-find username in database and for that username check if trader or blogger.
//A Query to find the Account_type that goes with the input account
$accquery = "SELECT Account_type FROM Account WHERE Account_Name =$_POST['account']";
//Running the query
$result = mysqli_query($connect,$accquery);
//Using an array to fetch the type and put it into a variables place
while($row = mysqli_fetch_array($connect,$result))
{
$acctype = $row['Account_Type'];
}
else {
die("Query failed");
}
And then do something like
if($acctype == "trader") {
$_SESSION['trader'] = 1;
elseif($acctype == "Blogger") {
$_SESSION['blogger'] =1;
else {
//error message
}
and then when you need to check which they are you can do something like
if((isset($_SESSION['trader'])) && ($_SESSION['trader'] == "1")){
//specific code for trader
}
and you can apply the same for blogger.
I would also advise you look into sanitizing your inputs, it's simple but very important.
Also note, do a thorough search through stackoverflow for answers to your questions because more than likely you will find something.
-Hope this helps, note its only rough so you will have to work around it but you should have some grasp of PHP anyways so that should do.

Related

Codeigniter 3 application bug: adding is_unique validation criteria prevents edit form data from submitting

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4. The application has user (author) accounts.
Once logged in, the author can edit his/her account info, including the email address:
Adding is_uniqueto the email field (in order to prevent duplicate email addresses on account info edit, not just creation) causes this bug:
When I try to update the email using an email already assigned an author, including myself, the validation error message The Email is already taken appears.
In the controller I have this update method:
public function update() {
// Only logged in users can update user profiles
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$id = $this->input->post('id');
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['author'] = $this->Usermodel->editAuthor($id);
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[authors.email]');
$this->form_validation->set_message('is_unique', 'The %s is already taken');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// Upload avatar
$config['upload_path'] = './assets/img/authors';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$uerrors = array('uerrors' => $this->upload->display_errors());
// if NO file is uploaded,
if (empty($_FILES['userfile']['name'])) {
// force upload validation and
$uerrors = [];
// use the existing avatar (if any)
$avatar = $this->input->post('avatar');
}
$data['uerrors'] = $uerrors;
} else {
$data = array('upload_data' => $this->upload->data());
$avatar = $_FILES['userfile']['name'];
$this->session->set_userdata('user_avatar', $avatar);
}
if(!$this->form_validation->run() || !empty($uerrors)) {
$this->load->view('partials/header', $data);
$this->load->view('dashboard/edit-author');
$this->load->view('partials/footer');
} else {
$this->Usermodel->update_user($avatar, $id);
$this->session->set_flashdata('user_updated', 'Your account details have been updated');
redirect(base_url('/dashboard/manage-authors'));
}
}
In the view with the edit form:
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<input type="text" name="email" id="email" class="form-control" value="<?php echo set_value('email', $author->email); ?>" placeholder="Email">
<?php if(form_error('email')) echo form_error('email'); ?>
</div>
Where is my mistake?
This is how the is_unique works, it checks the table for any duplicate entries as it has no way of knowing what id is being edited. Is this a bug? Maybe.
But you can make your own validation function and make a call to it. Like so -
public function update() {
$id = $this->input->post('id');
// ...
// ...
// ...
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|callback__checkemail['.$id.']'); // pass id
// ...
// ...
// ...
}
function _checkemail($email, $id){
// don't need to $this->input->post('email') as it is a validation for the same ↑↑(set_rules), if you need anything else then $this->input->post('input_field')
if( !$id ){
$this->db->where('email', $email);
$num = $this->db->count_all_results('authors');
}else{
$this->db->where('email', $email);
$this->db->where_not_in('id', $id); // not in current id in edit mode
$num = $this->db->count_all_results('authors');
}
// You'd probably want to do DB queries↑↑ in model
// You can also combine the queries into one as they seem repetitive
if ($num > 0) {
$this->form_validation->set_message('_checkemail','Email already exists!'); //set message to the callbacked function(ie _checkemail) not the input field here.
return FALSE;
} else {
return TRUE;
}
}
See if it helps you.

Session data gets lots when form is submitted

I have a method that adds a record to a MySQL database. The application is progremmed in CodeIgnite. I get the ID of the currently logged on user with the following code -
$agentId = $this->session->userdata('agentid');
When I echo $agentId to the top of the form page, it shows 28 which is correct. When the Save button is clicked and the method is ran, the session clears it and logs the user out. I can't figure out why this happens.
public function add(){
$agentId = $this->session->userdata('agentId');
echo $agentId;
if(!$agentId){
redirect(base_url().'login', 'refresh');
}
if(!isSuperAdmin() && !isPayment()){
redirect(base_url().'payment', 'refresh');
}
$data['p_title'] = $this->project_model->projectName().' :: Property : Add New Property';
$data['Message'] = '';
$data['heading'] = 'Property: Add New Property';
$data['pageName'] = 'property';
$data['title'] = filter_value('title', '');
$data['meta_decription'] = filter_value('meta_decription', '');
$data['keywords'] = filter_value('keywords', '');
$data['type'] = filter_value('type', '');
$data['sub_type'] = filter_value('sub_type', '');
$data['sub_type1'] = filter_value('sub_type1', '');
$data['bedrooms'] = filter_value('bedrooms', '');
$data['kitchen'] = filter_value('kitchen', '');
$data['parking'] = filter_value('parking', 'YES');
$data['bathrooms'] = filter_value('bathrooms', '');
$data['price'] = filter_value('price', '0.00');
$data['rent_frequency'] = filter_value('rent_frequency', '');
$data['deposit'] = filter_value('deposit', '0.00');
$data['location'] = filter_value('location', '');
$data['city'] = filter_value('city', 82);
$data['country'] = filter_value('country', 102);
$data['details'] = filter_value('details', '');
$data['featured'] = filter_value('featured', 'NO');
$data['countries'] = $this->general_model->listCountries($data['country']);
$data['cities'] = $this->general_model->listCities($data['country'], $data['city']);
$this->form_validation->set_rules('title', 'Property title', 'trim|required');
if($this->form_validation->run() === TRUE){
// the agentId variable is lost here, so 0 gets etntered in to the database and the user is logged out.
$agentId = $this->session->userdata('agentId');
$Date = getCurrentDate();
$Time = getCurrentTime();
$DbFieldsAry = array('agentId', 'title', 'meta_decription', 'keywords', 'type', 'sub_type', 'sub_type1', 'bedrooms', 'kitchen', 'parking', 'bathrooms', 'price', 'rent_frequency', 'deposit', 'location', 'city', 'country', 'details', 'featured', 'date');
$InfoAry = array($agentId, $data['title'], $data['meta_decription'], $data['keywords'], $data['type'], $data['sub_type'], $data['sub_type1'], $data['bedrooms'], $data['kitchen'], $data['parking'], $data['bathrooms'], $data['price'], $data['rent_frequency'], $data['deposit'], $data['location'], $data['city'], $data['country'], $data['details'], $data['featured'], $Date);
if($this->general_model->duplicateEntry($DbFieldsAry, $InfoAry, 'tbl_properties_list')){
$activityId = $this->general_model->getSingleValue($data['title'], 'title', 'property_id', 'tbl_properties_list');
setMessage('success_message', 'New property added successfully. Add pictures to property.');
redirect(base_url().'property/update/'.$activityId.'/0', 'refresh');
}
else{
setMessage('error_message', 'Unable to perofrm this operation, please try again later!');
redirect(base_url().'property/user_listing', 'refresh');
}
}
$data['allowed'] = true;
$data['warning'] = '';
if(!isSuperAdmin()){
$total_properties = $this->general_model->getTotalDataSimple1('property_id','tbl_properties_list');
if(allowed_properties() <= $total_properties){
$data['allowed'] = false;
$data['warning'] = '<br/>You have reached to maximum limit of your property upload listing.<br/>Click HERE to change payment plan.<br/><br/><br/><br/><br/>';
}
}
$this->load->view('add_property', $data);
}
Here is the session in config.php
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 14400;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 600;
I am assuming you have already loaded session library in the constructor or autoload file. if not then that maybe the problem. If yes than try changing the session timeout or session storage method in config.php of codeigniter.

How to remove this error: The filetype you are attempting to upload is not allowed

public function addAppdetails()
{ $dev_id = $this->sessionStart();
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run())
{
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
echo "l";
$data1=$this->appFileupload();
echo "Break";
$data2=$this->appImageupload();
die;
foreach ($data1 as $dataArray)
{
$fileName=$dataArray['file_name'];
}
foreach ($data2 as $dataArray)
{
$imageName=$dataArray['file_name'];
}
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category,'file_name'=>$fileName,'image_name'=>$imageName,'dev_id'=>$dev_id);
$this->Dev_model->addApp($data);
//$this->appImageupload();
echo "yolo";
}
else
{
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appFileupload()
{
$config1['upload_path'] = './uploads/files';
$config1['allowed_types'] = 'apk|exe';
$this->load->library('upload', $config1);
if ( ! $this->upload->appFileUpload('file'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function appImageupload()
{
$config2['upload_path'] = './uploads/appImages';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = 1000000000;
$config2['max_width'] = 10240000;
$config2['max_height'] = 76800000;
$this->load->library('upload', $config2);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The output is as follows:
lBreak
Array ( [error] =>
The filetype you are attempting to upload is not allowed.
)
So, if I exchange the positions of appFileupload() and appImageupload() then it will give the same error for 'apk|exe' file and right now it is giving the error for appImageupload(). If you will ask how do I know about this? Then the answer is, I have checked their folder one gets uploaded but not the other.
CodeIgniter version is: 3.x
Add * in place of another type.
$config['allowed_types'] = '*';
I am just suggesting this for test purpose
Edit:
I am not sure but this will be helpful.
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Well Lol, I'm answering my own question.
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use:
$this->upload->initialize($config2);

Error submitting a form with upload pic option. PHP Codeigniter

I've been trying to upload a pic to a folder and store its path in the database, my code seems to work correctly, but no it's not, After i click submit button, it goes to a blank page.
Using Inspect element, Network option in my browser, when seeing the parameters sent
I see correct input from the text fields but for the image,
Content-Disposition: form-data; name="myimage"; filename="IMG_8971.JPG"
Content-Type: image/jpeg
Plus some other weirly looking characters and symbols like :
ÿØÿà
CONTROLLER:
private function setup_upload_option()
{
$config = array();
$config['upload_path'] = 'blog/uploads/';
$config['allowed_type']='jpg|jpeg|png|gif';
$config['encrypt_name']= TRUE;
$config['overwrite']=FALSE;
return $config;
}
public function post_new_blog()
{
$this->form_validation->set_rules('title', 'Title of the Blog', 'trim|required');
$this->form_validation->set_rules('desc', 'Content of the Blog', 'trim|required');
$this->form_validation->set_rules('tags', 'Tags fo the blog', 'trim|required');
if($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('fail', validation_errors());
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in));
}
else {
$this->load->library('upload');
$files = $_FILES;
$count = count($_FILES['myimage']['name']);
for($i=0; $i<$count ;$i++)
{
$_FILES['myimage']['name'] = $files['myimage']['name'][$i];
$_FILES['myimage']['type'] = $files['myimage']['type'][$i];
$_FILES['myimage']['size'] = $files['myimage']['size'][$i];
$_FILES['myimage']['tmp_name'] = $files['myimage']['tmp_name'][$i];
$this->upload->initialize($this->setup_upload_option());
if($this->upload->do_upload()==TRUE)
{
$data = $this->upload->data();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'blog/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['height'] = 200;
$config['width'] = 200;
$this->load->library('image_lib', $config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$mydata = $this->session->all_userdata();
$dataarray = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
'blog_image_name' => $data['orig_name'],
'blog_image' => $data['full_path'],
'date_posted' => date(" jS \of F Y "),
'posted_by' => $mydata['username']
);
$this->main_model->save_new_posts($dataarray);
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in, 'success' => 'Blog was posted successfully',$dataarray));
}
}
}
}
MODEL:
public function save_new_posts($dataarray)
{
$this->db->insert('blogs', $dataarray);
if($this->db->affected_rows()>0)
{
return true;
}
}
i have code that always works, it is some what different from you method i hope it will help you.
$imgpath='uploads/profile_pic/';
$all_img="";
if($_FILES["profile_pic"]['name'])//form input type file
{
$path_parts = pathinfo($_FILES["profile_pic"]["name"]);
$image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
$all_img.=$image_path;
move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path);
$data['cm_user_profile_pic']=$all_img;//store image name in array
}

accessing 'blog' functionality / template in FUEL CMS

I'm having trouble getting the "stock" blog functionality / template working within FUEL CMS.
I have read that it is already there, stock with the download configuration of the CMS; I have also tried creating one from scratch and uploading a 'blog' theme from a project found in GitHub. None have worked so far.
I found the blog variable at:
_variables/global.php
I have created a 'blog' controller via interpretation of (gappy) docs.
By adding the below code within it; then making a corresponding 'blog.php' view. I get nothing but a 404 error.
<?php
class Blog extends CI_Controller {
public function view($page = 'home')
{
//you can acesse this http://example.com/blog/view/
}
public function new($page = 'home')
{
//you can acesse this http://example.com/blog/new/
}
}
Within the modules folder. I found this 'stock' blog controller file. But don't know how to use it? found at: /fuel/modules/blog/controller/blog.php
<?php
require_once(MODULES_PATH.'/blog/libraries/Blog_base_controller.php');
class Blog extends Blog_base_controller {
function __construct()
{
parent::__construct();
}
function _remap()
{
$year = ($this->uri->rsegment(2) != 'index') ? (int) $this->uri->rsegment(2) : NULL;
$month = (int) $this->uri->rsegment(3);
$day = (int) $this->uri->rsegment(4);
$slug = $this->uri->rsegment(5);
$limit = (int) $this->fuel->blog->config('per_page');
$view_by = 'page';
// we empty out year variable if it is page because we won't be querying on year'
if (preg_match('#\d{4}#', $year) && !empty($year) && empty($slug))
{
$view_by = 'date';
}
// if the first segment is id then treat the second segment as the id
else if ($this->uri->rsegment(2) === 'id' && $this->uri->rsegment(3))
{
$view_by = 'slug';
$slug = (int) $this->uri->rsegment(3);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
redirect($post->url);
}
}
else if (!empty($slug))
{
$view_by = 'slug';
}
// set this to false so that we can use segments for the limit
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache))
{
$output =& $cache;
}
else
{
$vars = $this->_common_vars();
if ($view_by == 'slug')
{
return $this->post($slug);
}
else if ($view_by == 'date')
{
$page_title_arr = array();
$posts_date = mktime(0, 0, 0, $month, $day, $year);
if (!empty($day)) $page_title_arr[] = $day;
if (!empty($month)) $page_title_arr[] = date('M', strtotime($posts_date));
if (!empty($year)) $page_title_arr[] = $year;
// run before_posts_by_date hook
$hook_params = array('year' => $year, 'month' => $month, 'day' => $day, 'slug' => $slug, 'limit' => $limit);
$this->fuel->blog->run_hook('before_posts_by_date', $hook_params);
$vars = array_merge($vars, $hook_params);
$vars['page_title'] = $page_title_arr;
$vars['posts'] = $this->fuel->blog->get_posts_by_date($year, (int) $month, $day, $slug);
$vars['pagination'] = '';
}
else
{
$limit = $this->fuel->blog->config('per_page');
$this->load->library('pagination');
$config['uri_segment'] = 3;
$offset = $this->uri->segment($config['uri_segment']);
$this->config->set_item('enable_query_strings', FALSE);
$config = $this->fuel->blog->config('pagination');
$config['base_url'] = $this->fuel->blog->url('page/');
//$config['total_rows'] = $this->fuel->blog->get_posts_count();
$config['page_query_string'] = FALSE;
$config['per_page'] = $limit;
$config['num_links'] = 2;
//$this->pagination->initialize($config);
if (!empty($offset))
{
$vars['page_title'] = lang('blog_page_num_title', $offset, $offset + $limit);
}
else
{
$vars['page_title'] = '';
}
// run before_posts_by_date hook
$hook_params = array('offset' => $offset, 'limit' => $limit, 'type' => 'posts');
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
$vars['offset'] = $offset;
$vars['limit'] = $limit;
$vars['posts'] = $this->fuel->blog->get_posts_by_page($limit, $offset);
// run hook again to get the proper count
$hook_params['type'] = 'count';
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
//$config['total_rows'] = count($this->fuel->blog->get_posts_by_page());
$config['total_rows'] = $this->fuel->blog->get_posts_count();
// create pagination
$this->pagination->initialize($config);
$vars['pagination'] = $this->pagination->create_links();
}
// show the index page if the page doesn't have any uri_segment(3)'
$view = ($this->uri->rsegment(2) == 'index' OR ($this->uri->rsegment(2) == 'page' AND !$this->uri->segment(3))) ? 'index' : 'posts';
$output = $this->_render($view, $vars, TRUE);
$this->fuel->blog->save_cache($cache_id, $output);
}
$this->output->set_output($output);
}
function post($slug = null)
{
if (empty($slug))
{
redirect_404();
}
$this->load->library('session');
$blog_config = $this->fuel->blog->config();
// run before_posts_by_date hook
$hook_params = array('slug' => $slug);
$this->fuel->blog->run_hook('before_post', $hook_params);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
$vars = $this->_common_vars();
$vars['post'] = $post;
$vars['user'] = $this->fuel->blog->logged_in_user();
$vars['page_title'] = $post->title;
$vars['next'] = $this->fuel->blog->get_next_post($post);
$vars['prev'] = $this->fuel->blog->get_prev_post($post);
$vars['slug'] = $slug;
$vars['is_home'] = $this->fuel->blog->is_home();
$antispam = md5(random_string('unique'));
$field_values = array();
// post comment
if (!empty($_POST))
{
$field_values = $_POST;
// the id of "content" is a likely ID on the front end, so we use comment_content and need to remap
$field_values['content'] = $field_values['new_comment'];
unset($field_values['antispam']);
if (!empty($_POST['new_comment']))
{
$vars['processed'] = $this->_process_comment($post);
}
else
{
add_error(lang('blog_error_blank_comment'));
}
}
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache) AND empty($_POST))
{
$output =& $cache;
}
else
{
$this->load->library('form');
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
$captcha = $this->_render_captcha();
$vars['captcha'] = $captcha;
}
$vars['thanks'] = ($this->session->flashdata('thanks')) ? blog_block('comment_thanks', $vars, TRUE) : '';
$vars['comment_form'] = '';
$this->session->set_userdata('antispam', $antispam);
if ($post->allow_comments)
{
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$this->load->library('form_builder', $blog_config['comment_form']);
$fields['author_name'] = array('label' => 'Name', 'required' => TRUE);
$fields['author_email'] = array('label' => 'Email', 'required' => TRUE);
$fields['author_website'] = array('label' => 'Website');
$fields['new_comment'] = array('label' => 'Comment', 'type' => 'textarea', 'required' => TRUE);
$fields['post_id'] = array('type' => 'hidden', 'value' => $post->id);
$fields['antispam'] = array('type' => 'hidden', 'value' => $antispam);
if (!empty($vars['captcha']))
{
$fields['captcha'] = array('required' => TRUE, 'label' => 'Security Text', 'value' => '', 'after_html' => ' <span class="captcha">'.$vars['captcha']['image'].'</span><br /><span class="captcha_text">'.lang('blog_captcha_text').'</span>');
}
// now merge with config... can't do array_merge_recursive'
foreach($blog_config['comment_form']['fields'] as $key => $field)
{
if (isset($fields[$key])) $fields[$key] = array_merge($fields[$key], $field);
}
if (!isset($blog_config['comment_form']['label_layout'])) $this->form_builder->label_layout = 'left';
if (!isset($blog_config['comment_form']['submit_value'])) $this->form_builder->submit_value = 'Submit Comment';
if (!isset($blog_config['comment_form']['use_form_tag'])) $this->form_builder->use_form_tag = TRUE;
if (!isset($blog_config['comment_form']['display_errors'])) $this->form_builder->display_errors = TRUE;
$this->form_builder->form_attrs = 'method="post" action="'.site_url($this->uri->uri_string()).'#comments_form"';
$this->form_builder->set_fields($fields);
$this->form_builder->set_field_values($field_values);
$this->form_builder->set_validator($this->blog_comments_model->get_validation());
$vars['comment_form'] = $this->form_builder->render();
$vars['fields'] = $fields;
}
$output = $this->_render('post', $vars, TRUE);
// save cache only if we are not posting data
if (!empty($_POST))
{
$this->fuel->blog->save_cache($cache_id, $output);
}
}
if (!empty($output))
{
$this->output->set_output($output);
return;
}
}
else
{
show_404();
}
}
function _process_comment($post)
{
if (!is_true_val($this->fuel->blog->config('allow_comments'))) return;
$notified = FALSE;
// check captcha
if (!$this->_is_valid_captcha())
{
add_error(lang('blog_error_captcha_mismatch'));
}
// check that the site is submitted via the websit
if (!$this->_is_site_submitted())
{
add_error(lang('blog_error_comment_site_submit'));
}
// check consecutive posts
if (!$this->_is_not_consecutive_post())
{
add_error(lang('blog_error_consecutive_comments'));
}
$this->load->module_model(BLOG_FOLDER, 'blog_users_model');
$user = $this->blog_users_model->find_one(array('fuel_users.email' => $this->input->post('author_email', TRUE)));
// create comment
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$comment = $this->blog_comments_model->create();
$comment->post_id = $post->id;
$comment->author_id = (!empty($user->id)) ? $user->id : NULL;
$comment->author_name = $this->input->post('author_name', TRUE);
$comment->author_email = $this->input->post('author_email', TRUE);
$comment->author_website = $this->input->post('author_website', TRUE);
$comment->author_ip = $_SERVER['REMOTE_ADDR'];
$comment->content = trim($this->input->post('new_comment', TRUE));
$comment->date_added = NULL; // will automatically be added
//http://googleblog.blogspot.com/2005/01/preventing-comment-spam.html
//http://en.wikipedia.org/wiki/Spam_in_blogs
// check double posts by IP address
if ($comment->is_duplicate())
{
add_error(lang('blog_error_comment_already_submitted'));
}
// if no errors from above then proceed to submit
if (!has_errors())
{
// submit to akisment for validity
$comment = $this->_process_akismet($comment);
// process links and add no follow attribute
$comment = $this->_filter_comment($comment);
// set published status
if (is_true_val($comment->is_spam) OR $this->fuel->blog->config('monitor_comments'))
{
$comment->published = 'no';
}
// save comment if saveable and redirect
if (!is_true_val($comment->is_spam) OR (is_true_val($comment->is_spam) AND $this->fuel->blog->config('save_spam')))
{
if ($comment->save())
{
$notified = $this->_notify($comment, $post);
$this->load->library('session');
$vars['post'] = $post;
$vars['comment'] = $comment;
$this->session->set_flashdata('thanks', TRUE);
$this->session->set_userdata('last_comment_ip', $_SERVER['REMOTE_ADDR']);
$this->session->set_userdata('last_comment_time', time());
redirect($post->url);
}
else
{
add_errors($comment->errors());
}
}
else
{
add_error(lang('blog_comment_is_spam'));
}
}
return $notified;
}
// check captcha validity
function _is_valid_captcha()
{
$valid = TRUE;
// check captcha
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
if (!$this->input->post('captcha'))
{
$valid = FALSE;
}
else if (!is_string($this->input->post('captcha')))
{
$valid = FALSE;
}
else
{
$post_captcha_md5 = $this->_get_encryption($this->input->post('captcha'));
$session_captcha_md5 = $this->session->userdata('comment_captcha');
if ($post_captcha_md5 != $session_captcha_md5)
{
$valid = FALSE;
}
}
}
return $valid;
}
// check to make sure the site issued a session variable to check against
function _is_site_submitted()
{
return ($this->session->userdata('antispam') AND $this->input->post('antispam') == $this->session->userdata('antispam'));
}
// disallow multiple successive submissions
function _is_not_consecutive_post()
{
$valid = TRUE;
$time_exp_secs = $this->fuel->blog->config('multiple_comment_submission_time_limit');
$last_comment_time = ($this->session->userdata('last_comment_time')) ? $this->session->userdata('last_comment_time') : 0;
$last_comment_ip = ($this->session->userdata('last_comment_ip')) ? $this->session->userdata('last_comment_ip') : 0;
if ($_SERVER['REMOTE_ADDR'] == $last_comment_ip AND !empty($time_exp_secs))
{
if (time() - $last_comment_time < $time_exp_secs)
{
$valid = FALSE;
}
}
return $valid;
}
// process through akisment
function _process_akismet($comment)
{
if ($this->fuel->blog->config('akismet_api_key'))
{
$this->load->module_library(BLOG_FOLDER, 'akismet');
$akisment_comment = array(
'author' => $comment->author_name,
'email' => $comment->author_email,
'body' => $comment->content
);
$config = array(
'blog_url' => $this->fuel->blog->url(),
'api_key' => $this->fuel->blog->config('akismet_api_key'),
'comment' => $akisment_comment
);
$this->akismet->init($config);
if ( $this->akismet->errors_exist() )
{
if ( $this->akismet->is_error('AKISMET_INVALID_KEY') )
{
log_message('error', 'AKISMET :: Theres a problem with the api key');
}
elseif ( $this->akismet->is_error('AKISMET_RESPONSE_FAILED') )
{
log_message('error', 'AKISMET :: Looks like the servers not responding');
}
elseif ( $this->akismet->is_error('AKISMET_SERVER_NOT_FOUND') )
{
log_message('error', 'AKISMET :: Wheres the server gone?');
}
}
else
{
$comment->is_spam = ($this->akismet->is_spam()) ? 'yes' : 'no';
}
}
return $comment;
}
// strip out
function _filter_comment($comment)
{
$this->load->helper('security');
$comment_attrs = array('content', 'author_name', 'author_email', 'author_website');
foreach($comment_attrs as $filter)
{
$text = $comment->$filter;
// first remove any nofollow attributes to clean up... not perfect but good enough
$text = preg_replace('/<a(.+)rel=["\'](.+)["\'](.+)>/Umi', '<a$1rel="nofollow"$3>', $text);
// $text = str_replace('<a ', '<a rel="nofollow"', $text);
$text = strip_image_tags($text);
$comment->$filter = $text;
}
return $comment;
}
function _notify($comment, $post)
{
// send email to post author
if (!empty($post->author))
{
$config['wordwrap'] = TRUE;
$this->load->library('email', $config);
$this->email->from($this->fuel->config('from_email'), $this->fuel->config('site_name'));
$this->email->to($post->author->email);
$this->email->subject(lang('blog_comment_monitor_subject', $this->fuel->blog->config('title')));
$msg = lang('blog_comment_monitor_msg');
$msg .= "\n".fuel_url('blog/comments/edit/'.$comment->id)."\n\n";
$msg .= (is_true_val($comment->is_spam)) ? lang('blog_email_flagged_as_spam')."\n" : '';
$msg .= lang('blog_email_published').": ".$comment->published."\n";
$msg .= lang('blog_email_author_name').": ".$comment->author_name."\n";
$msg .= lang('blog_email_author_email').": ".$comment->author_email."\n";
$msg .= lang('blog_email_author_website').": ".$comment->author_website."\n";
$msg .= lang('blog_email_author_ip').": ".gethostbyaddr($comment->author_ip)." (".$comment->author_ip.")\n";
$msg .= lang('blog_email_content').": ".$comment->content."\n";
$this->email->message($msg);
return $this->email->send();
}
else
{
return FALSE;
}
}
function _render_captcha()
{
$this->load->library('captcha');
$blog_config = $this->config->item('blog');
$assets_folders = $this->config->item('assets_folders');
$blog_folder = MODULES_PATH.BLOG_FOLDER.'/';
$captcha_path = $blog_folder.'assets/captchas/';
$word = strtoupper(random_string('alnum', 5));
$captcha_options = array(
'word' => $word,
'img_path' => $captcha_path, // system path to the image
'img_url' => captcha_path('', BLOG_FOLDER), // web path to the image
'font_path' => $blog_folder.'fonts/',
);
$captcha_options = array_merge($captcha_options, $blog_config['captcha']);
if (!empty($_POST['captcha']) AND $this->session->userdata('comment_captcha') == $this->input->post('captcha'))
{
$captcha_options['word'] = $this->input->post('captcha');
}
$captcha = $this->captcha->get_captcha_image($captcha_options);
$captcha_md5 = $this->_get_encryption($captcha['word']);
$this->session->set_userdata('comment_captcha', $captcha_md5);
return $captcha;
}
function _get_encryption($word)
{
$captcha_md5 = md5(strtoupper($word).$this->config->item('encryption_key'));
return $captcha_md5;
}
}
My goal is:
1.) Enable 'Blog' Module / template / functionality and understand how I did it. I find the docs lacking, I'm also new at code igniter so that could be why. I just want the most basic way to do this for now.
And 2.) I want to create a page 'from scratch' that resolves on the dashboard side as well. I have created pages in /views/ but they resolve with that whole string /fuel/application/views/page/ I want to create a normal page without all that in the URL. I have tried creating corresponding controllers even variables and haven't had much luck!!!!!!!
As of FUEL CMS 1.0 the blog module is no longer bundled with the CMS by default. You would need to do the following:
Download & setup FUEL CMS per the install instructions here: https://github.com/daylightstudio/FUEL-CMS
Next, once you've got that up and running you can download & setup the blog module per the instructions here: https://github.com/daylightstudio/FUEL-CMS-Blog-Module
Once the blog is setup, you should be able to access it at "yourdomain.com/blog". As far as creating themes, there is a views/themes folder in the blog module which contains a default theme and also where you can setup your custom theme. Additional information about the blog module & theming can be found here http://docs.getfuelcms.com/modules/blog

Categories