My Local Development Workflow with WAMP/XAMPP, GIT and Google Drive

I like to share my local development workflow which has turned out to be extremely useful in that all my projects’ files are versioned and on the cloud. I use git to keep my files versioned and Google Drive so that I can access my projects anywhere. In this post, I will share really cool stuff that you definitely should consider implementing for your own projects.

If you don’t know about git and its benefits, there are numerous compelling reasons why it is useful, you might want to check out:

The benefits of keeping all my files and projects on the cloud like Google Drive should be obvious but if you are still not sure, check out:

Although there are many other cloud storage services such as Microsoft SkyDrive, Dropbox, Box, Bitcasa, etc but I chose Google Drive since it gives 10GB of free space which should be enough for my development needs. If that’s not enough for you, you can create another Gmail account and get another 10GB free. You might want to read their usage policies too if you want.  You may also consider using Bitcasa which gives you unlimited space but since it is new, I can’t personally trust it as yet.

Installing Google Drive

Step 1: Create a new Gmail account to be used with Google Drive client software. Although you can use your existing account but it is good idea to create a new one used for your projects’ backup only.

Step 2: Download Google Drive from here or here. During the installation, you would be asked to specify the folder path which will be synchronized with Google Drive. Make sure that you specify a folder present on any drive other than your OS drive so that even if your system crashes or corrupts, your projects remain intact. For example, I have that folder on path D:/Google Drive/

Step 3:  Once installed, run Google Drive software and specify the credentials of your newly created Gmail account.

Using Google Drive with WAMP/XAMPP

Now that we’ve setup google drive, it is time to setup document root to google drive folder and create virtual host. This would allow you to run your local projects through WAMP/XAMPP from google drive folder. The reason why we do this is that since google drive folder will be sync by google drive software, any project we put in that folder will automatically be uploaded in your google drive account.

Note: I am using XAMPP but if you are using WAMP, some settings or file paths might be different, you should consider reading its documentation.

Step 1: Inside your google drive folder, create a new folder named webroot making whole path X:\Google Drive\webroot where represents your drive letter.

Step 2: Assuming you have specified google drive folder to be  D:/Google Drive/, open httpd.conf (normally located at apache\conf folder) file in notepad or other text editor and find the line Include “conf/extra/httpd-vhosts.conf”. If there is a hash (#) before that line, remove it. Now find the line with <Directory /> and you should see something similar to:

<Directory />
 AllowOverride none
 Require all denied
</Directory>

Change Require all denied  to Require all granted

Or if you see something like:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

Change it to:

<Directory />
    ........
    Allow from all
</Directory>

Now come to bottom of the file and add:

<Directory "D:\Google Drive\webroot">
  Options Indexes MultiViews
  Order Allow,Deny
  Allow from all
</Directory>

Save the file and close it.

Step 3: Open httpd-vhosts.conf (normally located at apache\conf\extra folder) and add these lines at the end of it:

<VirtualHost 127.0.0.1:80>
    DocumentRoot "D:/Google Drive/webroot"
    ServerName gdroot.loc
    ServerAlias gdroot.loc
    ErrorLog "D:/Google Drive/webroot/logs/error.log"
    CustomLog "D:/Google Drive/webroot/logs/access.log" combined
</VirtualHost>

Save the file and close it. Notice that we have specified gdroot.loc as address which actually means google drive root (.loc signals that it is local folder) which actually maps to your google drive webroot folder eg D:/Google Drive/webroot. Notice that you could name it anything you want like mycoolwebsite.com, yourname.com, etc but of course that is local folder running from your own computer.

Step 4: Open hosts file in notepad or other text editor located at X:\Windows\System32\drivers\etc where stands for drive letter where your OS is installed. At the end of that file add this line assuming you specified URL in above step as gdroot.loc:

127.0.0.1       gdroot.loc

Or if you also use port to access your LAMP/XAMPP URLs, specify that as well:

127.0.0.1:PORT_NUMBER_HERE       gdroot.loc
Note: If you can’t edit hosts file, you need to have file owner permission, search on google how to do that.

Restart apache and access the new url by typing gdroot.loc in your browser. You should see screen similar to when you go to http://localhost.

Congratulations ! you have a nice workflow now. You can now put all your existing our new projects inside your new document root which was assumed to be located at D:\Google Drive\webroot and now all your projects are sync with google drive and automatically uploaded to your google account which you can access anywhere. For example, you can now access your projects at office or any other computer by installing google drive client software  there and telling it sync/download your webroot folder. Your projects are now always there and backed up on the cloud :)

Let’s take cool stuff one step further by using git so that our projects file are also versioned. If you don’t know much about git and its benefits consider reading links posted above or below in the Git Resources section.

Using Git with a Central Repository

Creating and using central repository is especially useful in a team. If you just want to keep your projects versioned and are the only developer working on a project, the normal flow is (unless you track your project to remote host such as github):

  • modify files
  • commit your changes
  • repeat

So essentially you can skip this section if you just want to version your project files and are only developer working on a project.

Step 1: Download msysgit from here, choose first link from there. Install it with default settings.

Step 2: Go to your google drive folder (D:\Google Drive\) and create a new folder there named central.git

Step 3: Right click on newly created folder and choose Git Bash Here and type: git init –bare

Step 4: Create a test project folder named myproject inside your normal WAMP/XAMPP webroot/htdocs folder or google drive webroot folder mentioned above (Although you can git-manage any folder anywhere on the drive but naturally we want to git-manage projects that we run from webroot/htdocs folder).

Step 5: Right click on newly created folder, choose Git Bash Here and issue these commands one by one:

git init
git remote add central /e/Google\ Drive/central.git/
git push --all central
git push --set-upstream-to central master

Great! now we’ve setup central repository for all our git-managed projects and we can commit, push, fetch all changes from that central repository. For any new repository, you can now issue commands like:

git clone /e/Google\ Drive/central.git/
git fetch /e/Google\ Drive/central.git/
git push central
and so on

Hope you liked the post and have fun !

Git Resources

Stack Overflow Tips & Tricks

Disclaimer: I have shared my personal ideas in this article, i do not encourage or ask  anyone to misuse, game Stack Overflow reputation system just to earn points. You are expected to be helpful to others and get help when you need it..

.

Stack Overflow is moving fast to becoming the de facto standard to assess your programming skills and knowledge. It has a system of awarding reputation points that you get by providing correct answers to others or asking questions that are voted up. If you have earned a good reputation figure, you can show that on your site, blog or your resume; this will throw a positive impact on anyone who visits your site, blog or an employer who sees your resume. Also if you have earned good reputation, chances are that you might be selected as moderator on the stack overflow.

For me, it has been great experience with this magnificent site. Undoubtedly, i have learned a loooooot from it and like most others, i have also become addicted to this site because of the wealth of knowledge and benefits it offers. Here i share the tips and tricks that i have utilized on this site and have earned me good reputation in a very short time but before that let’s be clear about the fact that there is no magic to getting reputation points; you do have to provide the correct answers to the questions posed by others or ask most logical questions that stimulate others to vote up your questions. Nobody cares about your reputation besides you. You are not here to enlarge your reputation, you are here to give answers to people asking questions.

1. Get 100 Reputation Points Free

If you have earned at least 200 reputation points on SO (Stack Overflow), you can get 100 more by associating other sister accounts of SO. Click your username on top to go to your profile and then click on the accounts tab as shown in the picture below:

There you see other sister sites of SO:

  • Server Fault
  • Super User
  • Meta Stack Overflow

Authenticate these sites by pressing corresponding authenticate button. This should give you 100 reputation points. Now that you have earned 100 reputation points and signed up on these sites, you are expected to help others on these sites too or get help for yourself. If you think you can involve yourself in any of these three sites, go for them.

2. Add “Interesting” & “Ignored” Tags

To be able to earn reputation points, you should be able to provide correct answers to the questions posed by others. In order to know that a question relevant to your expertise has been posted, you need to add Interesting tags. To do so, go to your profile (by clicking your username on top) and then  click on the prefs tab present just before the accounts tab. There you can add your interesting and ignored tags; for example the interesting tags are those you are good at like it can be php, mysql, java, etc. Add as many as you think. Similarly, you also need to add Ignored tags; doing this will remove all questions from SO homepage that are not as per your expertise and this will also increase your chances of answering a question before anyone else does. I will expand on this in the next tip below.

3. Install Greasemonkey Script

You need to install the “StackOverflow Interesting Tags First” script. When you install it and visit SO homepage, then all your interesting tags will be pushed up there by greatly increasing your chances of answering a question before anyone else and I am sure most SO users are not aware of this great piece of script. Note that Greasemonkey works in Firefox and Chrome currently.

4. Be the First to Answer a Question

If there is question you think you know the answer of, jump to it instantly and answer it. If you have answered it correctly and are the first to answer then if anyone else visits that question, he may vote you up rather than providing his own correct answer that you have already provided. By default, all answers are ordered by number of votes, so if you manage to get some votes, your answer will be on top of all there by having more chances of getting votes and finally chosen as the final correct answer something for which you earn 15 additional points. Getting your answer (correct one) to be first just makes it more likely to get quick votes but remember this is not the rule of thumb, an answer posted after even half an hour can be voted up and chosen as the final correct answer.

Another important thing is that once you have posted your answer, you can revise it, add more details such as lists, images, etc. This shows how comprehensive answer you have given with examples/demos and makes your answer best in the queue.

5. Markdown

SO employs what is known as “MarkDown” for adding style to your text. Familiarize yourself with it, this will help you quickly add indentations, lists and more to your answers. You will mostly be indenting your code which can be done by selecting some text and pressing the Cntr+K keys combination.

6. Don’t Over-Style Your Answers

This has happened to me, if i add styles such as bold, colors, etc to most of the text of my answers, i get down votes even if my answer is correct. Other users don’t like this because it makes them feel that this guy is trying to get more attention than our answers (which are not necessarily styled). And of course you are supposed to provide correct answers rather than providing styled answers. Avoid this as much as possible and also note that styling can take more time something decreasing your chances of answering a question first.

7. Add Pictures

To reinforce your answers, you can add pictures to them by copy pasting a picture url you know or searching on google. This makes your answer best of all. But remember, only add images when they help the answer – not just to make it shiny.

8. Use Google Effectively

There are many questions posted which make you search on the google for their answers. If you think there is an answer on a certain site but you don’t remember page’s url, you can put google to use. For example, there was a question posted about “long vertical dropdown menu” and i knew that there was a solution for that on the css-tricks.com site but i did not remember page’s url, so i committed the search like this on google:

site:css-tricks.com [SPACE] mysearch keywords

And guess what i was the first to answer this question and my answer was chosen as final for that question. But if you don’t have any idea of it, you can simply search that on google without specifying any specific site.

9. Use JS Bin

The JS Bin is the tool you can use to create and preview your html, javascript, css files online instantly. This turns out to be extremely handy when it comes to question about javascript, jquery, html or css. What is more you can instantly create your pages and create a public link  for them and show that link in your answers as demo. You could also you Pastebin if you are looking for more language options. Once you provide the demo, your answer looks most authoritative.

10. Edit Your Answers Cleverly

If you have already answered a question, you can make that question jump back on top of SO homepage. The trick is that you should edit your answer after 5 minutes period of time. Once the question is pushed on top of the SO homepage, there are higher chances of other users visiting that question and voting you up. Having said that, don’t edit your answers too much otherwise it will be turned into “Community Wiki” answer by SO and then you won’t be scored even if your answer is voted up.

11. Keep Your References Open

You should always keep your reference code or cheat sheets open so as to quickly locate the syntax or any details relevant to the question. For example, I always keep PHP official reference and JQuery cheat sheet open and this helps me greatly.

12. Involve Yourself to Earn Badges

Other than reputation points, you would also like to earn Badges. There are a number of factors involved in earning these badges:

  • Your answers gets a lot of votes.
  • Your question gets a lot of votes.
  • You revise others’ questions.
  • You provide feedback to the comments.
  • etc….

I hope that you guys have a better time at Stack Overflow…

.
.
.tweet_this

Handy PHP Tips & Tricks

I have written some handy php tips and tricks right into a php file that puts them to use. You will learn some of the hidden tricks and pitfalls. Of course you would come to this file again and again unless you remember everything it contains. So here is the code with explanation:

$newline = "\n___________________________________________\n\n";
$br = "\n";

////////////////////////////////////////////////////////////
$name = 'Sarfraz';

// variable recognition in single and double quotes
print 'hello $name\n'.$br;
print "hello $name$br";

// reading string varibale as array / extracting text
print $name[3];
print $newline;
////////////////////////////////////////////////////////////

// heredoc: useful way of representing string vars. It can be handy
// in echoing out the html code or related text.
// PHP Comments inside heredocs are not applicable

$url = '/deal.php';
$text = 'Deal More Cards';
$remaining_cards = 5;

print <<< HTML
There are <b>$remaining_cards</b> cards left.

<a href="$url">$text</a>
HTML;
echo $br;

// second example
$a = <<< END
Once upon a time, there was a
END
. ' boy!';
print $a.$br;

// third example

print <<< END
Right now, the time is
END
. strftime('%c') . <<< END
 but tomorrow it will be
END
. strftime('%c',time() + 86400);
print $newline;
////////////////////////////////////////////////////////////

// read chars from backward using negatvie start value
print substr('watch out for that tree',-6);

print $newline;
////////////////////////////////////////////////////////////

$message = <<< TEXT
The function substr_replace is useful when you've got text that's too big to display all at once, and you want to display some of the text with a link to the rest. For example, this displays the first
25 characters of a message with an ellipsis after it as a link to a page that displays more text
TEXT;

printf('<a href="more-text.php?id=%d">%s</a>',
       1, substr_replace($message,' ...',25));
print $newline;
////////////////////////////////////////////////////////////

// counts vowels in a given string using strstr
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    if (strstr('aeiouAEIOU',$string[$i])) {
        $vowels++;
    }
}
print "Number of vowels are: $vowels";
print $newline;
////////////////////////////////////////////////////////////

//To reverse by words, explode the string by word boundary,
// reverse the words, then rejoin:

$s = "Once upon a time there was a turtle.";
$words = explode(' ',$s);
$words = array_reverse($words);
$s = join(' ',$words);
print $s.$br;
print $newline;
////////////////////////////////////////////////////////////

/*
The trim functions can also remove user-specified characters
from strings. Pass the characters you want to remove as a second argument. You can indicate a range of characters with two dots between the first and last characters in the range.
*/
// Remove numerals and space from the beginning of the line
print ltrim('10 means ten',' 0..9').$br;
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
print $newline;
////////////////////////////////////////////////////////////

//Use split( ) or preg_split( ) if you need a POSIX or Perl regular //expression to describe the separator:
// regexp plus means one or more chars
$words = split(' +','This sentence  has  some extra whitespace  in it.');

foreach($words as $value)
{
    print $value . " ";
}
echo $br;
print_r($words);
print $newline;
////////////////////////////////////////////////////////////

/*
Helpfully, is_numeric properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric( ) to return false.

To strip the thousands separators from your number before calling is_numeric( ) use str_replace( ):
*/
$number = "5,100";
print is_numeric(str_replace($number, ',', ''));
print $newline;
////////////////////////////////////////////////////////////

// ==========================================
// Variable variables (IMPORTANT)
// ==========================================

/*
You want to construct a variable's name dynamically. For example, you want to use variable names that match the field names from a database query.
*/
$animal = 'turtles';
$turtles = 103;
print $$animal.$br.$br;

/*
The previous example prints 103. Because $animal = 'turtles', $$animal is $turtles,
which equals 103.

Using curly braces, you can construct more complicated expressions that indicate variable names:
*/

$stooges = array('Moe','Larry','Curly');
$stooge_moe = 'Moses Horwitz';
$stooge_larry = 'Louis Feinberg';
$stooge_curly = 'Jerome Horwitz';

foreach ($stooges as $s) {
  print "$s's real name was ${'stooge_'.strtolower($s)}.\n";
}
print $newline;
////////////////////////////////////////////////////////////

// This is how to capture page data before showing it to the user's browser:

$user = "Sarfraz";

ob_start();
var_dump($user);
$dump = ob_get_contents();
ob_end_clean();
print $dump;

print $newline;
////////////////////////////////////////////////////////////

// StrPos Usage Warning

/*
strpos() returns the location of the first substring within a string. If the
substring isn't found, strpos( ) returns false. If it is found, it returns an integer with the position. Therefore, to find a substring position, you might write:
if (strpos($string, $substring)) { found it! }

However, if $substring is found at the exact start of $string, the value returned is 0.
Unfortunately, inside the if, this evaluates to false, so the conditional is not executed.

Here's the correct way to handle the return value of strpos( ):
*/

if (false !== strpos("hello there", "hello")) { print "found"; }

print $newline;
////////////////////////////////////////////////////////////

// open the index.php in main window / frame.
header('Window-target: main');
header('Location: index.php');

////////////////////////////////////////////////////////////

/*
You want to force output to be sent to the browser. For example, before doing a slow database query, you want to give the user a status update.

The flush() function sends all output that PHP has internally buffered to the web server, but the web server may have internal buffering of its own that delays when
the data reaches the browser. Additionally, some browsers don't display data immediately upon receiving it, and some versions of Internet Explorer don't display a page until they've received at least 256 bytes. To force IE to display content, print blank
spaces at the beginning of the page:
*/

print str_repeat(' ',300);
print 'Finding identical snowflakes...';
flush();
$sth = $dbh->query('SELECT shape,COUNT(*) AS c FROM snowflakes');
////////////////////////////////////////////////////////////
/*
You want to start generating output before you're finished sending headers or cookies.

Call ob_start at the top of your page and ob_end_flush( ) at the bottom. You can
then intermix commands that generate output and commands that send headers.
The output won't be sent until ob_end_flush( ) is called:
*/

/*
<?php ob_start(); ?>
I haven't decided if I want to send a cookie yet.
<?php setcookie('heron','great blue'); ?>
Yes, sending that cookie was the right decision.
<?php ob_end_flush(); ?>
*/

/*
You can pass ob_start( ) the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots:

<?php
function mangle_email($s) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        '<$1@...>',
                        $s);
}

ob_start('mangle_email');
?>

I would not like spam sent to ronald@example.com!

<?php ob_end_flush(); ?>

The mangle_email( ) function transforms the output to:
I would not like spam sent to <ronald@...>!
*/
////////////////////////////////////////////////////////////
/*
You want to process a variable with a period in its name, but when a form is submitted, you
can't find the variable.

Replace the period in the variable's name with an underscore. For example, if you have a form
input element named foo.bar, you access it inside PHP as the variable $_REQUEST['foo_bar'].

Because PHP uses the period as a string concatenation operator, a form variable called
animal.height is automatically converted to animal_height, which avoids creating an
ambiguity for the parser. While $_REQUEST['animal.height'] lacks these ambiguities, for
legacy and consistency reasons, this happens regardless of your register_globals
settings.
*/

////////////////////////////////////////////////////////////

/*
You can put a username and password in the URL if you need to retrieve a protected page. In
this example, the username is david, and the password is hax0r. Here's how to do it with
fopen( ):

$fh = fopen('http://david:hax0r@www.example.com/secrets.html','r')
    or die($php_errormsg);
while (! feof($fh)) {
    $page .= fread($fh,1048576);
}
fclose($fh);
*/
////////////////////////////////////////////////////////////

// Build query string from an array

$query = http_build_query($array);

////////////////////////////////////////////////////////////