What is #Magento?

Magento is an e-commerce platform built atop open source technology, enabling online sellers to have ultimate control over the look, functionality, and content of their online shops. With Magento, there is the opportunity to deploy powerful marketing strategies, enjoy advanced catalog management, and manage search engine optimisation to maximise your brand’s exposure to your target market.

Today, Magento is one of the best ecommerce platforms available that outstrips other platforms such as WordPress and Shopify when it comes to the control you have over it.

This considerable power comes at a price, though. Magento needs serious hosting setup to shine fully and requires some degree of technical understanding. Granted, even complete novices can design pretty sites with its interface but having knowledge about basic hosting concepts and some scripting cannot hurt.

In addition, there is a large and helpful community of developers and other merchants behind Magento, who are always more than happy to help out newcomers. It is a robust system at its most basic level, and once it is integrated with other systems, its true power is realised.

Magento is super fast too. Any experienced developer will be able to tell you that overall speed is of high importance when it comes to e-commerce. Your customer is not going to wait around for five to 10 minutes for a page to load if she wants to make a purchase. If your site is slow, she will go elsewhere. With Magento, this never has to be an issue as the whole platform is highly optimised and designed to run at lightning fast speed.

If you want to learn more about Magento, check out our infographic below:

WordPress User Registration Spam

Recently I had enabled the option to register on TechUtils.in as a subscriber to the login page. It’s an easy option just go to the Admin Section> Settings> General.

Check the Option “Anyone can register” and click on save.

This was the easy part thinking that I could get users and later if they wish to contribute then, I would just change their role. Thus easy public contribution to my Blog.

And within hours I had about 300+ users registering on my blog as subscribers.

The peculiar part was that every time someone registered, they would change their password. As an admin i would receive the mail instantly that the user has lost their password and have changed it.

At first I was amused, but then later curious that why would each user change their password as soon as they register.

On digging I found various articles. One that sticks out was this one

It seems that many people are facing the same issue and sites like

komatoz.net
gawab.com
yandex.ru
mail.ru
inbox.ru

Users from these sites may be budding hackers or just fun spammers…but for blog owners they are just useless irritations.

How to lose them?

There are a few ways for that:

  • Use of the .htaccess File

    .htAccess file has an in-built design for such issues.
    add the following entries to your .htAccess File

    #BEGIN_ADDS
    Options -Indexes

    order allow,deny

    deny from 24.1.39.117
    deny from 38.99.101.151
    deny from 58.65.237.113
    deny from 58.65.239.146
    deny from 61.152.95.162
    deny from 64.233.179.101
    deny from 64.86.69.6
    deny from 64.94.4.196

    deny from 66.235.180.189
    deny from 72.249.100.188
    deny from 75.126.3.177
    deny from 78.110.160.130
    deny from 85.225.117.179
    deny from 87.118.112.50
    deny from 88.255.69.10
    deny from 89.149.227.193
    deny from 89.149.241.229
    deny from 89.207.216.211

    deny from 160.114.38.82
    deny from 190.2.0.2
    deny from 192.116.79.226

    deny from 195.2.114.31
    deny from 195.2.114.32
    deny from 195.245.119.76
    deny from 195.225.178.15

    deny from 203.162.2.137
    deny from 205.158.160.76
    deny from 208.187.80.135

    deny from 210.14.128.112
    deny from 210.14.128.172
    deny from 210.22.158.132
    deny from 212.175.13.169

    deny from 216.240.152.9
    deny from 217.20.115.118
    deny from 218.61.16.8

    allow from all

    #END_ADDS

  • Use of Akismet

    Most folk use anyway as it’s part of the default WordPress install. The activation is fairly simple and even though the say select a plan, it can still be used as free.

    • Just head over to the activation plan selection page.
    • Select the basic plan
    • drag the slider to the leftmost, till you wipe the smile off that smiley.
    • click get API Key.
    • head over to your Admin Section.
    • activate Akismet
    • add new Activation key from your mail.
    • Enjoy. In case there comes an Oops moment where people still trickle through and you don’t even want them…upgrade your plan…

Source

How to Create a Custom Page in WordPress

A custom page is helpful if you want to have a page that looks completely different than rest of your blog but still runs on the WordPress CMS. You can also use it as a homepage or a landing page.

To customize the design and edit styling for the page, HTML and CSS knowledge would be helpful.

You will begin creating a custom page by opening a blank file in your text editor and paste the following code at the very top:

<?php /* Template Name: TechUtilsPageTemplate */ ?>

Once you have added the code, save the page as: blog[template_name].php so it will be blogtechutils.php for this example. You can name it any other structure you like as long as it is a php file.

The above code is simply giving your template a name that you will later see that WordPress recognize, so we are calling our template TechUtilsPageTemplate but you can call it whatever you like for example, archive, contact, landingpage etc.

Once you have completed editing this file save it and upload it in your theme directory (/wp-content/themes/yourthemedirectory/) where files like single.phpand index.php are located.

Next you will need to login to your WordPress admin panel and Add a New Page. Since you have already written down all the text and settings in the php file, simply name the page and leave the content area blank. Look on the right hand side, you will see a box called Attributes below the publish button. Choose the template using the drag down button.

Source

Create Virtual Hosts with Apache

Apache is very flexible, and it’s easy to configure Apache to handle several domains even when your Web server only has one IP address to share between them. You can use this to host multiple sites, or just to provide a sandbox for development rather than making changes on your live site. This weekend, we’ll learn how to create virtual hosts with Apache.

Setting up virtual hosts might seem like a big challenge, but it’s not. In fact, you can set up a virtual host with just a few edits to Apache’s configuration and by setting up additional directories for the documents. For this how to, I want to use an Apache installation on a Ubuntu server. Please be aware, the instructions for this may require modification if being done on a non-Debian distribution because of the way that Apache is packaged. However, the Apache directives should be standard across distributions and should work even if Apache isn’t running on Linux.

Creating the Directory Structure

Before the configurations can be tackled, the directory structure for the virtual site must be created. We are going to be working with Apache as installed on a Ubuntu server, so the Apache document root will be/var/www. The directory structure for the new Web site can be created anywhere. Some create those directories in their home (~/) directory, some create them in /usr/local/apache, and other, various locations. For the sake of simplicity, We are going to illustrate setting the virtual host in the document root of Apache (in Ubuntu that would be /var/www). By doing this, it will not be necessary to change ownership of the newly created directory or the parent directory housing the virtual host (since Apache must have access to the directories and files.)

We are going to set up the virtual host demosite.com. So to create the directories for the virtual host, the following commands must be run:

  • sudo mkdir /var/www/demosite.com
  • sudo chmod -R 755 /var/www/demosite.com

Now that the home directory for the virtual host is done, it’s time to start configuring Apache so it is aware of the new site. After configuring Apache, the site can then be built within /var/www/demosite.com.

Apache Configuration

The first step in the Apache configuration is to make sure Apache knows virtual hosts are enabled. In the Ubuntu set up look for a line (near the bottom) of /etc/apache/apache2.conf that looks like:

Include sites-enabled/

Make sure that line is not commented out (does not begin with a ‘#‘ character). That sites-enabled include points to /etc/apache/sites-enabled. A look in that directory will reveal a file called 000-default. That file should contain all of the directory containers needed for virtual sites on the server. To create a new virtual host (to map the example demosite.com), create a new file within sites-available called /etc/apache/sites-available/demosite.com. The contents of that file will look something similar to this (depending upon the needs and application of the virtual host):


<VirtualHost test.domain.com>
   ServerAdmin webmaster@localhost
   #We want to be able to access the web site using www.test.domain.com or test.domain.com
   ServerAlias www.test.domain.com
   DocumentRoot /var/www/demosite.com
   #log file for this server
   CustomLog /var/log/apache2/www.test.domain.com-access.log combined
</VirtualHost>

The above code assumes that domain.com is the actual domain to be used (insert proper domain where necessary). It’s almost ready to fire up, but we have two simple steps left before restarting Apache. The first step is to create a link in /etc/apache/sites-enabled to the file we just created. This is done with the following steps:

  1. Change to the /etc/apache/sites-enabled directory with the command cd /etc/apache/sites-enabled .
  2. Create the link with the command sudo ln -s /etc/apache/sites-available demosite.com .

It is also possible to create the links automatically with the command sudo a2ensite demosite.com and then, should the virtual site need to be disabled, remove the link with the command sudo a2dissite demosite.com.

The last step is to make sure the server knows that our new virtual site is to be found on the server and not out on the Internet. For this, do the following:

  • Open up the /etc/hosts file in a text editor (with administrative rights).
  • Add a line like 127.0.0.1 localhost.localdomain localhost test.domain.com www.demosite.com .
  • Save and close that file.

Now it’s time to restart Apache with the command sudo /etc/init.d/apache2 restart and test virtual host by pointing a browser to the address.

Non-Debian Servers

If the server hosting the virtual sites is a non-Debian distribution, the steps are different for hosting virtual sites. Here’s how it works:

  1. Create the directory container for the virtual site in /etc/httpd/conf/httpd.conf. This container will look similar to that used for the Debian-based server.
  2. Make sure the Apache configuration file is aware of virtual hosts by making sure the line Include conf.d/*.conf is not commented out.
  3. Create the new virtual hosts file (we’ll call it vhosts.conf) in /etc/httpd/conf.d/ .
  4. Add the virtual site to the /etc/hosts file.
  5. Restart Apache with the command /etc/rc.d/init.d/httpd restart.

The directory container, for the non-Debian host, will look similar to the very basic container below:


<VirtualHost *:80>
   ServerName demosite.com
   DocumentRoot /var/www/html/demosite.com
</VirtualHost>

The virtual hosts file mentioned above, will need to look like this:


<VirtualHost 127.0.0.1> 
   DocumentRoot /var/http/www/demosite.com
   ServerName www.demosite.com
</VirtualHost>  

<VirtualHost 127.0.0.1>
   DocumentRoot /var/http/www/demosite.com
   ServerName test.demosite.com
</VirtualHost>

Building Time

Now that the virtual host is up and running, it is now possible to build the site within the/var/www/demosite.com directory.

You can do this for as many virtual hosts as you need (assuming the server can take the added load).

Source

Simple way to generate a random password in PHP

When creating web apps, there’s often a need to generate a random password for your users. There are a number of ways to do this, but in needing to do it recently I came up with this very simple function that will generate a password (or other random string) of whatever length you wish. It’s particularly useful when generating passwords for users that they will then change in the future. It uses PHP’s handy str_shuffle() function:

<?php
    function random_password( $length = 8 ) {
         $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
         $index=rand($length,$length*$length);
         $password='';
         for($i=0;$i<$index;$i++){
            $password = substr( str_shuffle( $chars.$password ), 0, $length );
         }
         return $password;
    }

?>
<?php $password = random_password(8); ?>

NOTE: This method is better than the on posted in the Source. It randomizes the password generation process enough to be safe from brute force or predictability.

JQuery not working in wordpress

Since WordPress version 2.x, jQuery is a build-in JavaScript library, explicitly include the jQuery library into WordPress is not necessary.

$(document).ready(function(){
  alert('test');
});

the above code will be giving an error in the console of your code:

$ is undefined

In WordPress, the $() syntax is always used by other scripting library, and causing the conflict issue and fail to call the jQuery function. You should use jQuery() instead…

jQuery(document).ready(function(){
  alert('test');
});

Alternatively, you can use noConflict()

$j=jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function(){
  alert('test');
});

P.S jQuery.noConflict();http://wordpress.org/support/topic/141394

Never use jQuery handy function $() in WordPress plugin. You have to use jQuery() or jQuery.noConflict() to work between jQuery and WordPress.

Source

OpenCart 1.5.X developer quick start guide for beginners

This guide is written for developers already familiar with PHP, OOP and the MVC architecture

In the following, you’ll see examples for the catalog side of the cart. The admin side is identical in function with the exception of the views which is noted in the relevant section


Understanding Libraries

All of the library functionality is accessible through Controller, Model and Views using $this->library_name. All of these can be found in the /system/library/ folder. For example, to access the current shopping cart’s products, you’ll need to use the Cart class, which is in /system/library/cart.php and can be accessed using $this->cart->getProducts()

Commonly used items

  • customer.php – Customer related functions
  • user.php – Admin user related functions
  • cart.php – Cart related functions
  • config.php – All settings are loaded from this
  • url.php – URL generation functions

Understanding the route parameter

OpenCart’s framework relies on the route=aaa/bbb/ccc in the query string parameter to know what to load, and is the underpinning feature to finding the files you need to edit for each page. Most route’s actually only use the aaa/bbb which should be seen as two parts, however some contain three parts aaa/bbb/ccc The first part aaa generally related to the folder within a generic folder such as the controller or template folders. The second part usually relates to the file name, without the relevant .php or .tpl extension. The third part is explained in the understanding controllers below


Understanding languages

Languages are stored in /catalog/language/ folder in the your-language subfolder. Within this, general text values used across various pages are stored in the your-language.php file inside the folder, so for the English language on the catalog side, you’ll find the values in catalog/language/english/english.php. For specific page text, you’ll need the route for the page (This is generally the case, but not always as you can specify any language file you like). For example, the search page has the route product/search, and therefore the language specific text for that page can be found in catalog/language/english/product/search.php (Notice the file’s name and subfolder match the route followed by .php.

To load the language in a controller, you use

$this->language->load('product/search');

Then you can use the language library function get to retrieve specific language texts, such as

$some_variable = $this->language->get('heading_title');

The language variables are assigned in the language file using a special variable $_ which is an array of keys and text values. In your /catalog/language/english/product/search.php you should find something similar to

$_['heading_title']     = 'Search';

The values in the global language file english/english.php are automatically loaded and available to use without the $this->language->load method


Understanding controllers

Controllers are loaded based on the route and are fairly straight forward to understand. Controllers are located in the /catalog/controller/ folder. Continuing from the last example, the Controller for the Search page is in /product/search.php within this folder. Notice again that the route followed by .php is used.

Opening the controller file, you’ll see a Pascal Case classname extending the Controller class, called ControllerProductSearch. This again is specific to the route, with Controller followed by the subfolder name and file name without the extension capitalised. The capitalisation is not actually required, but it’s recommended for easy readability. It’s worth noting that classnames don’t take any values from the subfolder and file name other than letters and numbers. Underscores are removed.

Within the class are the methods. Methods in the class declared public are accessible to be run via the route – private are not. By default, with a standard two part route (aaa/bbb above), a default index() method is called. If the third part of a route (ccc above) is used, this method will be run instead. For example, account/return/insert will load the /catalog/controller/account/return.php file and class, and try to call the insert method


Understanding Models

Model’s in OpenCart are found in the /catalog/model/ folder and are grouped based on function not the route, and therefore you will need to load them in your controller via

$this->load->model('xxx/yyy');

This will load the file in the subfolder xxx called yyy.php. It is then available to use via the object

$this->model_xxx_yyy

and as with controllers you can only call it’s public methods. For instance, to resize an image, you would use the tool/image model and call it’s resize method as follows

$this->load->model('tool/image');
$this->model_tool_image->resize('image.png', 300, 200);

Understanding variable assignment in views from the controller

In order to pass values to the view from the controller, you simply need to assign your data to the $this->data variable, which is essentially an array of key => value pairs. As an example

$this->data['example_var'] = 123;

Accessing this in a view is a little should be easy to understand if you’re familiar with the extract()method which converts each key into a variable. So the example_var key becomes $example_varand can be accessed as such in the view


Understanding themes

Themes are available to the catalog side only, and are basically a folder of templates, stylesheets and theme images. Theme folders are placed in the /catalog/view/theme/ folder followed by the theme name. The folder name isn’t of importance with exception to the default folder

The admin side uses /admin/view/template/ (skipping the /theme/theme-name/ from the path as it doesn’t allow differing themes)

Template files reside in a template folder within the theme folder. Should any template not be available for the currently selected theme, the default folder’s template is used instead as a fallback. This means themes can be created with very few files and still function fully. It also reduces code duplication and issues as upgrades are made


Understanding views (templates)

As with language and models, the view file’s are generally related to the route, though don’t have to be at all. Templates on the catalog side are usually found in /catalog/view/theme/your-theme/template/ unless it doesn’t exist, in which case the default theme’s templates will be used. For our search page example above, the file is product/search.tpl. For routes with three parts, it is generally in aaa/bbb_ccc.tpl though there’s no hard set rule. In the admin, most pages follow this, with the exception that pages listing items, like the product listing page are in catalog/product_list.tpl and the product editing form is in catalog/product_form.tpl. Again, these aren’t set, but a standard for the default cart

It’s worth point out that the template file is in fact just another php file, but with a .tpl extension and is actually run in the controller file, therefore all of the things you can code in a controller can be run in a template file (though not recommended unless absolutely necessary)


Understanding the database object

Queries are run using

$result = $this->db->query("SELECT * FROM `" . DB_PREFIX . "table`");

DB_PREFIX as the name suggests is a constant containing the database prefix if one exists

$result will return an object for SELECT queries, containing a few properties

$result->row contains the first row’s data if one or more are returned as an associative array

$result->rows contains an array of row results, ideal for looping over using foreach

$result->num_rows contains the number of results returned

There are also a few extra methods the $this->db object has

$this->db->escape() uses mysql_real_escape_string() on the value passed

$this->db->countAffected returns the number of rows affected by an UPDATE query and so on

$this->db->getLastId() returns the last auto increment id using mysql_insert_id()


Understanding reserved variables

OpenCart has predefined variables to use in place of the standard $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST AND $_SERVER

$_SESSION is edited using $this->session->data where data is an associative array mimicking the $_SESSION

All of the others can be accessed using $this->request and have been “cleaned” to comply with magic quotes enabled/disabled, so

$_GET becomes $this->request->get

$_POST becomes $this->request->post

$_COOKIE becomes $this->request->cookie

$_FILES becomes $this->request->files

$_REQUEST becomes $this->request->request

$_SERVER becomes $this->request->server


Summary

While the above isn’t a bulletproof guide for developers, hopefully it will serve as a good starting point for those getting started

Credit: Post

How to create a custom admin page in OpenCart?

OpenCart uses the MVC pattern.

Recommended reading: How to be an OpenCart Guru?

1) Create a new file in admin/controller/custom/helloworld.php

Your filename and controller name should be the same in desc order:

helloworld.php

<?

class ControllerCustomHelloWorld extends Controller{ 
    public function index(){
                // VARS
                $template="custom/hello.tpl"; // .tpl location and file
        $this->load->model('custom/hello');
        $this->template = ''.$template.'';
        $this->children = array(
            'common/header',
            'common/footer'
        );      
        $this->response->setOutput($this->render());
    }
}
?>

2) Create a new file in admin/view/template/custom/hello.tpl

Hello.tpl

<?php echo $header; ?>
<div id="content">
<h1>HelloWorld</h1>
<?php
echo 'I can also run PHP too!'; 
?>
</div> 
<?php echo $footer; ?>

3) Create a new file in admin/model/custom/hello.php

<?php
class ModelCustomHello extends Model {
    public function HellWorld() {
        $sql = "SELECT x FROM `" . DB_PREFIX . "y`)"; 
        $implode = array();
        $query = $this->db->query($sql);
        return $query->row['total'];    
    }       
}
?>

4) You then need to enable the plugin to avoid permission denied errors:

Opencart > Admin > Users > User Groups > Admin > Edit

Select and Enable the Access Permission.

To visit your page go to

www.yoursite.com/opencart/admin/index.php?route=custom/helloworld

Credits: Post

Code maintenance for Open Source Projects: GIT Sub-modules and Composer

Problem Statement:

Lets say you have a working directory of GIT where all your project work is stored and checked in. Also you are using Open Source Solutions from 3-4 different repositories. You want the latest code to be available whenever it is uploaded. 1 way to do that is to download the zip/repository code each time to your project folder. Other sleek and effective ways are:

  • Git Sub modules:
    Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.Extract:

    Starting with Submodules

    We’ll walk through developing a simple project that has been split up into a main project and a few sub-projects.

    Let’s start by adding an existing Git repository as a submodule of the repository that we’re working on. To add a new submodule you use the git submodule add command with the URL of the project you would like to start tracking. In this example, we’ll add a library called “DbConnector”.

    $ git submodule add https://github.com/chaconinc/DbConnector
    Cloning into 'DbConnector'...
    remote: Counting objects: 11, done.
    remote: Compressing objects: 100% (10/10), done.
    remote: Total 11 (delta 0), reused 11 (delta 0)
    Unpacking objects: 100% (11/11), done.
    Checking connectivity... done.

    By default, submodules will add the subproject into a directory named the same as the repository, in this case “DbConnector”. You can add a different path at the end of the command if you want it to go elsewhere.

    If you run git status at this point, you’ll notice a few things.

    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
    	new file:   .gitmodules
    	new file:   DbConnector

    First you should notice the new .gitmodules file. This is a configuration file that stores the mapping between the project’s URL and the local subdirectory you’ve pulled it into:

    $ cat .gitmodules
    [submodule "DbConnector"]
    	path = DbConnector
    	url = https://github.com/chaconinc/DbConnector

    If you have multiple submodules, you’ll have multiple entries in this file. It’s important to note that this file is version-controlled with your other files, like your .gitignore file. It’s pushed and pulled with the rest of your project. This is how other people who clone this project know where to get the submodule projects from.

    Since the URL in the .gitmodules file is what other people will first try to clone/fetch from, make sure to use a URL that they can access if possible. For example, if you use a different URL to push to than others would to pull from, use the one that others have access to. You can overwrite this value locally with git config submodule.DbConnector.url PRIVATE_URL for your own use.

    The other listing in the git status output is the project folder entry. If you run git diff on that, you see something interesting:

    $ git diff --cached DbConnector
    diff --git a/DbConnector b/DbConnector
    new file mode 160000
    index 0000000..c3f01dc
    --- /dev/null
    +++ b/DbConnector
    @@ -0,0 +1 @@
    +Subproject commit c3f01dc8862123d317dd46284b05b6892c7b29bc

    Although DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

    If you want a little nicer diff output, you can pass the --submodule option to git diff.

    $ git diff --cached --submodule
    diff --git a/.gitmodules b/.gitmodules
    new file mode 100644
    index 0000000..71fc376
    --- /dev/null
    +++ b/.gitmodules
    @@ -0,0 +1,3 @@
    +[submodule "DbConnector"]
    +       path = DbConnector
    +       url = https://github.com/chaconinc/DbConnector
    Submodule DbConnector 0000000...c3f01dc (new submodule)

    When you commit, you see something like this:

    $ git commit -am 'added DbConnector module'
    [master fb9093c] added DbConnector module
     2 files changed, 4 insertions(+)
     create mode 100644 .gitmodules
     create mode 160000 DbConnector

    Notice the 160000 mode for the DbConnector entry. That is a special mode in Git that basically means you’re recording a commit as a directory entry rather than a subdirectory or a file.

    Cloning a Project with Submodules

    Here we’ll clone a project with a submodule in it. When you clone such a project, by default you get the directories that contain submodules, but none of the files within them yet:

    $ git clone https://github.com/chaconinc/MainProject
    Cloning into 'MainProject'...
    remote: Counting objects: 14, done.
    remote: Compressing objects: 100% (13/13), done.
    remote: Total 14 (delta 1), reused 13 (delta 0)
    Unpacking objects: 100% (14/14), done.
    Checking connectivity... done.
    $ cd MainProject
    $ ls -la
    total 16
    drwxr-xr-x   9 schacon  staff  306 Sep 17 15:21 .
    drwxr-xr-x   7 schacon  staff  238 Sep 17 15:21 ..
    drwxr-xr-x  13 schacon  staff  442 Sep 17 15:21 .git
    -rw-r--r--   1 schacon  staff   92 Sep 17 15:21 .gitmodules
    drwxr-xr-x   2 schacon  staff   68 Sep 17 15:21 DbConnector
    -rw-r--r--   1 schacon  staff  756 Sep 17 15:21 Makefile
    drwxr-xr-x   3 schacon  staff  102 Sep 17 15:21 includes
    drwxr-xr-x   4 schacon  staff  136 Sep 17 15:21 scripts
    drwxr-xr-x   4 schacon  staff  136 Sep 17 15:21 src
    $ cd DbConnector/
    $ ls
    $

    The DbConnector directory is there, but empty. You must run two commands: git submodule init to initialize your local configuration file, and git submodule update to fetch all the data from that project and check out the appropriate commit listed in your superproject:

    $ git submodule init
    Submodule 'DbConnector' (https://github.com/chaconinc/DbConnector) registered for path 'DbConnector'
    $ git submodule update
    Cloning into 'DbConnector'...
    remote: Counting objects: 11, done.
    remote: Compressing objects: 100% (10/10), done.
    remote: Total 11 (delta 0), reused 11 (delta 0)
    Unpacking objects: 100% (11/11), done.
    Checking connectivity... done.
    Submodule path 'DbConnector': checked out 'c3f01dc8862123d317dd46284b05b6892c7b29bc'

    Now your DbConnector subdirectory is at the exact state it was in when you committed earlier.

    There is another way to do this which is a little simpler, however. If you pass --recursive to the git clone command, it will automatically initialize and update each submodule in the repository.

    $ git clone --recursive https://github.com/chaconinc/MainProject
    Cloning into 'MainProject'...
    remote: Counting objects: 14, done.
    remote: Compressing objects: 100% (13/13), done.
    remote: Total 14 (delta 1), reused 13 (delta 0)
    Unpacking objects: 100% (14/14), done.
    Checking connectivity... done.
    Submodule 'DbConnector' (https://github.com/chaconinc/DbConnector) registered for path 'DbConnector'
    Cloning into 'DbConnector'...
    remote: Counting objects: 11, done.
    remote: Compressing objects: 100% (10/10), done.
    remote: Total 11 (delta 0), reused 11 (delta 0)
    Unpacking objects: 100% (11/11), done.
    Checking connectivity... done.
    Submodule path 'DbConnector': checked out 'c3f01dc8862123d317dd46284b05b6892c7b29bc'

    Working on a Project with Submodules

    Now we have a copy of a project with submodules in it and will collaborate with our teammates on both the main project and the submodule project.

    Pulling in Upstream Changes

    The simplest model of using submodules in a project would be if you were simply consuming a subproject and wanted to get updates from it from time to time but were not actually modifying anything in your checkout. Let’s walk through a simple example there.

    If you want to check for new work in a submodule, you can go into the directory and run git fetchand git merge the upstream branch to update the local code.

    $ git fetch
    From https://github.com/chaconinc/DbConnector
       c3f01dc..d0354fc  master     -> origin/master
    $ git merge origin/master
    Updating c3f01dc..d0354fc
    Fast-forward
     scripts/connect.sh | 1 +
     src/db.c           | 1 +
     2 files changed, 2 insertions(+)

    Now if you go back into the main project and run git diff --submodule you can see that the submodule was updated and get a list of commits that were added to it. If you don’t want to type --submodule every time you run git diff, you can set it as the default format by setting thediff.submodule config value to “log”.

    $ git config --global diff.submodule log
    $ git diff
    Submodule DbConnector c3f01dc..d0354fc:
      > more efficient db routine
      > better connection routine

    If you commit at this point then you will lock the submodule into having the new code when other people update.

    There is an easier way to do this as well, if you prefer to not manually fetch and merge in the subdirectory. If you run git submodule update --remote, Git will go into your submodules and fetch and update for you.

    $ git submodule update --remote DbConnector
    remote: Counting objects: 4, done.
    remote: Compressing objects: 100% (2/2), done.
    remote: Total 4 (delta 2), reused 4 (delta 2)
    Unpacking objects: 100% (4/4), done.
    From https://github.com/chaconinc/DbConnector
       3f19983..d0354fc  master     -> origin/master
    Submodule path 'DbConnector': checked out 'd0354fc054692d3906c85c3af05ddce39a1c0644'

    This command will by default assume that you want to update the checkout to the master branch of the submodule repository. You can, however, set this to something different if you want. For example, if you want to have the DbConnector submodule track that repository’s “stable” branch, you can set it in either your .gitmodules file (so everyone else also tracks it), or just in your local .git/config file. Let’s set it in the .gitmodules file:

    $ git config -f .gitmodules submodule.DbConnector.branch stable
    
    $ git submodule update --remote
    remote: Counting objects: 4, done.
    remote: Compressing objects: 100% (2/2), done.
    remote: Total 4 (delta 2), reused 4 (delta 2)
    Unpacking objects: 100% (4/4), done.
    From https://github.com/chaconinc/DbConnector
       27cf5d3..c87d55d  stable -> origin/stable
    Submodule path 'DbConnector': checked out 'c87d55d4c6d4b05ee34fbc8cb6f7bf4585ae6687'

    If you leave off the -f .gitmodules it will only make the change for you, but it probably makes more sense to track that information with the repository so everyone else does as well.

    When we run git status at this point, Git will show us that we have “new commits” on the submodule.

    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)
    
      modified:   .gitmodules
      modified:   DbConnector (new commits)
    
    no changes added to commit (use "git add" and/or "git commit -a")

    If you set the configuration setting status.submodulesummary, Git will also show you a short summary of changes to your submodules:

    $ git config status.submodulesummary 1
    
    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)
    
    	modified:   .gitmodules
    	modified:   DbConnector (new commits)
    
    Submodules changed but not updated:
    
    * DbConnector c3f01dc...c87d55d (4):
      > catch non-null terminated lines

    At this point if you run git diff we can see both that we have modified our .gitmodules file and also that there are a number of commits that we’ve pulled down and are ready to commit to our submodule project.

    $ git diff
    diff --git a/.gitmodules b/.gitmodules
    index 6fc0b3d..fd1cc29 100644
    --- a/.gitmodules
    +++ b/.gitmodules
    @@ -1,3 +1,4 @@
     [submodule "DbConnector"]
            path = DbConnector
            url = https://github.com/chaconinc/DbConnector
    +       branch = stable
     Submodule DbConnector c3f01dc..c87d55d:
      > catch non-null terminated lines
      > more robust error handling
      > more efficient db routine
      > better connection routine

    This is pretty cool as we can actually see the log of commits that we’re about to commit to in our submodule. Once committed, you can see this information after the fact as well when you run git log -p.

    $ git log -p --submodule
    commit 0a24cfc121a8a3c118e0105ae4ae4c00281cf7ae
    Author: Scott Chacon <schacon@gmail.com>
    Date:   Wed Sep 17 16:37:02 2014 +0200
    
        updating DbConnector for bug fixes
    
    diff --git a/.gitmodules b/.gitmodules
    index 6fc0b3d..fd1cc29 100644
    --- a/.gitmodules
    +++ b/.gitmodules
    @@ -1,3 +1,4 @@
     [submodule "DbConnector"]
            path = DbConnector
            url = https://github.com/chaconinc/DbConnector
    +       branch = stable
    Submodule DbConnector c3f01dc..c87d55d:
      > catch non-null terminated lines
      > more robust error handling
      > more efficient db routine
      > better connection routine

    Git will by default try to update all of your submodules when you run git submodule update --remote so if you have a lot of them, you may want to pass the name of just the submodule you want to try to update.

    Working on a Submodule

    It’s quite likely that if you’re using submodules, you’re doing so because you really want to work on the code in the submodule at the same time as you’re working on the code in the main project (or across several submodules). Otherwise you would probably instead be using a simpler dependency management system (such as Maven or Rubygems).

    So now let’s go through an example of making changes to the submodule at the same time as the main project and committing and publishing those changes at the same time.

    So far, when we’ve run the git submodule update command to fetch changes from the submodule repositories, Git would get the changes and update the files in the subdirectory but will leave the sub-repository in what’s called a “detached HEAD” state. This means that there is no local working branch (like “master”, for example) tracking changes. So any changes you make aren’t being tracked well.

    In order to set up your submodule to be easier to go in and hack on, you need do two things. You need to go into each submodule and check out a branch to work on. Then you need to tell Git what to do if you have made changes and then git submodule update --remote pulls in new work from upstream. The options are that you can merge them into your local work, or you can try to rebase your local work on top of the new changes.

    First of all, let’s go into our submodule directory and check out a branch.

    $ git checkout stable
    Switched to branch 'stable'

    Let’s try it with the “merge” option. To specify it manually, we can just add the --merge option to ourupdate call. Here we’ll see that there was a change on the server for this submodule and it gets merged in.

    $ git submodule update --remote --merge
    remote: Counting objects: 4, done.
    remote: Compressing objects: 100% (2/2), done.
    remote: Total 4 (delta 2), reused 4 (delta 2)
    Unpacking objects: 100% (4/4), done.
    From https://github.com/chaconinc/DbConnector
       c87d55d..92c7337  stable     -> origin/stable
    Updating c87d55d..92c7337
    Fast-forward
     src/main.c | 1 +
     1 file changed, 1 insertion(+)
    Submodule path 'DbConnector': merged in '92c7337b30ef9e0893e758dac2459d07362ab5ea'

    If we go into the DbConnector directory, we have the new changes already merged into our localstable branch. Now let’s see what happens when we make our own local change to the library and someone else pushes another change upstream at the same time.

    $ cd DbConnector/
    $ vim src/db.c
    $ git commit -am 'unicode support'
    [stable f906e16] unicode support
     1 file changed, 1 insertion(+)

    Now if we update our submodule we can see what happens when we have made a local change and upstream also has a change we need to incorporate.

    $ git submodule update --remote --rebase
    First, rewinding head to replay your work on top of it...
    Applying: unicode support
    Submodule path 'DbConnector': rebased into '5d60ef9bbebf5a0c1c1050f242ceeb54ad58da94'

    If you forget the --rebase or --merge, Git will just update the submodule to whatever is on the server and reset your project to a detached HEAD state.

    $ git submodule update --remote
    Submodule path 'DbConnector': checked out '5d60ef9bbebf5a0c1c1050f242ceeb54ad58da94'

    If this happens, don’t worry, you can simply go back into the directory and check out your branch again (which will still contain your work) and merge or rebase origin/stable (or whatever remote branch you want) manually.

    If you haven’t committed your changes in your submodule and you run a submodule update that would cause issues, Git will fetch the changes but not overwrite unsaved work in your submodule directory.

    $ git submodule update --remote
    remote: Counting objects: 4, done.
    remote: Compressing objects: 100% (3/3), done.
    remote: Total 4 (delta 0), reused 4 (delta 0)
    Unpacking objects: 100% (4/4), done.
    From https://github.com/chaconinc/DbConnector
       5d60ef9..c75e92a  stable     -> origin/stable
    error: Your local changes to the following files would be overwritten by checkout:
    	scripts/setup.sh
    Please, commit your changes or stash them before you can switch branches.
    Aborting
    Unable to checkout 'c75e92a2b3855c9e5b66f915308390d9db204aca' in submodule path 'DbConnector'

    If you made changes that conflict with something changed upstream, Git will let you know when you run the update.

    $ git submodule update --remote --merge
    Auto-merging scripts/setup.sh
    CONFLICT (content): Merge conflict in scripts/setup.sh
    Recorded preimage for 'scripts/setup.sh'
    Automatic merge failed; fix conflicts and then commit the result.
    Unable to merge 'c75e92a2b3855c9e5b66f915308390d9db204aca' in submodule path 'DbConnector'

    You can go into the submodule directory and fix the conflict just as you normally would.

  • Composer{PHP Only}:

    Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

    Dependency management

    Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

    This idea is not new and Composer is strongly inspired by node’s npm and ruby’s bundler. But there has not been such a tool for PHP.

    The problem that Composer solves is this:

    a) You have a project that depends on a number of libraries.

    b) Some of those libraries depend on other libraries.

    c) You declare the things you depend on.

    d) Composer finds out which versions of which packages need to be installed, and installs them (meaning it downloads them into your project).

PHPMAILER: Attach A File To An Email In PHP

The steps below shows you how to set up and use the PHPMailer library:

  • Import the PHPMailer Lib into your project either using Autoloader or Include. Library can be found @
  • Implement the code as below:


include('phpmailer.php');

$email = new PHPMailer();
$email->From = ‘##Source Mail ID##’;
$email->FromName = ‘##Mailer Name##’;
$email->Subject = ‘##Subject##’;
$email->Body = ‘##Content##’;
$email->AddAddress( ‘##destination Mail ID##’ );
$file = ‘##Path to File to be attached##’;
$email->AddAttachment( $file, ‘##label of file that is attached##’ );
return $email->Send();

if we want to attach a file to an email directly from an upload, you can pass in the uploaded file from the $_FILES global like so
$email->AddAttachment( $_FILES['attachment']['tmp_name'], $_FILES['attachment']['name'] );

Make sure your mail server is configured and is working. In case not then follow this to setup a local open source mail server