Guide for Developing a Business Website for a Small Business

1. Analyse the Basic Purpose of Your Website

Your website is always a front face of your online business, so it’s been very clear with the information you are providing on that. Because it’s gives the information about your company and services. Clarify your business purpose firstly and make your website accordingly. Don’t make it difficult for the user or customer, make it easy to use and may customer easily found your services and terms.

Think about from the prospective of your user, what he exactly wants and which information is useful for those. Whatever your fundamental goal is, you need to make your website according to your user to get success in business.

2. Decide Your Domain Name Smartly

Domain name is always the key in the present business scenario because of the high competition of the market. So take your domain name which reflect your business or services just in one word. You need to be descriptive with your domain name that you can explain about your business in your domain name. Don’t confuse your user, just be simple and creative with your domain name. Once you found the creative domain name, just check availability with domain provider websites like Go Daddy and confirm your domain.

3. Choose a Web Host

Choosing a web host to manage your website on server is another import step to do. It’s totally based on your budget; you can get the shared host as well as lease-expensive option through internet search. Dedicating hosting cost you too much as a small business owner, so choose other option with proper analyzation first.

Before choosing a web host, you can go with some important steps to verify the host that how they react on your queries, how is the past reviews of that particular host, server location and reliability. Analysing all those facts you can take up the best host for your website.

4. Create Your Web Pages Smartly

A good website is always a full of relevant content and service pages according to the business need. To reach up to your customer or user you need to be very descriptive and clear with your service pages where user can easily relate with your niche services. Need to create maximum call-to-action buttons on website from where user can easily connect with you just at one click.

You need to properly mention about your business, staff, experiences and skills, it’s a most important part to do in the small business website. Your contact information should be easily accessible and viewable on your website and be clear what best solution you are providing in your field.

Also set up your payment system page properly if applicable on your website. Do your calculation properly about what amount you are taking; how much taxes people need to give it to you. Place your third party payment system properly with the proper instruction and make those easily visible to all.

5. Testing and Publishing of Your Website

Testing is the another important part of the web development process, through this you can check your website working fine with all the functionality you put up on that, running on all the browsers quite smoothly, images you are on to the website looks great, all the services mention clearly on to the related pages, URL structure is SEO friendly, web design is responsive or not, website loading speed is good or not.

After look on all those aspect, once you will get confirmation from your testing team you can do live your website for your users. As perfect website is the key for the quick business growth.

6. Market Your Website on Search Engines and Social Media

Online marketing is the key to success of every online business whether it’s small or big in the present business scenario. You have to market your business properly if you want to increase your audience reach in short period of time. Marketing is the online way to create new business opportunities, new clients or new customers.

Online marketing depends upon few factors like how well you do SEO (Search Engine Optimization) and SMO (Social Media Marketing) of your business website. So before hiring SEO company in India analyse all the things and then hire them for the services.

You can also take help of your social accounts like Facebook, Twitter, LinkedIn to promote your business in your surroundings, use niche groups or communities to spread your business information or services to more people and create new business opportunities through social media marketing.

7. Maintenance of Website

In the fast and competitive business environment maintenance is the another important aspect of web development. You need to be updated about your business and know what are the latest trends run into the market and do changes accordingly time to time.

You also need to check all the functionality you put on to the website are working properly on the regular basis. If you have software related business, then you need to update it on regular basis otherwise it’s in the danger and being hacked easily.

Those are some useful points which you can follow when planning to build a business website as a small business owner.

Types of Design Patterns – Singleton Pattern

Moving forward on design pattern as I discussed in previous blog about how we can Solving Design Problems by Design Patterns, so let’s discuss our first pattern Singleton Pattern.

Basically its a design pattern which ensures your system will have only one entry point to access it. It’s sometime very important to have exactly one instance e.g. Our database. In that we always want to have only one access point to maintain the security and similarly in some other scenario also it’s possible. Now as a programmer one can ask, how to ensure that a class has only one instance and prevent all other instances? Lets think a bit on this, A global variable/flag (boolean 0,1)? which will keep track of the instances. No a global variable can never keep track of it as it will not be accessible on other modules of our project. Then what? An experience architect would say that the better solution would be to make the class itself responsible for keeping track of its instance. The class itself only can ensure that no other instance of that is created. At this stage it might look very complex to you but think on it and read it carefully.

For php guys lets walk through the following code.. Syntax will not be different in other languages…

1
2
3
4
5
6
7
class myClass
{
public function myClass() { ... }
public function myMethod() { ... }
public function myNewMethod() { ... }
...
}
class myClass
{
public function myClass() { ... }
public function myMethod() { ... }
public function myNewMethod() { ... }
...
}

Now what happens if i want to use this class? simply by creating a new object

1
$classInstance = new myClass();
$classInstance = new myClass();

But we can create many instances for this class and that is what i want to prevent because i am going to show you how you can restrict multiple instances of this class. So how can we do that?

Like i wrote, the class itself will have to keep track of this and so our class becomes

1
2
3
4
5
6
7
8
9
10
11
12
13
class myClass {
 
//Variable responsible to keep track.
 
private static $m_pInstance;
 
//constructor
 
public function myClass() { ... }
public function myMethod() { ... }
public function myNewMethod() { ... }
...
}
class myClass {

//Variable responsible to keep track.

private static $m_pInstance;

//constructor

public function myClass() { ... }
public function myMethod() { ... }
public function myNewMethod() { ... }
...
}

Now one can ask why this “private static” thing is used here. Well it’s simple, i declared it private because a user has nothing to do with this variable and we don’t want it to be accessible and “static” because i want it to be a class variable so that it retains it’s value to keep track of instance of it’s class. Second thing that i will do is, i will make this constructor private. What?? Yes!! because we don’t want this class to be instantiated from outside of this class. By making it public we are allowing everybody to create instance of it, which we don’t want. Well what’s next? Will this guarantee for only one instance? Not yet. So far we have prohibited outsiders to use it directly not even a single time then now we have to implement the way it will be used only once. So to do that, i will add a very weird method to this class which will ensure that nobody can create any second instance of this class. So our new class becomes-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class myClass {
 
//Variable responsible to keep track.
 
private static $m_pInstance;
 
//constructor
 
private function myClass() { ... }
 
public static function createInstance() {
//self is used for accessing class members
if (!self::$m_pInstance)   {
self::$m_pInstance = new myClass();
}
 
return self::$m_pInstance;
 
}
 
public function myMethod() { ... }
public function myNewMethod() { ... }
...
}
class myClass {

//Variable responsible to keep track.

private static $m_pInstance;

//constructor

private function myClass() { ... }

public static function createInstance() {
//self is used for accessing class members
if (!self::$m_pInstance)   {
self::$m_pInstance = new myClass();
}

return self::$m_pInstance;

}

public function myMethod() { ... }
public function myNewMethod() { ... }
...
}

after reading above code intention should be clear that we have added this function to keep track of instances of the class. Let me explain me little bit about it, i have created a public function to make it accessible from anywhere and static because we are gonna access a static member of the class and we want this method to be available for use without creating any instance of the class. Rest is about checking for any other instance and allowing a instance to be created. So far so good but how shall we use it? Well it’s simple-

1
2
3
$classInstance = myClass::createInstance();
 
$response = $classInstance->myMethod();
$classInstance = myClass::createInstance();

$response = $classInstance->myMethod();

This was the implementation of singleton pattern. Post your comments for your queries.

Content Source: http://www.raakeshkumar.in/

Solving Design Problems by Design Patterns

Today i am gonna describe design patterns. The very first question that can arise in anyone’s mind is What is design pattern? Where we use it? Why we use it? Hold on… Lets go through this one by one.

What is a design pattern?

In simple sentence, a design pattern is a way to design our software/application. Each design pattern addresses a problem or set of problem and describe a solution for it. So these design patterns help us understand those problems and solve them effectively.

Designing object-oriented software is hard, and designing a good, reusable object-oriented software is even harder. We need to find objects, factor them into classes at the right granularity, define class interfaces and establish relationship among them to make a good software. Our software design should be flexible enough that can handle future problems and for modifications. This means it’s impossible to find exactly right design for any software but we can make it in such a way that can cover maximum solutions for future issues.

Why and where we use it?

It’s one of the most time taking process in any software design, as per my experience. And it takes a long time for someone to learn these design patterns from scratch. An experienced architect never solve any problem from first rules rather they use experience that have helped them in past. Consequently, we find recurring patterns of classes and their communications. These patterns solve some specific design problems and make object-oriented designs more flexible, elegant and reusable, which is the main philosophy behind object oriented systems.

So at this point now we are able to define what is a design pattern? Its a description of communicating objects and classes that are customized to solve a general design problem in a particular context.

So basically a design pattern has following elements –

  1. 1. Problem
  2. 2. Solution
  3. 3. Future consequences

Still one question can come into ones’ mind that How these design patterns solve design problems?

Well its a vast topic and lets walk through it.

Design patterns solve many problems object-oriented designers face.

Followings are few of them –

Designing appropriate objects – The most complex part of any object-oriented design is decomposing a system into objects. This is difficult because of many factors like our object should be reusable, it should address future problems, should be flexible etc. Think of a scenario where an architect designs a bad software, how costly that can be for the organization in future? So design patterns helps you identify your problems and create objects that can capture them.

Determining Object Level – Objects can vary in size. They can represent anything from hardware to the complete application. So how do we decide what should be an object? Design pattern solves this problem also.

In this context let me introduce you with very common terms of object-oriented design. Every operation declared by an object specifies the operation’s name, the objects it takes as parameters, and the return value. This is known as the operation’s signature. The set of all signatures defined by an object’s operations is called the interface to the object. An object’s interface characterizes the complete set of requests that can be sent to the object. An object is the set of operations it can perform and set of states it can be in. There are several kind of design patterns e.g. Abstract, Factory, Singleton etc. I will try to cover them in my next posts.

Content Source: http://www.raakeshkumar.in/

Configure Codeigniter with Twig

In my recent project i tried to integrate codeigniter with twig template engine with php-activerecord and so thought to share with everyone.

First you need to have codeigniter downloaded and extracted then download php-activerecord. Now lets integrate both:

1- Extract active record and put it inside /libraries folder so the directory structure becomes /application/libraries/php-activerecord.
2- Create a class Activerecord.php inside libraries folder itself with the following contents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 $db_values) {
                // Convert to dsn format
                $dsn[$name] = $db[$name]['dbdriver'] .
                    '://'   . $db[$name]['username'] .
                    ':'     . $db[$name]['password'] .
                    '@'     . $db[$name]['hostname'] .
                    '/'     . $db[$name]['database'];
            }
        } 
        
        // Initialize ActiveRecord
        ActiveRecord\Config::initialize(function($cfg) use ($dsn, $active_group){
            $cfg->set_model_directory(APPPATH.'/models');
            $cfg->set_connections($dsn);
            $cfg->set_default_connection($active_group);
        });
        
    }
}
 
/* End of file Activerecord.php */
/* Location: ./application/libraries/Activerecord.php */
 $db_values) {
            	// Convert to dsn format
            	$dsn[$name] = $db[$name]['dbdriver'] .
            		'://'   . $db[$name]['username'] .
            		':'     . $db[$name]['password'] .
            		'@'     . $db[$name]['hostname'] .
            		'/'     . $db[$name]['database'];
            }
        } 
        
        // Initialize ActiveRecord
        ActiveRecord\Config::initialize(function($cfg) use ($dsn, $active_group){
            $cfg->set_model_directory(APPPATH.'/models');
            $cfg->set_connections($dsn);
            $cfg->set_default_connection($active_group);
        });
        
    }
}

/* End of file Activerecord.php */
/* Location: ./application/libraries/Activerecord.php */

3- Configure your config/database.php file to match with your database settings.

And that’s it!! You are done… And can use this easily in your application. All you now need to do is , load the library whenever you want to use it. And to get rid of this you can simple put a line in your config/autoload.php

1
$autoload['libraries'] = array('activerecord');
$autoload['libraries'] = array('activerecord');

Now lets configure codeigniter with twig engine.

For this first get Twig. After extracting you can place this too in your application/libraries folder so that your directory structure becomes

1
2
3
 application/
..libraries/
..Twig
 application/
..libraries/
..Twig

Afterward, you need to create a file named Twig.php in libraries directory and place following code into that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
CI =& get_instance();
        $this->CI->config->load('twig');
 
        ini_set('include_path',
        ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');
        require_once (string) "Autoloader" . EXT;
 
        log_message('debug', "Twig Autoloader Loaded");
 
        Twig_Autoloader::register();
 
        $this->_template_dir = $this->CI->config->item('template_dir');
        $this->_cache_dir = $this->CI->config->item('cache_dir');
 
        $loader = new Twig_Loader_Filesystem($this->_template_dir);
 
        $this->_twig = new Twig_Environment($loader, array(
                'cache' => $this->_cache_dir,
                'debug' => $debug,
        ));
                $this->_config['title_separator'] = ' | ';
            foreach(get_defined_functions() as $functions) {
                    foreach($functions as $function) {
                        $this->_twig->addFunction($function, new Twig_Function_Function($function));
                    }
            }
    }
 
    public function add_function($name) 
    {
        $this->_twig->addFunction($name, new Twig_Function_Function($name));
    }
        
        public function add_functions($names) 
    {
            foreach ($names as $name)
                $this->_twig->addFunction($name, new Twig_Function_Function($name));
    }
 
    public function render($template, $data = array()) 
    {
        $template = $this->_twig->loadTemplate($template);
        return $template->render($data);
    }
 
    public function display($template, $data = array()) 
    {
        $template = $this->_twig->loadTemplate($template.'.html.twig');
        /* elapsed_time and memory_usage */
        $data['elapsed_time'] = $this->CI->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
        $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2) . 'MB';
        $data['memory_usage'] = $memory;
        $template->display($data);
    }
        public function title()
    {
        if(func_num_args() > 0)
        {
            $args = func_get_args();
 
            // If at least one parameter is passed in to this method, 
            // call append() to either set the title or append additional
            // string data to it.
            call_user_func_array(array($this, 'append'), $args);
        }
 
        return $this;
    }
        public function append()
    {
        $args = func_get_args();
        $title = implode($this->_config['title_separator'], $args);
 
        if(empty($this->_globals['title']))
        {
            $this->set('title', $title, TRUE);
        }
        else
        {
            $this->set('title', $this->_globals['title'] . $this->_config['title_separator'] . $title, TRUE);
        }
 
        return $this;
    }
        public function set($key, $value, $global = FALSE)
    {
        if(is_array($key))
        {
            foreach($key as $k => $v) $this->set($k, $v, $global);
        }
        else
        {
            if($global)
            {
                $this->_twig->addGlobal($key, $value);
                $this->_globals[$key] = $value;
            }
            else
            {
                $this->_data[$key] = $value;
            }   
        }
 
        return $this;
    }
}
CI =& get_instance();
		$this->CI->config->load('twig');

		ini_set('include_path',
		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');
		require_once (string) "Autoloader" . EXT;

		log_message('debug', "Twig Autoloader Loaded");

		Twig_Autoloader::register();

		$this->_template_dir = $this->CI->config->item('template_dir');
		$this->_cache_dir = $this->CI->config->item('cache_dir');

		$loader = new Twig_Loader_Filesystem($this->_template_dir);

		$this->_twig = new Twig_Environment($loader, array(
                'cache' => $this->_cache_dir,
                'debug' => $debug,
		));
                $this->_config['title_separator'] = ' | ';
	        foreach(get_defined_functions() as $functions) {
            		foreach($functions as $function) {
                		$this->_twig->addFunction($function, new Twig_Function_Function($function));
            		}
        	}
	}

	public function add_function($name) 
	{
		$this->_twig->addFunction($name, new Twig_Function_Function($name));
	}
        
        public function add_functions($names) 
	{
            foreach ($names as $name)
                $this->_twig->addFunction($name, new Twig_Function_Function($name));
	}

	public function render($template, $data = array()) 
	{
		$template = $this->_twig->loadTemplate($template);
		return $template->render($data);
	}

	public function display($template, $data = array()) 
	{
		$template = $this->_twig->loadTemplate($template.'.html.twig');
		/* elapsed_time and memory_usage */
		$data['elapsed_time'] = $this->CI->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
		$memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2) . 'MB';
		$data['memory_usage'] = $memory;
		$template->display($data);
	}
        public function title()
	{
		if(func_num_args() > 0)
		{
			$args = func_get_args();

			// If at least one parameter is passed in to this method, 
			// call append() to either set the title or append additional
			// string data to it.
			call_user_func_array(array($this, 'append'), $args);
		}

		return $this;
	}
        public function append()
	{
		$args = func_get_args();
		$title = implode($this->_config['title_separator'], $args);

		if(empty($this->_globals['title']))
		{
			$this->set('title', $title, TRUE);
		}
		else
		{
			$this->set('title', $this->_globals['title'] . $this->_config['title_separator'] . $title, TRUE);
		}

		return $this;
	}
        public function set($key, $value, $global = FALSE)
	{
		if(is_array($key))
		{
			foreach($key as $k => $v) $this->set($k, $v, $global);
		}
		else
		{
			if($global)
			{
				$this->_twig->addGlobal($key, $value);
				$this->_globals[$key] = $value;
			}
			else
			{
			 	$this->_data[$key] = $value;
			}	
		}

		return $this;
	}
}

I would like to take you through the functions defined in this file first. Well, first two functions are to add function to twig which will help you call php/codeigniter functions in your template files.

Function title is to add title to the page and function append is to append title to the title you have defined earlier. For example we can create a base title of the website something like “Google” and then append strings to it to appear something like “Google | About” and in these cases append function is very useful.

Set function is used to set a variable which can be accessed in template files and if you set “global=TRUE”, you can access it in your all template files. These all functions may look trivial but actually these are very useful to separate your logic(Controllers) from view completely as view files are only responsible to display data and it’s controller who should handle all the logic behind those data.

Now finally you need to create a file twig.php in your config directory with following contents:

1
2
3
4
5
6
7
<?php 
if (!defined(&#039;BASEPATH&#039;)) exit(&#039;No direct script access allowed&#039;);
// Below line is to define the location of all your view files.
// For me i wanted to put them in views directory.
$config[&#039;template_dir&#039;] = APPPATH.&#039;views&#039;;
// This is important to locate your cache folder. Although it&#039;s not that much important but as a good practice you should create application/cache/twig directory.
$config[&#039;cache_dir&#039;] = APPPATH.&#039;cache/twig&#039;;
<?php 
if (!defined(&#039;BASEPATH&#039;)) exit(&#039;No direct script access allowed&#039;);
// Below line is to define the location of all your view files.
// For me i wanted to put them in views directory.
$config[&#039;template_dir&#039;] = APPPATH.&#039;views&#039;;
// This is important to locate your cache folder. Although it&#039;s not that much important but as a good practice you should create application/cache/twig directory.
$config[&#039;cache_dir&#039;] = APPPATH.&#039;cache/twig&#039;;

And that’s it 🙂 You are done with it.

Now you have to create some view files. You can do it at your own also but in my case i created a folder called _layouts inside views(directory you had configured earlier to handle template files) directory and another directory to place my pages. So my directory structure becomes

1
2
3
views/
.._layouts/
..pages/
views/
.._layouts/
..pages/

So first i created a file application.html.twig in my _layouts/ folder like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    
        
        <!--[if lt IE 9]>-->
        
        
        <title>{% block title %}{% endblock %}</title>
    
    
 
        {% block content %}
 
        {% endblock %}
 
    
    
        
        <!--[if lt IE 9]>-->
        
        
        <title>{% block title %}{% endblock %}</title>
    
    

        {% block content %}

        {% endblock %}

    

You see these {% block %} thing? The first one is used to display the title you had set in your controller using that “title” and “append” function we discussed earlier. And the second one to display the page content which will come later.

Now create another file index.html.twig in pages directory with the following contents:

1
2
3
4
5
6
7
{% extends "_layouts/application.html.twig" %}
{% block title %}{{title}}{% endblock %}
{% block content %}
 
    Default template data.
 
{% endblock %}
{% extends "_layouts/application.html.twig" %}
{% block title %}{{title}}{% endblock %}
{% block content %}

    Default template data.

{% endblock %}

So now your template files are ready. You can extend this application.html.twig file from anywhere in your views directory. Now you need to call these files from your controller. It’s simple as following:

1
2
3
4
5
twig->title('Dashboard'); 
        //Following line will load your index.html.twig from views/pages
        $this->twig->display('pages/index');
    }
}
twig->title('Dashboard'); 
        //Following line will load your index.html.twig from views/pages
        $this->twig->display('pages/index');
    }
}

Now one last line needs to be added in your autoload.php and that is:

1
$autoload['libraries'] = array('activerecord','twig');
$autoload['libraries'] = array('activerecord','twig');

And that’s it.. I hope you enjoyed this. Also if you are looking for Codeigniter Web Development services connect with us at Dignitech Media Works

Please feel free to comment or ask me any query.

Content Source:http://www.raakeshkumar.in/

Resizing Images Dynamically in Codeigniter

We are posting very interesting thing which we believe could be a great help for people who wanna develop scalable applications with lots of images.

We have often seen that when people upload images on websites, they tend to create thumbnails as to make those images appear better on websites. Even we used to do this but recently we analyzed that this method obviously solves our in-hand problem but let say if we want to change the design of our website in future and want different sized image. One way to solve this problem is to keep your original image and run scripts to resize all your images to desired size but we thought to solve this problem with a different approach which is to not resize the images at all and keep it as is.

Now the question is, how do we fit our images in my website?

To solve this problem we created a Codeigniter Class(However it can be used for other frameworks as well with some changes) which would resize our images on the fly. Lets see how:–

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
 
/**
 * This is a custom image manupulation library developed by raakesh.
 * @license GNU GPL
 * @author raakesh
 * Released under public license hence author takes no warranty of this code out of this project scope. However, modification of this code is allowed under GNU GPL license.
 */
class Image {
 
    // Declare all public variables
    var $image;
    var $image_type;
    var $image_name;
 
    // Function to render final image to the browser
    public function display() {        
        $this->load($_GET['image']);
        $this->image_name = $_GET['image'];
        if($this->image_type == IMAGETYPE_JPEG)
            $this->check_orientation ($_GET['image']);
        if(isset($_GET['w']) and !isset($_GET['h']))
            $this->resizeToWidth ($_GET['w']);
        if(!isset($_GET['w']) and isset($_GET['h']))
            $this->resizeToHeight ($_GET['h']);
        if(isset($_GET['w']) and isset($_GET['h']))
            $this->crop($_GET['w'], $_GET['h']);            
        $this->output($this->image_type);
    }
 
    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if ($this->image_type == IMAGETYPE_JPEG) {
            $this->image = imagecreatefromjpeg($filename);
        } elseif ($this->image_type == IMAGETYPE_GIF) {
            $this->image = imagecreatefromgif($filename);
        } elseif ($this->image_type == IMAGETYPE_PNG) {
            $this->image = imagecreatefrompng($filename);
        }
    }
 
    function output($image_type = IMAGETYPE_JPEG) {
        header('Cache-Control: max-age=86400, public');
        if ($image_type == IMAGETYPE_JPEG) {
            header('Content-Type: image/jpeg');
            imagejpeg($this->image, NULL, 60);
        } elseif ($image_type == IMAGETYPE_GIF) {
            header('Content-Type: image/gif');
            imagegif($this->image);
        } elseif ($image_type == IMAGETYPE_PNG) {
            header('Content-Type: image/png');
            imagepng($this->image, NULL, 6);
        }
    }
 
    function getWidth() {
        return imagesx($this->image);
    }
 
    function getHeight() {
        return imagesy($this->image);
    }
 
    function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width, $height);
    }
 
    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width, $height);
    }
    function resize($width, $height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }
 
 
    function crop($thumb_width, $thumb_height) {
        $width = $this->getWidth();
        $height = $this->getHeight();
 
        $original_aspect = $width / $height;
        $thumb_aspect = $thumb_width / $thumb_height;
 
        if ($original_aspect >= $thumb_aspect) {
            // If image is wider than thumbnail (in aspect ratio sense)
            $new_height = $thumb_height;
            $new_width = $width / ($height / $thumb_height);
        } else {
            // If the thumbnail is wider than the image
            $new_width = $thumb_width;
            $new_height = $height / ($width / $thumb_width);
        }
 
        $new_image = imagecreatetruecolor($thumb_width, $thumb_height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $thumb_width, $thumb_height, $transparent);
// Resize and crop
 
        imagecopyresampled($new_image, $this->image, 0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                0, 0, $new_width, $new_height, $width, $height);
        $this->image = $new_image;
    }
    function check_orientation($source) {
        $exif = exif_read_data($source);        
        $ort = isset($exif['Orientation']) ? $exif['Orientation'] : '';
        switch ($ort) {
 
            case 2: // horizontal flip
 
                $this->ImageFlip();
 
                break;
 
            case 3: // 180 rotate left
 
                $this->image = imagerotate($this->image, 180, -1);
 
                break;
 
            case 4: // vertical flip
 
                $this->ImageFlip();
 
                break;
 
            case 5: // vertical flip + 90 rotate right
 
                $this->ImageFlip();
 
                $this->image = imagerotate($this->image, -90, -1);
 
                break;
 
            case 6: // 90 rotate right
 
                $this->image = imagerotate($this->image, -90, -1);
 
                break;
 
            case 7: // horizontal flip + 90 rotate right
 
                $this->ImageFlip();
 
                $this->image = imagerotate($this->image, -90, -1);
 
                break;
 
            case 8: // 90 rotate left
 
                $this->image = imagerotate($this->image, 90, -1);
 
                break;
            default :
                $this->image = $this->image;
                break;
        }
    }
 
    public function ImageFlip($x = 0, $y = 0, $width = null, $height = null) {
 
        if ($width < 1)
            $width = $this->getWidth();
        if ($height < 1)
            $height = $this->getHeight();
 
        // Truecolor provides better results, if possible.
        if (function_exists('imageistruecolor') && imageistruecolor($this->image)) {
 
            $tmp = imagecreatetruecolor(1, $height);
        } else {
 
            $tmp = imagecreate(1, $height);
        }
 
        $x2 = $x + $width - 1;
 
        for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--) {
 
            // Backup right stripe.
            imagecopy($tmp, $this->image, 0, 0, $x2 - $i, $y, 1, $height);
 
            // Copy left stripe to the right.
            imagecopy($this->image, $this->image, $x2 - $i, $y, $x + $i, $y, 1, $height);
 
            // Copy backuped right stripe to the left.
            imagecopy($this->image, $tmp, $x + $i, $y, 0, 0, 1, $height);
        }
 
        imagedestroy($tmp);
 
        return true;
    }
 
}
 
?>
<?php

/**
 * This is a custom image manupulation library developed by raakesh.
 * @license GNU GPL
 * @author raakesh
 * Released under public license hence author takes no warranty of this code out of this project scope. However, modification of this code is allowed under GNU GPL license.
 */
class Image {

    // Declare all public variables
    var $image;
    var $image_type;
    var $image_name;

    // Function to render final image to the browser
    public function display() {        
        $this->load($_GET['image']);
        $this->image_name = $_GET['image'];
        if($this->image_type == IMAGETYPE_JPEG)
            $this->check_orientation ($_GET['image']);
        if(isset($_GET['w']) and !isset($_GET['h']))
            $this->resizeToWidth ($_GET['w']);
        if(!isset($_GET['w']) and isset($_GET['h']))
            $this->resizeToHeight ($_GET['h']);
        if(isset($_GET['w']) and isset($_GET['h']))
            $this->crop($_GET['w'], $_GET['h']);            
        $this->output($this->image_type);
    }

    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        if ($this->image_type == IMAGETYPE_JPEG) {
            $this->image = imagecreatefromjpeg($filename);
        } elseif ($this->image_type == IMAGETYPE_GIF) {
            $this->image = imagecreatefromgif($filename);
        } elseif ($this->image_type == IMAGETYPE_PNG) {
            $this->image = imagecreatefrompng($filename);
        }
    }

    function output($image_type = IMAGETYPE_JPEG) {
        header('Cache-Control: max-age=86400, public');
        if ($image_type == IMAGETYPE_JPEG) {
            header('Content-Type: image/jpeg');
            imagejpeg($this->image, NULL, 60);
        } elseif ($image_type == IMAGETYPE_GIF) {
            header('Content-Type: image/gif');
            imagegif($this->image);
        } elseif ($image_type == IMAGETYPE_PNG) {
            header('Content-Type: image/png');
            imagepng($this->image, NULL, 6);
        }
    }

    function getWidth() {
        return imagesx($this->image);
    }

    function getHeight() {
        return imagesy($this->image);
    }

    function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width, $height);
    }

    function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getheight() * $ratio;
        $this->resize($width, $height);
    }
    function resize($width, $height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }


    function crop($thumb_width, $thumb_height) {
        $width = $this->getWidth();
        $height = $this->getHeight();

        $original_aspect = $width / $height;
        $thumb_aspect = $thumb_width / $thumb_height;

        if ($original_aspect >= $thumb_aspect) {
            // If image is wider than thumbnail (in aspect ratio sense)
            $new_height = $thumb_height;
            $new_width = $width / ($height / $thumb_height);
        } else {
            // If the thumbnail is wider than the image
            $new_width = $thumb_width;
            $new_height = $height / ($width / $thumb_width);
        }

        $new_image = imagecreatetruecolor($thumb_width, $thumb_height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $thumb_width, $thumb_height, $transparent);
// Resize and crop

        imagecopyresampled($new_image, $this->image, 0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                0, 0, $new_width, $new_height, $width, $height);
        $this->image = $new_image;
    }
    function check_orientation($source) {
        $exif = exif_read_data($source);        
        $ort = isset($exif['Orientation']) ? $exif['Orientation'] : '';
        switch ($ort) {

            case 2: // horizontal flip

                $this->ImageFlip();

                break;

            case 3: // 180 rotate left

                $this->image = imagerotate($this->image, 180, -1);

                break;

            case 4: // vertical flip

                $this->ImageFlip();

                break;

            case 5: // vertical flip + 90 rotate right

                $this->ImageFlip();

                $this->image = imagerotate($this->image, -90, -1);

                break;

            case 6: // 90 rotate right

                $this->image = imagerotate($this->image, -90, -1);

                break;

            case 7: // horizontal flip + 90 rotate right

                $this->ImageFlip();

                $this->image = imagerotate($this->image, -90, -1);

                break;

            case 8: // 90 rotate left

                $this->image = imagerotate($this->image, 90, -1);

                break;
            default :
                $this->image = $this->image;
                break;
        }
    }

    public function ImageFlip($x = 0, $y = 0, $width = null, $height = null) {

        if ($width < 1)
            $width = $this->getWidth();
        if ($height < 1)
            $height = $this->getHeight();

        // Truecolor provides better results, if possible.
        if (function_exists('imageistruecolor') && imageistruecolor($this->image)) {

            $tmp = imagecreatetruecolor(1, $height);
        } else {

            $tmp = imagecreate(1, $height);
        }

        $x2 = $x + $width - 1;

        for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--) {

            // Backup right stripe.
            imagecopy($tmp, $this->image, 0, 0, $x2 - $i, $y, 1, $height);

            // Copy left stripe to the right.
            imagecopy($this->image, $this->image, $x2 - $i, $y, $x + $i, $y, 1, $height);

            // Copy backuped right stripe to the left.
            imagecopy($this->image, $tmp, $x + $i, $y, 0, 0, 1, $height);
        }

        imagedestroy($tmp);

        return true;
    }

}

?>

When i have to use this class, i can simply call it using

1
<?= base_url() ?>image/display?image=url-of-your-image&w=width&h=height
<?= base_url() ?>image/display?image=url-of-your-image&w=width&h=height

With this solution you don’t have to worry about creating different thumbnails for images as well as future design changes. Also read about Secure Image Uploading im PHP.

We hope this will solve your problems. Comments & suggestions are invited.

Content Source: http://www.raakeshkumar.in/

Secure Image Uploading in PHP and Theory Behind It

After seeing so many questions on how we can do secure uploading of images on the server, i am gonna post a theory of how to do this effectively.

Very first method which is basic uploading:

We just browse an image from our local machine and upload them as following. This method is called a naive method.

1
2
3
4
5
6
7
8
9
10
11
if (!empty($_FILES['yourFileName']['name']))
 
{
// To upload the Image.
$name = $_FILES['yourFileName']['name'];
$type = $_FILES['yourFileName']['type'];
$size = $_FILES['yourFileName']['size'];
$source = $_FILES['yourFileName']['tmp_name'];
$destination = "images/".$name;
move_uploaded_file($source, $destination);
}
if (!empty($_FILES['yourFileName']['name']))

{
// To upload the Image.
$name = $_FILES['yourFileName']['name'];
$type = $_FILES['yourFileName']['type'];
$size = $_FILES['yourFileName']['size'];
$source = $_FILES['yourFileName']['tmp_name'];
$destination = "images/".$name;
move_uploaded_file($source, $destination);
}

This uploading is done through a normal html form tag

1
<form action="" enctype=""multipart/form-data" method="post"><input type="file" name="yourFileName" /> <input type="submit" value="Upload" /></form>
<form action="" enctype=""multipart/form-data" method="post"><input type="file" name="yourFileName" /> <input type="submit" value="Upload" /></form>

Unfortunately this has several flaws- 1 – It can easily be guessed that where are to putting your files and so anybody can upload any PHP script or any executable file and get your server down. 2 – For an example somebody can upload a file which enables shell commands on your machine as following and can do anything with your server. So this way is never suggested. A simple solution at the first site seems to check for the file type being uploaded. so putting a simple script

1
2
3
4
if($_FILES['yourFileName']['type'] != 'image/jpg')
{
//Error
}
if($_FILES['yourFileName']['type'] != 'image/jpg')
{
//Error
}

Can make your script secure a bit but unfortunately it also has some flaws. This php method check content type of the image you are uploading and can be broken by a simple perl script by making header content-type to image/jpg.

Now moving one step ahead let’s check the file type, rather checking content type. There is a function in php getimagesize() which returns a list with image attribute as;

1
list($width, $height, $type, $attr) = getimagesize('yourUploadedImage');
list($width, $height, $type, $attr) = getimagesize('yourUploadedImage');

by this way we can check for the file type and test whether it’s an image. Now one can ask, are we secure? The unfortunate answer is NO. Even after verifying file type, we are not done? YES still there is a flaw in this…

A hacker can easily use steganography and embed a php code into the image and can break your system(Here my motive is not to teach hacking or steganography. I just to help others protect their system). Then? After this we have a one more thing to do with the code and that is putting your image folder out of your server directory (on Linux /var/www directory) or make your uploaded image folder not executable so that even if the hacker uploads image he shouldn’t be able to run that.

So now are you secure? Ummm… NO but after this stage you are highly secure from attacks. In this post i have tried to cover all the theory behind image uploading with little coding in php. Syntax in other languages are not very different but if you will ask i can provide you links/codes in other languages.

Content Source: http://www.raakeshkumar.in/


Fatal error: Uncaught Error: Call to undefined function twentyseventeen_get_svg() in /home/dignitech/dignitech.com/public_html/wp-content/themes/dignitech/archive.php:45 Stack trace: #0 /home/dignitech/dignitech.com/public_html/wp-includes/template-loader.php(74): include() #1 /home/dignitech/dignitech.com/public_html/wp-blog-header.php(19): require_once('/home/dignitech...') #2 /home/dignitech/dignitech.com/public_html/index.php(17): require('/home/dignitech...') #3 {main} thrown in /home/dignitech/dignitech.com/public_html/wp-content/themes/dignitech/archive.php on line 45