Categories
Codeigniter

Codeigniter 2.20 – Uploading files to a folder and Inserting in Database table

Back to CodeIgniter Tutorials

In this tutorial, I am going to show how to upload multiple files into a folder and insert its name in a database table. In an application, we may either have to upload a single or multiple files. Take freelancer.com portfolio page for instance. They allow freelancers to upload multiple files for the same portfolio item. So our goal here is the same. The goals are:

  1. Take one or multiple files as an input.
  2. Once submit is pressed, the file is uploaded.
  3. When the file is uploaded, an its name is inserted in the database table.

In order to understand this tutorial, you must know how to install, and use codeigniter. Follow the following links if you want to learn these steps.

Now lets begin!

In order to upload a file to a folder, first a view is built that takes File as an input and has a submit button. I am using a controller named c_upload and my view is v_uploader

VIEW: v_uploader

I am taking multiple files as an input.

<?php //echo base_url('index.php/c_uploader/do_upload'); ?>



Select One or multiple FilesAllowed files: gif, png, png, pdf

If you wish to upload a single file, then all you need to do is to remove the “multiple” keyword in line 5. Here is the code.

<?php //echo base_url('index.php/c_uploader/do_upload'); ?>



Select One or multiple FilesAllowed files: gif, png, png, pdf

 

CONTROLLER: c_upload

From view, I am calling a function called do_upload(). I also have another function set_upload_options().

Load these helpers

$this->load->helper("URL", "DATE", "URI", "FORM");

Load these libraries

$this->load->library('form_validation');
$this->load->library('upload');

Load this model

$this->load->model('m_upload');

Finally, here are the functions

Note: In set_upload_options() function, you can configure upload path

function do_upload(){

    $this->load->library('upload');

    $files = $_FILES;
    $cpt = count($_FILES['userfile']['name']);
    for($i=0; $i<$cpt; $i++){
        $_FILES['userfile']['name']		= $files['userfile']['name'][$i];
        $_FILES['userfile']['type']		= $files['userfile']['type'][$i];
        $_FILES['userfile']['tmp_name']	= $files['userfile']['tmp_name'][$i];
        $_FILES['userfile']['error']	= $files['userfile']['error'][$i];
        $_FILES['userfile']['size']		= $files['userfile']['size'][$i];    

	    $this->upload->initialize($this->set_upload_options());
	    $this->upload->do_upload();

	    $upload_data 	= $this->upload->data();
		    $file_name 	=   $upload_data['file_name'];
		    $file_type 	=   $upload_data['file_type'];
		    $file_size 	=   $upload_data['file_size'];

	    // Output control
			$data['getfiledata_file_name'] = $file_name;
			$data['getfiledata_file_type'] = $file_type;
			$data['getfiledata_file_size'] = $file_size;
        // Insert Data for current file
            $this->m_upload->insertNotices($form_input_Data);

        //Create a view containing just the text "Uploaded successfully"
		$this->load->view('upload_success', $data);

	}

}
private function set_upload_options(){   
	//  upload an image options
    $config = array();
    $config['upload_path'] = './fileselif/';
    $config['allowed_types'] = 'gif|jpg|png|pdf';
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE;


    return $config;
}

Now the Model code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class M_upload extends CI_Model {

	function __construct() {
        parent::__construct();
    }

	function M_notice (){
		parent::Model();
	}
	function insertNotices($arrayOfNoticeFiles){
		$tableName  = "t_notices";
		$inputArray = $arrayOfNoticeFiles;

		$data = array(
			'document_foldername'				=> $inputArray["document_foldername"],
			'document_filename'					=> $inputArray["document_filename"]
		);

		$this->db->insert($tableName, $data); 
	}


}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

These are the steps explaining the program.

Back to CodeIgniter Tutorials

Categories
Codeigniter

Hybirdigniter config file (hybridauthlib.php) guide

Hybrdigniter is an integration of HybridAuth and CodeIgniter. In this sub-tutorial, I am going to explain the usage of /applicaion/config/hybridauthlib.php which is found in the installation of HybridIgniter.

Get HybridIgniter-master

Complete Tutorial : Social media login setup in Codeigniter Site using Hybridigniter

The complete File

[expand]

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/

// ----------------------------------------------------------------------------------------
//	HybridAuth Config file: http://hybridauth.sourceforge.net/userguide/Configuration.html
// ----------------------------------------------------------------------------------------

$config =
	array(
		// set on "base_url" the relative url that point to HybridAuth Endpoint
		'base_url' => '/hauth/endpoint',

		"providers" => array (
			// openid providers
			"OpenID" => array (
				"enabled" => true
			),

			"Yahoo" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"AOL"  => array (
				"enabled" => true
			),

			"Google" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"Facebook" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"Twitter" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			// windows live
			"Live" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" )
			),

			"MySpace" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			"LinkedIn" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			"Foursquare" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" )
			),
		),

		// if you want to enable logging, set 'debug_mode' to true  then provide a writable file by the web server on "debug_file"
		"debug_mode" => (ENVIRONMENT == 'development'),

		"debug_file" => APPPATH.'/logs/hybridauth.log',
	);


/* End of file hybridauthlib.php */
/* Location: ./application/config/hybridauthlib.php */

 

[/expand]

Enable or Disable a social media service

This feature allows you to Enable or Disable social media services. For example, if I wish to disable twitter, then I will do the following:
FROM

"Twitter" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

To

"Twitter" => array (
				"enabled" => false,
				"keys"    => array ( "key" => "", "secret" => "" )
			),
Add Social Media Developer “key”/”id” and “secret”

The config file also allows you to add developer app specific key/id and secret code in the config file that allows integration for that specific app.

For example, look at the highlighted lines below:

$config =
	array(
		// set on "base_url" the relative url that point to HybridAuth Endpoint
		'base_url' => '/hauth/endpoint',

		"providers" => array (
			// openid providers
			"OpenID" => array (
				"enabled" => true
			),

			"Yahoo" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"AOL"  => array (
				"enabled" => true
			),

			"Google" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"Facebook" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" ),
			),

			"Twitter" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			// windows live
			"Live" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" )
			),

			"MySpace" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			"LinkedIn" => array (
				"enabled" => true,
				"keys"    => array ( "key" => "", "secret" => "" )
			),

			"Foursquare" => array (
				"enabled" => true,
				"keys"    => array ( "id" => "", "secret" => "" )
			),
		),

		// if you want to enable logging, set 'debug_mode' to true  then provide a writable file by the web server on "debug_file"
		"debug_mode" => (ENVIRONMENT == 'development'),

		"debug_file" => APPPATH.'/logs/hybridauth.log',
	);
Understand this to avoid “providers” variable error

While developing, you might happen to see an error saying that the $providers variable is not defined. Well, please understand that this is where the providers array is. This will expand to the Controller and then lead to the View.

$config =
	array(
		// set on "base_url" the relative url that point to HybridAuth Endpoint
		'base_url' => '/hauth/endpoint',

		"providers" => array (
			// openid providers
			"OpenID" => array (
				"enabled" => true
			),

I hope this helps. The tutorial in future will continue HERE

Please do share this blog post and do comment if you liked this guide.

Categories
Codeigniter Programming

Codeigniter 2.20 – Learn how to make live search using Codeigniter

Back to CodeIgniter Tutorials

You may have seen live search <input> boxes all over the internet. Here is how to make that live search in reference to the design of the following image using Codeigniter 2.20 and 3.0.

codeigniter_json_encode1
Example of live search using input box

This technique will use the following steps.

  1. User types in an input box.
  2. A call is sent to controller with input parameters taken from input box.
  3. Controller calls model.
  4. Model searches database and returns with or without an input to the controller.
  5. Controller uses json_encode() on result of model and sends the data to view.
  6. View receives data from controller and shows it on the interface.

Please note that you must have a working codeigniter installation and database connection. You can use XAMPP for that if you need to test.

MODEL

Create a table of hotels and use the following model

function select_table_column($table_name, $column_name,$criteria = null, $id = null)
{
	$this->db->select($column_name);
	$this->db->from($table_name);

	if (!is_null($id)){
		$this->db->where('id', $id);
	}

	$this->db->order_by('id', 'desc');

	return $this->db->get()->result();
}

VIEW

Then set up a view and add jquery and bootstrap support along with bootstrap-typeahead

<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>">  

 Controller

Finally, use the following code in a controller function to call the model from view.

	//	Controller Code
	$get_Manufacturers = $this->M_selections->select_table_column('hotels_table',hotel_'name');
	$encoded_Manufacturers = json_encode($get_Manufacturers);
	$data['manufacturers'] = $encoded_Manufacturers;

	//	Now, you have json encoded hotels list

With this done, you will now be able to use live search in your interface.

I hope you find this helpful. If you have any questions, then please post in the comments. I will be glad to help.

Kind Regards,

Codeonion

Back to CodeIgniter Tutorials

Categories
General

Install and run XAMPP on Windows and Linux

In this basic tutorial, you will learn how to install XAMPP. XAMPP is used to run Apache HTTP Server, MySQL database, and interprets scripts written in the PHP. It is a great tool to test or host a website on your own machine. Lets see how install and start it.

  1. Download and Install.
    • Install for Windows here
    • Linux (Knoppix mainly) Installation here and Please follow that guide only if you are Linux User.
  2. Now run the program.
  3. The control panel will open. You need to start the Apache and MySQL services and make sure that they are green.

xampp

 

Now, all you need to do is the browse to the installation folder of XAMPP and get to the htdocs folder. Assuming you installed XAMPP in c:\ then look for the following path.

C:\xampp\htdocs

Now make a folder named mywebsite inside the htdocs folder and inside it, make a file named index.php like this.

C:\xampp\htdocs\mywebsite\index.php

Open and edit the index.php file and add the following code.

<?php

echo "XAMPP has been installed and PHP is working fine".

?>

Now, go to your browser, and visit one of the following links.

If you see the message in the above code. then you have not only installed XAMPP but you are now able to work with PHP.

Categories
Codeigniter

Codeigniter 2.20 – Making your own home page

Back to CodeIgniter Tutorials

Now that  you have learned how to install codeigniter, it would be prefereable to replace the default codeigniter welcome page by something that we have made. By the end of this tutorial, when you will visit localhost/yourapp you will be presented with your own home page instead of the the default codeigniter Welcome page.

Install Codeigniter

First install Codeigniter. And make sure that you get the following page when you go to localhost/yourapp

Codeigniter installing xampp

Now we can get started.

Setting custom controller (which is first loaded)

In codeigniter, when you visit www.yourapp.com, a default controller is run by the server. This can be customized by editing a config file. This file is located at

localhost/yourapp/application/config/routes.php

Open this file and look for the following line:

$route['default_controller'] = "welcome";

Replace this line with a line which points out to our own controller (which we will make shortly)

$route['default_controller'] = "homecontroller";

We have just told codeigniter to point to our own controller instead of the default welcome controller which calls the welcome_message view. If you visit your website nowcodeigniter will try to access homecontroller but that does not exist yet. Lets make one!

Creating our controller

  1. Go to localhost/yourapp/application/controllers/
  2. Create a new file named homecontroller.php
  3. Add the following code in this file and the save it.
public function index()
	{
		$this->load->helper('url');
		$this->load->view('homepage');
	}

You have just created a controller which is pointing towards the view homepage. Lets create a view to finish the ritual.

Creating our View

  1. Go to localhost/yourapp/application/views/
  2. Create a new file named homepage.php
  3. Add the some HTML code to it like a paragraph. Maybe mention a Hello World!

You have just created a view which has our Hello World. Now you can use CSS styling to create more detailed websites.

 Lets test it

  1. Go to localhost/yourapp in your browser.
  2. You will see your new page/view 😀

Congratulations!

You have not only learnt how to install codeigniter, but also learnt how to set it up and make your own home page. In the next step, we will learn how to manage assets in codeigniter such as png, jpg, mp3, js, css, etc files.

Back to CodeIgniter Tutorials

Categories
Codeigniter

CodeIgniter 2.20 – How to set up in XAMPP

This is the first part of the CodeIgniter 2.20 tutorials series. In this part, you will learn how simple it is to install CodeIgniter in XAMPP.

Lets assume that the web application you are making is “yourapp”.

  1. First go to CodeIgniter website and download it.
  2. Now go to your www or htdocs folder in XAMPP and create a new folder for your application. Lets name it yourapp.

    CI_in_xampp

  3. Copy the downloaded CodeIgniter .zip file into your folder (yourapp) and unzip it. You will have a folder looking like this.
  4. Now go to the following link in your browser: http://localhost/yourapp/
  5. You will be presented with the welcome screen of codeigniter.

Codeigniter default welcome screen

At this stage, you have CodeIgniter ready for your application development. The page you are seeing is a view at application/views/welcome_message.php which is loaded using the controller at application/controllers/welcome.php

Back to CodeIgniter Tutorials

Categories
Programming

Learn how to get rid of the “You may use these HTML tags and attributes” from WordPress

 

WordPress is amazing and facilitates bloggers in every aspect. Everything can be adjusted to personal taste. But there is one thing and many people including myself would like to be removed from their pages.

If you look at the bottom of your wordpress pages, then just below the comments box, you will see this.

[edsanimate animation=”tada” delay=”12″ infinite_animation=”yes” animate_on=””]

The HTML suggestions concerning the comment text

[/edsanimate]

 

With or without the highlighter and regardless of the theme selected, this looks like the HTML code itself. It is just like handing over the engine and tires to the driver when he comes to buy a car. Lets get rid of that!

If we look at the code of my page, it is easy to spot the CLASS and ID of the HTML element responsible for that text.

[edsanimate animation=”bounceInUp” delay=”1″ duration=”3″ infinite_animation=”no” animate_on=”scroll”]

tags2

[/edsanimate]

Both the ID and the CLASS of that element is form-allowed-tags. In CSS, we can make an HTML element invisible using the following code.

.class_of_the_element {
	display: none;
}

/* OR */

#id_of_the_element {
	display: none;
}

Now, we will simply add our CSS to the wordpress using the following menu.

[edsanimate animation=”flip” delay=”2″ infinite_animation=”no” animate_on=”scroll”]

Click to enlarge!
Click to enlarge!

[/edsanimate]

Basically, click Appearance and then go to Edit CSS. Then paste your the following code and then click Save Stylesheet.

.form-allowed-tags {
	display: none;
}

Now if you visit your page again, you will see that is is gone. The “You may use these HTML tags and attributes” message used to be at the highlighted section below.

[edsanimate animation=”zoomInRight” delay=”2″ infinite_animation=”no” animate_on=”scroll”]

You may use these HTML tags and attributes is gone as highlighted
You may use these HTML tags and attributes is gone as highlighted

[/edsanimate]

Congratulations! now your blog looks better and your comments section will be pleasant 🙂

[edsanimate animation=”shake” infinite_animation=”yes” animate_on=”scroll”]

And please, do SHARE! 😀

[/edsanimate]

 

Categories
Android General

How to switch between Activities in Android

To switch Menus/Activities in Android App
public void backToMainMenu(View view){ 
	Intent i = new Intent(getApplicationContext(), PreviousMenuClassName.class);
 	startActivity(i);
}
  1. I called this function in XML file as android:onClick=”backToMainMenu” in the attributes of button.
  2. The function must be public and have only one attribute i.e. “View view”
  3. You can call “i” whatever you wish.
  4. “PreviousMenuClassName” is the name of the Activity where you want to go after clicking the button.
Categories
Android

Android adding camera in app

So why not use the camera that already exists in your Android Phone!

First put the following in AndroidManifest.xml before the <application…></application> tag

<uses-feature android:name="android.hardware.camera" />

Then go to the MainActivity class or wherever you want to call “Camera opening function”. Add the following function:

public void startCamera(View view){ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(takePictureIntent); }
  1. Here, startCamera is a function called when a button is pressed.
  2. The default camera app of your phone opens and you will have all the advanced features without any work.
  3. Done 😀
Categories
Programming

Knoppix touchpad click workaround

Problem: I can’t click with my touchpad in Knoppix. I can use USB/bluetooth mouse normally but the Laptop’s touchpad can’t be tapped to click.

Solution:

  1. Go to terminal and enter the following

    knoppix@Microknoppix:~$ synclient Tapbutton1=1

  2. Now try closing the terminal by tapping the [X] in the terminal window and it will work.

Note: This only works for the current session which means if you restart knoppix, the touchpad will be back to unclickable. I will update the post as soon as I discover the permanent solution to the problem. But as far as I am concerned, I can do that on every boot 🙂