Wednesday, May 5, 2010

CodeIgniter Helpers – How to write your own?

Find yourself again and again doing CI or are you just getting started in to your next big project ? Get this book by Rob Foster. This is an easy-to-follow guide consisting of a number of projects that enable you to develop full-featured applications at a fast pace. CodeIgniter Web Application Blueprints

What is here:
         -> What is a codeigniter helper? an example
         -> Creating your own codeigniter helper, create a helper which will have a function to Check Ajax requests
         -> Accessing sessions/models from within Helpers
         -> A tip on how to load codeigniter models from within another model.

From CI site
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.

A helper can be loaded anywhere within your controller functions (or even within your View files, although that's not a good practice), as long as you load it before you use it.
Let me give you and example:
in controller, model or view you have to first load the helper you want to use with following line:
$this->load->helper('name');
where ‘name’ === is helper file residing in ===>  application/helpers/name_helper.php (custom helper if exists)
or system/helpers/name_helper.php (bundled with codeigniter)

‘name’ is the name you want for your helper, then a _ (underscore) & helper.php, the codeigniter’s way.
if you want to look at a sample: go check system/helpers folder, they come bundled with codeigniter. Here’s a snippet from: system/helpers/url_helper.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('site_url'))
{
    function site_url($uri = '')
    {
        $CI =& get_instance();
        //every time you need to use codeigniter system libraries or functions or model you’d do this      through the get_instance
        return $CI->config->site_url($uri);       
    }
}
Remember, when you used this site_url() function?? okay what you did was:
loaded the helper at your controller construction or where ever you needed using,  $this->load->helper('url');and simply echo site_url(); or like that. 

How to write your own helper  : Check Ajax Request using Codeigniter Helper

Yesterday, while going through my current project, I was calling lots of controller actions with jQuery Ajax and i was in need to check whether the call/request is made through Ajax or not in the controllers. Since i needed a way to use this facility in lots of controllers, i thought helpers would come handy here.
Rather than just copy/pasting the same lines of code in every controllers or at times you may need to use same functions in models & views too, it is good practice to make this function have some separate space in helpers (but not a good practice to load helper in views, see above, from CI site). So you should be clear at first whether your function need a place in helper or not??? Ask yourself  and decide for your work, if the frequency of your function call is going to be maximum, sure create a new helper or extend existing one. I decided to create one in my case.
Okay let’s make our Ajax request checker?? isAjax() function, residing in useful helper. When i Googled around for checking Ajax request i found a three line snippet here CHECK FOR AJAX REQUEST, i’ll will be implementing this for our purpose here. It goes like this:
function isAjax() {
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}
The Helper:
system/application/helpers/useful_helper.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
//secure your snippet from external access
function isAjax() {  
           return ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');  
      }
?>
Using in Controller: application/controllers/somecontroller.php
function submit_form(){
//function you call when you submit your form through Ajax. 
$this->load->helper('useful'); //load our just defined helper
if(isAjax()){
          echo ‘The request is made throug ajax. success!’ ;
          //do your stuffs
          exit;
       }     
}
 
Accessing session/models from within Helpers
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
      function isAjax() {  
           return ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');  
      }
     function check_login(){     
      //$userId = $this->session->userdata('userid); this line will not work here <<-----
       // you'd access your session variables through get_instance() as below
       $CI =& get_instance();
       //now session access through this instance
       $userId = $CI->session->userdata('userid);
       if ($userid < 0 ) {
              return 0; //user not logged in
           }
      else {
             return 1; user session exists, must be logged in 
           }
      }
  function hello_model_world(){     
        //or if you decided to load & use you models here
        //$this->load->model('Hello_model');   <---- this will not work too.
        //use as 
         $CI =& get_instance(); //first get instance
         $CI->load->model('Hello_model');  //then load model through instance.  
         //and calling a model function
         $data = $CI->Hello_model->display_this(‘hello world!’);
        //assuming your model returns capitalizing the initial letters of the words
         return $data; //will give Hello World! 
      }
?>
Now, you can easily load your helper in controllers & models and use it as regular helpers.

Extra tip about loading codeigniter model from another models:

You see how handy the $CI =& get_instance(); is in helpers. okay, let me add a quick tips talking about this, what if at times you needed to find out a way to load another models in your current model?? Ok here’s the solution:
<?php
class Test_model extends Model {
function Test_model()
    {
        //Call the Model constructor
        parent::Model();
    }
function do_something(){
//you wanted to load another model called Hello_model here in this function in this model class
//it’s okay
//use
         $CI =& get_instance(); //first get instance
         $CI->load->model('Hello_model'); //then load model
         $data = $CI->Hello_model->display_this(‘hello world!’); //call functions
         //do anything with this $data        
}
}
?>


Happy Coding.
Regards


Monday, May 3, 2010

Hello World – CodeIgniter Model – A Simple Bookmark Manager

Continued from Hello World – CodeIgniter!

I’ve been a bit busy with my development works. Talking about codeigniter,i will discuss today on how we can use it to access MySql database, insert data into tables, retrieve and display them, at times delete them. We’ll create a very simple Bookmark Manager App (just for the sake of understanding models in codeigniter, i’ve added code over the last article )

  what we’ll do today 

-1. if you don’t have codeigniter yet, download it from ci site.
0.rename extracted CodeIgniter zip folder to ci & add it to your server root - xampp/htdocs or wamp/www  folder
1. Database Design: create database & table representing our Bookmark Storage requirement & save some configuration setting so that codeigniter recognizes which database we want to work on.
2. Model: describe the database accessing logic (called business logic, it’s where the real business goes, your data will be your business & you’ll build logic over this business) – CRUD – create, retrieve, update, delete actions, in Models of the codeigniter
3. Controller: use the Controller to access data from the Model & pass them to View so that it can display them.
4. View: Create a simple View with HTML forms, that helps user with CRUD operations
5. Test

1. Create Database named ci_test going to http://localhost/phpMyAdmin, click on this database, there are zero tables yet.  copy paste the table structure by going to SQL link. and Go.

CREATE TABLE IF NOT EXISTS `bookmarks` (
  `bookmark_id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`bookmark_id`),
  UNIQUE KEY `url` (`url`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

http://localhost/phpMyadmin Interface: Create table from SQL

You created your database & table.

Open application/config/database.php and change as followings

$db['default']['hostname'] = "localhost";  //hostname
$db['default']['username'] = "root";          //default user name in local dev environment
$db['default']['password'] = "";                 //default password is blank
$db['default']['database'] = "ci_test";       //our database
$db['default']['dbdriver'] = "mysql";          //we are going to use MySql database

leave others as default for now. Now you told codeigniter to use our database in the application we are going to build.

2. Defining Model (a PHP class that’ll wrap our relation database model to Object Oriented style)

Here Bookmarks_Model  is a  PHP class, file name bookmarks_model.php & with some methods inside it inside the Models folder,
filename: Application/Models/bookmarks_model.php
the relation between file name & class name is
classname = ucfirst($filename)  without .php extension ok //first letter uppercase

it will look like this

 

<?php
class Bookmarks_model extends Model {

    var $url   = '';
    var $description = '';   

    function Bookmarks_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    function get_last_ten_entries()
    {
        $query = $this->db->get('bookmarks', 10);
        return $query->result();
    }

    function save($u,$d)
    {       
        $this->url = $u;
        $this->description = $d;               
        $this->db->insert('bookmarks', $this);       
    }
    function delete($id)
    {       
        $this->db->where('bookmark_id', $id);
        $this->db->delete('bookmarks');        

    }

    function update_entry()
    {
        $this->url  = $_POST['url'];
        $this->description = $_POST['desc']; 
        $this->db->update('bookmarks', $this, array('bookmarks_id' => $_POST['id']));
    }

}
?>

 3. Inside Controller

Here Hello is a  PHP class, file name helllo.php & with some methods inside it inside the controller folder. controller & function inside it are the only way user can interact with our system, that’s why we can say controller has control over the flow of the application, we’ll access this controller later as:  http://localhost/ci/index.php/hello and each function inside it as – see comment in the code.

The naming convention for filename & class name is
classname = ucfirst($filename)  without .php extension

filename: application/controllers/hello.php 

<?php

  class Hello extends Controller {
  function Hello()
    {       
        parent::Controller();
        $this->load->database();//load database library  
        $this->load->model('Bookmarks_model'); //load just defined model
    }

    function index($data='') { 
      //accessed from url when typed http://localhost/ci/index.php/hello
      $bookmarks=$this->Bookmarks_model->get_last_ten_entries();     
      //call the function inside model which returns last ten entries
      $data['bookmarks']=$bookmarks;                  
      //create $data array with the values returned from the model function
      $this->load->view("hello_view",$data);
      //load the view named hello_view.php passing $data to it.
    }

    function save()
    {     
     //accessed from url when typed http://localhost/ci/index.php/hello/save
     //retrieve data from the form post method
     $u=$this->input->post('url');    
     $d=$this->input->post('desc');            
     //check for validity
    if ($u==''&& $d==''){       
        echo "Invalid, Entry";               
    }
    else{       
    //if valid data, call the function of the model which will save our data
    //to database   
     $this->Bookmarks_model->save($u,$d);   
     echo "Thanks, Link Added!";        
    }
  }
  function del($id)
    {
    //del function is receiving data from URL
    //accessed from url when typed http://localhost/ci/index.php/hello/___id___
    //___id___ is the promary key of the data   
    //delete data by passing primary key  
    $this->Bookmarks_model->delete($id);
    echo "Thanks, Link Deleted!";                
  }
  }
?>

4. the view
no naming convention for a view. build your own but you should make it easier to link your controller action to view memorable. just remember you’ll load (like used to include) views using filename without extension in controller. if you like extension see user guide for more $this->load->view options.

filename: application/views/hello_view.php 

<h1>Bookmark Manager </h1>
//simple php for each loop to iterate throug our data
//remember $bookmarks was passed from the controller as index of the $data variable, which is accessed here as an array of object.
//if you want to view the structure of the $bookmarks array uncomment the line below this.
//print_r($bookmarks);
//initially the array will be blank, but will show it’s structure after you add some data using the form.

<?php foreach($bookmarks as $b) : ?>

<?php echo $b->description;?><br>
<a target='_blank' href='<?php echo $b->url;?>'><?php echo $b->url;?></a>
<a href='<?php echo base_url() .'hello/del/'. $b->bookmark_id;?>'> Del</a>
<hr>
<?php endforeach; ?>
<br><br>

//html form to help add data to the database

//the action of the form is defined as the save method of the hello controller.
// base_url() function gives the root path of this project
//defined in application/config/config.php as
//$config['base_url']    = http://localhost/ci/index.php/;

<form method="post" action="<?php echo base_url() .'hello/save'; ?>">
Url:<input type='text' name='url' > <br>
Description:<input type='text' name='desc' > <br>
<input type="submit" value="Add">
</form>

5. Now go test the application you just created.

 


Let’s memories $data flow in Codeigniter once

Model –  to – Controller – to – View   flow i.e.
from database to – [ PHP code to/Data Manipulation ] – HTML presentation

1. Go through the user guide, remember this, when you see the terms Model, View & Controller – you just keep focused in the PHP Classes inside  the folders named Models, Controllers & Views within the system/application folder of the codeigniter.

 

ci-mvc

Model – PHP files, each file, each class for each table in database or group as you like, application/models,
View – PHP files, each file, presentation for actions(methods/functions) in controller, application/views
Controller - PHP files, each file, each class that control application flow, application/controllers

2. when they say, build a model for your database, think that you are going to create PHP files, each for each table.. etc…  with a class with some function to access database (using SQL queries or ORM/object relation mapper or plane SQL) & return these data to controller as array or objects like you used to return 0;  in C/C++ main functions.

function get_last_ten_entries()
    {
       //codeigniters default ORM activerecord’s way to retrive data
       //produces sql like -- select * from bookmarks limit 10
        $query = $this->db->get('bookmarks', 10);
        return $query->result();//return data to calling function from controller, returns objects array
    }

3. When they say access data from the model – you’ll be calling from controller or view a function inside a codeigniter models php file to retrieve data from the database. like this.

//load model like you use to include dbconfig.php or whatever, wherever in controller you need
$this->load->model('Bookmarks_model');
//use the function inside it through the loaded model instance
$bookmarks=$this->Bookmarks_model->get_last_ten_entries();   //an object array  

data returned from model is stored invariable $bookmarks

4. when they say, pass data to the view, you’ll be using a simple codeigniter function to pass data to a function which is used to load view (php files inside the views folder).

why you accessed data in controller? obviously to display or act upon it: so let’s pass it to view that handles our display system, no data manipulation for now.

//create $data array with the values returned from the model function
$data['bookmarks']=$bookmarks;                  

//load the view named hello_view.php passing $data to it.
$this->load->view("hello_view",$data);

5. When they say, design/markup a view? you are going to add some PHP files in the Views folder, name it as you like but keep the name in order so that it’ll be easier to reference later which controller is calling which view??

//you passed the variable bookmarks from step 3(controller), to step 5 (view) in summary just above. now access it & display it.
<?php
foreach($bookmarks as $b) :?>
echo $b->description;
echo ‘<br>’;
echo $b->url;<hr>
endforeach;
?>

Hope this helps you to start out with CodeIgniter, you are ready to explore on your own now. 
Regards.

Sunday, May 2, 2010

Social Network Database Design Sample - MySQL

what?
------
sample database for a social network project – a mysql database schema
Database Engine: InnoDB (edit the mwb file if you need to change it to MyISAM or any other.)
the aspects of a social network i tried to cover in this database:
- user profile
- friends
- friends list
- status updates
- thumbs up/down status (these can be easily ported to other entities)
- bookmark saving
- rss/atom feeds saving
- notifications
- chat
- blog, site level not user level

user

- privacy
profile
why?
------
you can use these files for beginning a social n/w type projects in PHP/MySQL development environment.
when i was doing social network project, i searched here & there for database design of a social network, but what i found in the internet were not useful. they provided a introductory sketch about social network database structure but but as i had a limited  time frame for my project, those materials were not useful. i have analyzed most of the basic requirements for a  social network database structure, and sharing this with you so that it would save some of your time to start out your project. 
statusthe database is not completely normalized yet but you can edit it as per your needs. don't waste to much time on what  fields should i use for profile or for a status representation, these entity sets in the design will suffice in most of the cases. You can add entities for pictures, video, music sharing or anything you like. Just use the workbench design file.






Here are few books i'd recommend if you are willing to dive deep into MySQL and database designs

1. Beginning MySQL Database Design and Optimization: From Novice to Professional
or
2. High Performance MySQL: Optimization, Backups, and Replication

files included
-----------------
following files are included
sns.7.0-.mwb - MySql WorkBench Design
sns.7.0.png - exported PNG from MySql workbench
sns7.0.sql - exported SQL from MySql Workbench
sns.yml - Doctrine Generated schema in YAML
you can use the MySQL WorkBench Designer available Open Source at http://wb.mysql.com & begin with the mwb file,
change it for your need, export to sql & use it for your project.
Download MySQL Social Network Database Design – Sample

Update 11/14/2011:
Many readers have requested how the project ended up in look.
So, here goes the slide we presented to Tribhuvan University (with formal details cut out).
Thanks for reading this post.

TimiHami a Nepali Social Network







Monday, March 22, 2010

Blogger Post & Comment Feed URLs

Recent Posts RSS feed url
http://yourBlogAddress.blogspot.com/feeds/posts/default

Recent Comments RSS feed url
http://yourBlogAddress.blogspot.com/feeds/comments/default

Label Specific Feed url
http://yourBlogAddress.blogspot.com/posts/comments/default/-/labelname

Replace -> yourBlogAddress with your actual blogger address.
Replace -> labelname with your label

Hope That Helps.

Sunday, March 21, 2010

Hello World – CodeIgniter!

So you decided to learn CodeIgniter PHP MVC Framework. I am too starting with it and planning to post a series of introductory tutorials on it. Here i go with – Hello World example in CodeIgniter.
Install Code Igniter
http://codeigniter.com/

Download CodeIgniter copy form the above site. The version i am using is 1.7.2
I assume you have setup your local development environment installing XAMPP bundle, and your browser shows http://localhost correctly. Otherwise you may want to refer Starting with PHP.
Let’s Begin.
Unzip the CodeIgniter file you downloaded to your root folder. You’d have a folder named CodeIgniter_1.7.2. Open it and see how files/folders are organized their.
If everything went ok, try entering http://localhost/CodeIgniter_1.7.2/ or http://localhost/CodeIgniter_1.7.2/index.php in your browser. you’ll have the default CodeIgniter page welcoming you.
We’ll learn to define our Hello World page as the index page at the end of this article.

Understand the folder organization

Here i have a snapshot of the structure of the CodeIgniter folder. Look carefully at the folder organization here. I will complete this tutorial explaining this figure.


codeigniter


As you can see.. there’s the system & user_guide folder, index.php and license.txt file in the extracted folder. Inside system folder there’s application folder. which is the main folder that contains our Web Application files. Other folders inside the system folders are Framework’s folder and we don’t need to change them at this time.
You can see CodeIgniter has wrapped the M – Models, V – Views and C – Controllers inside the application folder. You’ll get use to these and other folder slowly.
models folder – used to represent classes and object, which will interact with the database.
views folder – this is where we define the presentation or our web layouts.
controller folder – all the logic of the web application will be written inside controller folder, in simple php files. Each file contains a class definition and a class would have methods inside it.



Role of the controller
Controller is the main entrance to your web app. Whatever you’d do to interact with the web application all web request you make will reach the controller and handled by it. It plays vital role in the application structuring.

Our database requirement and data accessing classes will be defined inside the models folder in simple php files. The controller will make use of this classes to access data and pass the accessed data to the view i.e where user can see the result.
STEP 1:

Simply, create a file hello.php inside the controller folder. Copy & paste the following code. The code is simple and the comments will clear things.



<?php 


class Hello extends Controller {

function index() {

$data['helloMsg'] = "CodeIgniter says, Hello world!";
//Data is passed from the controller to the
//view by way of an array or an object in the
//second parameter of the view loading function.
$this->load->view("hello_view",$data);
//Where hello_view is the name of your view file.
//Note: The .php file extension does not need to be specified
//u
nless you use something other than .php
}

}
?>


The name of the class is Hello with capital H and the file name is hello.php, you should understand this convention. We simply define a class Hello that extends the base class Controller which will allow us to use inherited methods from this base class.

$data['helloMsg'] = "CodeIgniter says, Hello world!";

We have defined a $data array with helloMsg as index. The controller passes data either in Array or in Object form to the view. This is the reason why we didn’t make a simple php variable to pass data.

$this->load->view("hello_view",$data);

Then we passed the $data variable to the hello_view. which is the view we’ll use to display this data. The index ‘helloMsg’ will be available to the view as $helloMsg variable, simple. hello_view is simply a php file inside views folder created as follows.

STEP 2:

Now, create a file hello_view.php inside the views folder. Copy & paste the following code.
<h1> Welcome to CodeIgniter. </h1>
<?php echo $helloMsg ?>
Since it’s the view part and as i already mentioned we can use our HTML knowledge as far as we can. I have added two kind of text here for illustration, the normal HTML <h1> tag and other printed from the dynamic variable. $data variable was passed from the controller to the view, and hence $helloMsg its index is available here in view. We use simple php echo to display it.


STEP 3:

We are done. Now it’s time to test it. http://localhost/CodeIgniter_1.7.2/index.php/hello try typing this in the browser. If everything worked fine you’d see this output:


Welcome to CodeIgniter.

CodeIgniter says, Hello world!
DEFAULT CONTROLLER
(Setup your hello.php as default controller)
Okay, since we have successfully passed data from controller to the view to render it, now let’s define our hello class as the default controller of the application we are going to build. For this open the routes.php file inside the application/config .
find this line
$route['default_controller'] = "welcome";
and change it to
$route['default_controller'] = "hello";
okay it’s done now, try

http://localhost/CodeIgniter_1.7.2/index.php/hello
or
http://localhost/CodeIgniter_1.7.2/index.php
both will output our hello_view file.

SUMMARY

We understood the organization of folders in CodeIgniter, and their functions. We created our own controller, passed some data from controller to it’s corresponding view, displayed it there. and finally we made our custom controller as the default one. Now you can extend it someway, try adding some cool HTML/CSS/JavaScript in the view & try storing passing data from controller. By then, you’d created a simple web application.
This might seem like we just stored some values in PHP array and displayed as in old general fashion, but what’s the difference here? It’s different – now we’ve accomplished Hello World! output from a MVC framework. Yeah, now we have the full control of our web application from within a framework. You’ll feel more organized and managed once you get used to this MVC separation in CodeIgniter. Also, we can use extensive resources and help available in CodeIgniter site & online.
I suggest now, go through the user guide included in the CodeIgniter folder and understand more about Controller & Views. I’ll try to cover Models and how they are used in later covers.

http://localhost/CodeIgniter_1.7.2/user_guide
or
http://codeigniter.com/user_guide/

Saturday, February 13, 2010

Protect your Gmail from spams – use mail aliases

There’s no argument that Gmail is the best free email service. Notable features include – Maximum Storage (~8GB ), POP3 Mail Support, Mail Labels, Mail Alias, Filters, Theme Support/Customization. Now the Social Google BUZZ is also integrated in Gmail.

Taking in account of all these features and sudden exposure of your Gmail ID as your Public Profile by the BUZZ it’s necessary that you learn some tricks/Gmail features to protect your Gmail from SPAMS.

With launch of so many nice and handy web services day to day, we just tend to sign up and try out new services as quick as possible. But you should take care that your online identity i.e your email is being shared there and there is no guarantee that these new sites will respect your privacy. They might sell your mails to spammers and you might suddenly end up in hundreds of spam mails in your inbox.

Further, If you give a quick look at your Gmail Profile URL there’s your email ID openly Buzzing around. This also increases chance that you’ll be spammed. It is just a matter of minute to extract your email id from your happy tweeted Google Buzz profile URL. A simple Twitter Search like this will disclose thousands of Tweets containing Buzz Profile URL.

Here are two ways that you can use with ease so that spam are better handled.

1. Gmail’s Mail Aliasing Feature:

Your gmail id is something like urid@gmail.com

Note: gmail id must be at least 6 char long. i’ve used urid for illustration.

You can create mail aliases as:

urid+anyname@gmail.com

Where anyname can be anything as your need, but @ sign in not supported in between. The specialty of aliased mail address is that any mail sent to this email will reach your inbox.

You can create any number of aliases for each different sites you sign up.

This will ensure that mails from each individual sites are managed with a unique aliased email id and if you noticed some spam behavior from this aliased mail you can simply create filter or report spam for the incoming mails.

Now, when you sign up to a new site use any friendly mail alias. Note it down for future in case you need to use password recovery options. When you sign up you are at your will sending your mail address to the site’s database. But we can’t be sure unless some trusted sites that those mail addresses will be kept confidential. If such sites sold your aliased mail address to other sites then you’ll clearly see in your inbox that your mail is being sold around. You can then create filters to send this messages to trash or report the site site you signed up as spam.

Example Use of mail alias:

If you are signing up for a new sport site, create an alias as:

urid+sport_site_name@gmail.com

If you are signing up for a new music site, create an alias as:

urid+music_site_name@gmail.com

2. Change your Public Google BUZZ URL to string of numbers.


People are sharing their Google Profile all way in public pages,like in their twitter. Since, there’s one to one mapping of your email address to the Google Profile the shared profile url may attract spammers.

I have mentioned above that, a simple Twitter Search like this will disclose thousands of Tweets containing Buzz Profile URL. or any Google search will display the shared URLs. So, you should take care sharing this URL.

You can change your profile URL to some random strings of numbers from Google Profile Edit page.

At the bottom of the page under Profile URL section, change your profile url to those strings of numbers.

profile

Now you can freely share your buzz URL around with some lowered spam risk.

Happy Buzzing. Happy Tweeting.

Follow me in Twitter: @bhu1st

Here’s my BUZZ: Bhupal Sapkota

Friday, November 21, 2008

MS-DOS BATCH PROGRAMMING

INFORMATION ON BATCH FILES

BATCH FILE ABCs

Batch files are programs that allow MS-DOS and Windows users to create a file to perform a long tasks fast. Such as opening certain programs ran frequently, deleting or managing files, etc. Simple batch files do not require any special programming skills and usually can be done by knowing the below commands and or just DOS commands.

A prime example of a batch file for someone whom may know more about Windows or MacOS would be relating a batch file to a shortcut in Windows or icon on a MacOS. Batch files like a shortcuts are small file which is used to run frequently accessed programs.

Another example of a very well known batch file is the autoexec.bat, which is simply a boot file loaded each time the computer is loaded. Within this file contains various lines to load various programs and drivers into memory each time the computer boots.

CREATING A BATCH FILE

To create a basic batch file first open a MS-DOS command prompt and follow the below instructions:

At the MS-DOS prompt type edit test.bat and press enter.
If typed properly you should now be in a blue screen within the blue screen type:
pause
dir c:\windows
dir c:\windows\system
Once the above three lines have been typed in the blue screen choose file and choose exit, when prompted to save click yes
Once you are back at the MS-DOS prompt type test. When enter is pressed, this should execute the test.bat file and begin running the file. Because the first line is pause you will first be prompted to press a key. Once you press a key the batch file will run line by line in this case listing the files in the windows and windows\system directory.
If you wish to add more lines to this batch file you would simply type "edit test.bat" to edit the file again.

BATCH COMMANDS

Just like all MS-DOS commands when creating batch files the lines are not case sensitive. However, in the below listing we have listed all commands in all caps to help you identify which text is a batch file command.

@ Does not echo back the text after the at symbol. This is most commonly used as @ECHO OFF to prevent any of the commands in the batch file from being displayed just the information needed.
%1 The percent followed by a numeric value, beginning with one, allows users to add variables within a batch file. The following is a batch file example:
echo Hello %1
When the above one line batch file is created and adding your name after the batch file. For example typing myname (being the name of the bat file) and then your name:
myname bob
would output
Hello bob

:LABEL By adding a colon in front of a word such as LABEL you create a category, more commonly known as a label. This allows you to skip to certain sections of a batch file such as the end of the batch file. Also see GOTO.

CALL This is used to run another batch file within a batch file. When the batch file that is called is completed the remainder of the original batch file is completed. Note if the batch file does not exist it will give an error message.

CHOICE See running different programs for example of how to use this command.

CLS Just like the DOS command would clear your screen.

ECHO Will echo a message in the batch file. Such as "ECHO Hello World" will print Hello World on the screen when executed. Note if you have not typed @ECHO OFF at the beginning of the file this will also print "ECHO Hello World" and "Hello World". If you would just like to create a blank line type ECHO. adding the period creates an empty line.

EXIT Exits out of the DOS window if the batch file is ran from Windows.

GOTO LABEL Used to go to a certain label such as LABEL. An example of GOTO would be to

GOTO END. For an Example of this see running different programs.

IF Used to check for a certain condition if the condition exists. If that condition exists it will perform that function.. To see an example of this see running different programs.

PAUSE Prompt the user to press any key to continue.

REM Allows you to place comments into the batch file without displaying or executing that line when the batch file is ran.

SHIFT Changes the position of replaceable parameters in a batch program. You can use this command only in batch programs.

START Used for Windows 95, Windows 98, and Windows NT 4.0 and above to start a windows application such as START C:\WINDOW\CALC would run the Windows Calculator. Users running Windows 3.x need to utilize the WIN command. For example WIN C:\WINDOWS\CALC.EXE would run Windows and then Calculator after Windows has finish loading.

BATCH FILE EXAMPLES

Running different programs
Deleting files in directory without prompt
How to start Windows 95 / 98 files from batch file
Creating a batch file delay
How to make time log

RUNNING DIFFERENT PROGRAMS

The following is a simple example of how you can implement the choice options into your batch files. Each line that is in red can be left out of the batch file. They have been included to help explain some of what the batch file means.

@ECHO OFF
REM - LABEL INDICATING THE BEGINNING OF THE DOCUMENT.
:BEGIN
CLS
REM - THE BELOW LINE GIVES THE USER 3 CHOICES (DEFINED AFTER /C:)
CHOICE /N /C:123 PICK A NUMBER (1, 2, or 3)%1
REM - THE NEXT THREE LINES ARE DIRECTING USER DEPENDING UPON INPUT
IF ERRORLEVEL ==3 GOTO THREE
IF ERRORLEVEL ==2 GOTO TWO
IF ERRORLEVEL ==1 GOTO ONE
GOTO END
:THREE
ECHO YOU HAVE PRESSED THREE
GOTO END
:TWO
ECHO YOU HAVE PRESSED TWO
GOTO END
:ONE
ECHO YOU HAVE PRESSED ONE
:END

HOW TO START APPLICATIONS FROM A BATCH FILE

To run files for Windows 95 or Windows 98 in a batch file you would use the START command. The following example would run Windows Notepad.

START /M "C:\WINDOWS\NOTEPAD.EXE"

The /m representing it to start the window Maximized.

CREATING A BATCH FILE DELAY

The following is an example of how to delay a batch file any where from 5 to 99 seconds. In the below example we illustrate a 5 second delay.

TYPE NUL | CHOICE.COM /N /CY /TY,5 >NUL

Additionally you could use the sleep file found on our utility download section.

HOW TO MAKE A TIME LOG

In the following example you will have the capability of creating a time log of when the batch file is loaded or for example in the autoexec.bat when someone logs into a computer.

ECHO. |TIME > TIME
COPY LOG +TIME

An alternate slightly more complicated method that to our knowledge cannot be used in Windows NT, Windows 2000 or Windows ME would be the following:

echo @prompt set date=$d$_set time=$t$h$h$h > {a}.bat
%comspec% /e:2048 /c {a}.bat > {b}.bat
for %%v in ({b}.bat del) do call %%v {?}.bat
echo %date% %time% >> log

For the above batch file to work properly you must create a file called log by typing "edit log" (without the quotes) and then save an exit the file which will create the file at 0 bytes. If this file is not created or not created properly you will receive the error message "Content of destination lost before copy".

How to restart the computer with a batch file:
It may be necessary after a batch file is completed its copying or installing process to restart the computer to complete that installation.

Solution:

MS-DOS

If the computer needs to be restarted from MS-DOS please see our debug page for additional information on how to do this.

Windows

If the computer needs to be restarted from Windows 98 within the batch file type:

START C:\WINDOWS\RUNDLL.EXE user.exe,exitwindowsexec
EXIT

When typing the above two lines spacing is important. It is also very important that the exit line be placed into the batch file as Windows cannot exit the window unless it is specified.

Additionally you may also type the following line in:

rundll32.exe shell32.dll,SHExitWindowsEx n

Where n is equal to one of the following numbers for the proper action.

0 - LOGOFF
1 - SHUTDOWN
2 - REBOOT
4 - FORCE
8 - POWEROFF

Tuesday, January 1, 2008

Remove Autorun Virus : Simple Approach

Make following FILES in your Desktop, be sure of the extensions. Now when you insert your removable drive. Just don't open it.

Select these all files -> Right Click -> Send To -> Removable Drive Letter.

Replace Files ? Dialog May Appear if your removable drive is infected by virus.

autorun.bat
autorun.bin
Autorun.exe
Autorun.ico
AUTORUN.INF
Autorun.ini
autorun.reg
autorun.srm
autorun.txt
autorun.vbs
autorun.wsh
autorun.zip
Autorun.~ex
bittorrent.exe
MFC32DLL.dll.vbs
ms32.dll.vbs
MS32DLL.dll.vbs
msvcr71.dll
RavMon.exe
sal.xls.exe


The virus files would be replaced by these 0 Bytes files. Hence no effect of virus on your computer.

Thursday, December 27, 2007

How Autorun Virus works in Windows Xp?

How to make AUTORUN Viruses:
--------------------------- ------
The pendrive viruses generally follow Autorun procedure of Windows OS.
When you plug your PENDRIVE or any removable storage device to USB Port,
the PLUG AND PLAY feature of Windows Xp first looks for the file AUTORUN.INF
and anyname following AUTORUN.* convention. Generally following files will be present in the list:

Autorun.inf // INFORmation file
Autorun.bat // Dos BATCH file EXECUTABLE
Autorun.vbs // Windows Scripting HOST WSCRIPT.EXE file , written using VB-SCRIPTING
Autorun.bin // ---
Autorun.ico // This icon file will be the ICON of your VIRUSED PenDRIVE
Autorun.com // Executable
Autorun.exe // Executable
or
somename.exe // Executable

The "autorun.inf" file contains information for the EXPLORER to Look the files to executable on click at pendrive icon. we'll use autorun.bat as executable at this Demo. You can have your virus code and reference it as an executable in "autorun.inf" file.


How to make a simple autorun VIRUS
------------------------------------
(Try it, it won't harm your computer. just a demonstration)


STEP1:
make "autorun.bat" using any text editor.
the *.bat files are DOS executable scripts.
eg:
----------CUT THE CODE--------------------
@echo off
@cls
@echo "this is a simple autorun test..."
@echo .
@echo .
@pause
@exit
-------SAVE CODE in a file autorun.bat-----

STEP2:
make "autorun.inf" using any text editor.
eg:

----------CUT THE CODE--------------------

[autorun]
open=autorun.bat
icon=autorun.ico
shell\open=Open
shell\open\Command=autorun.bat


-------SAVE CODE in a file autorun.inf---


STEP3:
find a "*.ico" or an icon file and rename it as
autorun.ico. this icon would be ther icon of your REMOVABLE DRIVE in My computer


STEP4:
till this step you should have following files at hand:

autorun.inf
autorun.bat
autorun.ico

Now make these files HIDDEN, SYSTEM and READONLY files,
Right Click -> Properties -> Attributes

if you are familiar with DOS, follow this:
copy these three files to folder named VIRUS in Drive C:
open DOS Prompt

type following DOS Commands:
-------------------------
cls
c:
cd\
cd virus
attrib *.* +s +h +r

-----------------------
this would make your VIRUS ready to copy to PENDRIVE



SETEP4: THE LAST STEP

Now open the C:\VIRUS Folder
goto tools menu -> Folder Options..
"under VIEW tab check followings"
-> Show hidden files
-> show protected operating system files

- if your VIRUS folder is opened you should see these 3 files HIDDEN..
- Now copy these files into your PENDRIVE.
- BOOM you are done.
- Remove your pendrive and plug it again to USB port.
- If you CLICK on PENDRIVE ---- BLAST! Virus would Run...