Friday, 17 May 2013

How to replace plain URLs with links in JavaScript or PHP?

Hello Friends

If you want to convert plain text in to URLs in JavaScript or PHP. This is good solution for you.
In PHP :

[sourcecode language="php"]
public function makeLinks($str)
{
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$urls = array();
$urlsToReplace = array();
if(preg_match_all($reg_exUrl, $str, $urls)) {
$numOfMatches = count($urls[0]);
$numOfUrlsToReplace = 0;
for($i=0; $i<$numOfMatches; $i++) {
$alreadyAdded = false;
$numOfUrlsToReplace = count($urlsToReplace);
for($j=0; $j<$numOfUrlsToReplace; $j++) {
if($urlsToReplace[$j] == $urls[0][$i]) {
$alreadyAdded = true;
}
}
if(!$alreadyAdded) {
array_push($urlsToReplace, $urls[0][$i]);
}
}
$numOfUrlsToReplace = count($urlsToReplace);
for($i=0; $i<$numOfUrlsToReplace; $i++) {
$str = str_replace($urlsToReplace[$i], "<a target='_balnk' href=\"".$urlsToReplace[$i]."\">".$urlsToReplace[$i]."</a> ", $str);
}
return $str;
} else {
return $str;
}
}
[/sourcecode]
In JavaScript

[sourcecode language="javascript"]
function makeLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a target='_blank' href='$1'>$1</a>");
}
[/sourcecode]

Hope it helps.

Wednesday, 15 May 2013

8 Things Productive People Do During the Workday

Forget about your job title or profession – everyone is looking for ways to be more productive at work. It’s time to set down your gallon-sized container of coffee, toss out your three-page to-do list, and put an end to those ridiculously long emails you’ve been sending.

8 Things Productive People Do During the WorkdayExperiencing a highly productive workday can feel euphoric. But contrary to popular belief, simply checking tasks off your to-do list isn’t really an indication of productivity. Truly productive people aren’t focused on doing more things; this is actually the opposite of productivity. If you really want to be productive, you’ve got to make a point to do fewer things.

Harness your productivity by taking note of these eight things:

1. Create a smaller to-do list. Getting things accomplished during your workday shouldn’t be about doing as much as possible in the sanctioned eight hours. It may be hard to swallow, but there’s nothing productive about piling together a slew of tasks in the form of a checklist. Take a less-is-more approach to your to-do list by only focusing on accomplishing things that matter.

2. Take breaks. You know that ache that fills your brain when you’ve been powering through tasks for several hours? This is due to your brain using up glucose. Too many people mistake this for a good feeling, rather than a signal to take a break. Go take a walk, grab something to eat, workout, or meditate – give your brain some resting time. Achieve more productivity during your workday by making a point to regularly clear your head. You’ll come back recharged and ready to achieve greater efficiency.

3. Follow the 80/20 rule. Did you know that only 20 percent of what you do each day produces 80 percent of your results? Eliminate the things that don’t matter during your workday: they have a minimal effect on your overall productivity. For example, on a project, systematically remove tasks until you end up with the 20 percent that gets the 80 percent of results.

4. Start your day by focusing on yourself. If you begin your morning by checking your email, it allows others to dictate what you accomplish. Set yourself in the right direction by ignoring your emails and taking the morning to focus on yourself, eat a good breakfast, meditate, or read the news.

5. Take on harder tasks earlier in the day. Knock out your most challenging work when your brain is most fresh. Save your busy work – if you have any – for when your afternoon slump rolls in.

6. Pick up the phone. The digital world has created poor communication habits. Email is a productivity killer and usually a distraction from tasks that actually matter. For example, people often copy multiple people on emails to get it off their plate – don't be a victim of this action. This distracts everyone else by creating noise against the tasks they’re trying to accomplish and is a sign of laziness. If you receive an email where many people are CC'd, do everyone a favor by BCCing them on your reply. If your email chain goes beyond two replies, it’s time to pick up the phone. Increase your productivity by scheduling a call.

7. Create a system. If you know certain things are ruining your daily productivity, create a system for managing them. Do you check your emails throughout the day? Plan a morning, afternoon, and evening time slot for managing your email. Otherwise, you’ll get distracted from accomplishing more important goals throughout the day.

8. Don’t confuse productivity with laziness. While no one likes admitting it, sheer laziness is the No. 1 contributor to lost productivity. In fact, a number of time-saving methods – take meetings and emails for example – are actually just ways to get out of doing real work. Place your focus on doing the things that matter most as efficiently and effectively as possible.

Remember, less is more when it comes to being productive during the workday.

What’s your secret to productive workdays?

Tuesday, 12 February 2013

Set php.ini Values Using .htaccess

Did you know that you can set php.ini values right inside the .htaccess file? It's actually very easy.

The .htaccess Code


#format
php_value setting_name setting_value#example
php_value upload_max_filesize 10M

Of course you could simply place these in the .htaccess file, but .htaccess is a viable alternative if your host doesn't allow you to touch the php.ini file.

Resource :

http://davidwalsh.name/php-values-htaccess

Prevent Your CSS and JavaScript Files From Being Cached

Some websites use highly volatile, oft-changing CSS and JavaScript files. In the case of these files, it's important that the developer prevent browsers from caching them. How do we do that? By using a phantom querystring, of course. We'll use PHP to tack the current time onto the file reference.

The PHP


[sourcecode language="php"]
<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" >
<-- RENDERS -->
<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css">

<script type="text/javascript" src="/site-script.js?<?php echo time(); ?>"></script>
<-- RENDERS -->
<script type="text/javascript" src="/site-script.js?1234567890"></script>
[/sourcecode]

It's a very simple technique and doesn't affect your CSS or JavaScript code in any way.

Resource :

http://davidwalsh.name/prevent-cache

Android Detection with JavaScript or PHP

Hello Friends

You have a web application and you want to detect that if your Application is opened from android device than it will be redirect to any other URL that will be Android compatible.This is a good solution for you.

What's obvious is that Android development is a hot topic that will only grow. Here are a few methods by which you can detect iOS' main competitor: Android.

The JavaScript


Searching the user agent string for "Android" is the quickest method:

[sourcecode language="php"]
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid)
{
// Do something! // Redirect to Android-site? window.location = 'http://android.viralsolani.co';
}

[/sourcecode]

The PHP


Again, we'll use PHP's strstr function to search for Android in the user agent:

[sourcecode language="php"]
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false){// && stripos($ua,'mobile') !== false) {
header('Location: http://android.viralsolani.co');
exit();
}
[/sourcecode]

Bonus! .htaccess Detection



We can even use .htaccess directives to detect and react to Android devices!

[sourcecode language="php"]
RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://android.viralsolani.co [R=301]
[/sourcecode]

And there you have it: three different Android device detection! Have fun with your mobile development!

Resource :

http://davidwalsh.name/detect-android

Thanks

 

Wednesday, 6 February 2013

How to install SSL Certificates with Apache 2 on Ubuntu 12.04

Please note that commercial SSL certificates require a unique IP address each for SSL-enabled site, although multiple non-SSL sites may also share that IP address.

Step – 1 Create a Certificate Signing Request

A CSR is an encrypted body of text. Your CSR will contain encoded information specific to your company and domain name; this information is known as a Distinguished Name or DN.
In the DN for most servers are the following fields: Country, State (or Province), Locality (or City), Organization, Organizational Unit, and Common Name. Please note:
1. The Country is a two-digit code -- for the United States, it's 'US'. For countries outside of the United States,
2. State and Locality are full names, i.e. 'California', 'Los Angeles'.
3. The Organization Name is your Full Legal Company or Personal Name, as legally registered in your locality.
4. The Organizational Unit is whichever branch of your company is ordering the certificate such as accounting, marketing, etc.
5. The Common Name is the Fully Qualified Domain Name (FQDN) for which you are requesting the ssl certificate.
If you are generating a CSR for a Wildcard Certificate your common name must start with *. (for example: *.digicert.com). The wildcard character (*) will be able to assume any name that does not have a "dot" character in it.
To remain secure, certificates must use keys which are at least 2048 bits in length. If your server platform can't generate a CSR with a 2048-bit key

[sourcecode language="php"]
mkdir /etc/apache2/ssl
cd /etc/apache2/ssl
openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr
[/sourcecode]

Replace yourdomain with the domain name you're securing. For example, if your domain name is viralsolani.co, you would type viralsolani.co.key and viralsolani.co.csr.

• This begins the process of generating two files: the Private-Key file for the decryption of your SSL Certificate, and a certificate signing request (CSR) file (used to apply for your SSL Certificate) with apache openssl.

• Open the CSR file with a text editor and copy and paste it (including the BEGIN and END tags) into the form from where you purchase your SSL certificate.

• Save (backup) the generated .key file as it will be required later for Certificate installation

Execute the following command to protect the key:
chmod 400 /etc/apache2/ssl/www.yourdomain.com.key

Execute the following command to protect the signed certificate:

[sourcecode language="php"]
chmod 400 /etc/apache2/ssl/www.mydomain.com.crt

[/sourcecode]

Step – 2 Get the Certificate Authority Root Certificate
In My case it is Go Daddy. So you need to go from wherever you purchase your SSL certificate and you need to submit the below generated CSR. And you can then download the certificate.
You will get two files. I’ve upload that two files in same folder where I’ve put my CSR and Private key that i.e /etc/apache2/ssl/
Step – 3 Configure Apache to use the Signed SSL Certificate.

This configuration vary depend upon OS and version of that OS. So I’ve installed Ubuntu 12.04 and to configure the certificate you need to do below steps.
You need to configuration in Apache virtual hosting file.
So now you need to go: /etc/apache2/sites-available/default-ssl

[sourcecode language="php"]
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin viral.solani@gmail.com

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

SSLCertificateFile /etc/apache2/ssl/yourdomain.com.crt
SSLCertificateKeyFile /etc/apache2/ssl/yourdomain.com.key
SSLCertificateChainFile /etc/apache2/ssl/gd_bundle.crt

</VirtualHost>
</IfModule>

[/sourcecode]

Basically you need to locate yourdomain.com.crt , yourdomain.com.key and gd_bundle.crt.
Now last thing you need to do is restart you apache with the following command

[sourcecode language="php"]
/etc/init.d/apache2 restart

[/sourcecode]

You should now be able to visit your site with SSL enabled. Congratulations, you've installed a commercial SSL certificate!

Monday, 28 January 2013

2012 in review

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.



Here's an excerpt:



4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 14,000 views in 2012. If each view were a film, this blog would power 3 Film Festivals

Click here to see the complete report.

Thursday, 6 December 2012

Understanding Abstract Classes in PHP

Abstract classes are an often misunderstood feature of PHP object-oriented programming (OOP) and the source of confusion when considered versus an Interface. The obvious reason for using an Interface is that a child class can implement multiple interfaces but extend only a single abstract class. However, if multiple inheritance is not required then people often go with abstract classes just because they provide the option of later adding base functionality within the abstract class. This is not entirely unreasonable but the reasons for creating abstract classes should be more than that.
Why Use Abstract Classes?

An Abstract class provides concrete base functions as well as abstract functions that must be implemented by concrete child classes—binding them into a contract so to speak, if they wish to make use of the base functionality.

This is a subtle but important point and this is where abstract classes really shine. They can call abstract functions from within base concrete functions. Jumping straight to an example is the clearest way to explain this.

[sourcecode language="php"]
abstract class Animal {
function greeting() {
$sound = $this->sound(); // exists in child class by contract
return strtoupper($sound);
}
abstract function sound(); // this is the contract
}

class Dog extends Animal {
function sound() { // concrete implementation is mandatory
return "Woof!";
}
}

$dog = new Dog();
echo $dog->greeting(); // WOOF!
[/sourcecode]

This opens up a whole lot of interesting possibilities. For example, you can write a drive() function that calls $this->start(); $this->accelerate(); in an abstract class. Then create a motorcycle class that defines its own start() and accelerate() functions that may be different from those in the car class. In turn, the motorcycle and car can both be driven by just calling drive() without having to implement it locally.
Characteristics of Abstract Classes

Make a note of these characteristics to lock down your understanding of abstract classes:

  • Single inheritance. Child classes can extend only one class at a time.

  • Abstract classes cannot be instantiated — no new Animal();

  • Abstract classes can define class variables of type const only.

  • Abstract class A can be extended by another abstract class B. Abstract class B can implement none or any of the abstract functions in A.

  • In the previous case, a child class C which extends abstract class B must implement all abstract functions in B as well as the abstract functions in A which have not already been implemented in B.

  • The signature of the concrete functions and abstract functions must be the same. However, if an abstract function is defined as abstract function speak($greeting); then it is okay to implement it as function speak($greeting, $shout = FALSE) but not function speak($greeting, $shout).

  • The visibility of functions in the child classes must be the same or less restrictive than the parent class. Thus, a protected abstract function can be implemented as either protected or public but not private.

  • Declaring functions as static abstract throws a strict warning in PHP 5.2 or earlier, however, as of PHP 5.3 this is allowed.

Wednesday, 26 September 2012

Friday, 25 May 2012

Writing Your First Twitter Application with oAuth

Hello Friends

In My current application There is requirement to fetch twitter timeline for the particular user. So I’ve fetched it with the help of Rest API of twitter an oAuth.

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. In layman’s terms, it is a system by which you can allow a user to authenticate with an OAuth-enabled service without providing you with their credentials to that service.

Why OAuth?


Using OAuth allows you to write applications that access the Twitter API but do not require your users to give you their Twitter username and password. This is important for a variety of reasons:

  • If the user changes their Twitter login, they do not have to update that information with you for your application to continue working for them

  • Using OAuth puts the user in control – if they ever wish to stop using your application, they can disable it through Twitter instead of trusting your application to stop using their login information. Once they disable it through Twitter, any requests by your application will require them to manually approve the connection again.

  • Increased sense of trust, since the user doesn’t have to worry about your application stealing their Twitter credentials and using it for nefarious purposes. I personally wouldn’t trust any web-based application that asks for my Twitter username and password, and given Twitter’s recent history of bad press regarding their security, more and more users are following that lead.


Getting Started – Registering Your Application with Twitter


First of all , you have to register your new application with Twitter. You’ll need a name and url for your application in order to register it, and you’ll need to define a callback url. The callback url is the full url of the page Twitter should send the user to after it’s done authenticating. This file can be named anything you want, but make sure the one you create on your server matches the one you register with Twitter. All of these details can be changed later if you change your mind or need to update something.

Once you’ve registered your application, Twitter will issue you a Consumer Key and a Consumer Secret for your new app. You’ll need these to get your sample code from the Twitter OAuth library working. As you can probably tell by the name, your Consumer Secret should remain private and you should never give it out to anyone. It’s used in your code so that Twitter can identify your application when you’re making API calls.

By forcing you to send your consumer key and secret with your API calls, Twitter is able to determine which application is sending the API calls, and can verify that the Twitter user you are attempting to send API requests on behalf of has actually authorized your application to access their account. If the user decides they no longer want to allow your application, they can edit their allowed application preferences and your application will no longer be able to make API calls on their behalf.

You can access a list of all of the applications you have registered with Twitter – and links to edit their details or view the consumer key and consumer secret – by going to your oauth clients page on Twitter.

The Twitter OAuth PHP Library Code


There are several oAuth Twitter -libraries for PHP. But I Recommend Abraham’s Twitter OAuth library . You can pull the code from http://github.com/abraham/twitteroauth.

This library does provide an example script. You need to replace your Consumer Key and a Consumer Secret in confing.php. Please check that callback.php file should be one that we’ve registered with Twitter as being our callback url. We can keep common configuration options such as the consumer key and consumer secret, and database credentials in a config.php file. Now you can run index.php.

Now in your callback.php you can save access_token in database for future request. You can use that access token to call the APIs and you don’t need to enter Twitter user name and password.

[sourcecode language="php"]
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
[/sourcecode]

Here you can dowanload the whole code from git hub. you just need to put your Consumer Key and a Consumer Secret in config.php and need to check callback url settings it should be demo's callback.php and than you can run index.php you will get the result.

https://github.com/viralsolani/twitter-oAuth-example

Important Links

Hope it helps

 

Thursday, 24 May 2012

PHP SDK & Graph API base Facebook Connect Tutorial

Hello Friends

In My current application I've used facebook Graph API to fetched data from facebook with the help of  PHP SDK. I've explored so many tutorials on web but I found some links are very helpful and easy to understand Here I'm sharing those links. By surfing through these links you can get to know these below things

1 . How you can create your application in Facebook and How you can use APP ID and APP Secret? 

2. How you can connect to Facebook from your Application?

3. How you can fetch data with the help of Facebook Graph API and PHP-SDK?

4. How you can Design your Facebook Application?

So here are some useful links.

  1. http://www.londatiga.net/it/how-to-create-facebook-application-with-php-for-beginner/

  2. http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/

  3. http://net.tutsplus.com/tutorials/php/wrangling-with-the-facebook-graph-api/

  4. http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/

  5. http://net.tutsplus.com/tutorials/javascript-ajax/design-and-code-an-integrated-facebook-app/


To Create a New Application in Facebook.

https://developers.facebook.com/apps
Graph API

https://developers.facebook.com/docs/reference/api/
PHP SDK refrence

https://developers.facebook.com/docs/reference/php/
FB Tool for Graph API Explorer

http://developers.facebook.com/tools/explorer

Hope it helps.


profile for Viral Solani at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday, 24 April 2012

Autoload your classes in PHP

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

This is how it works in action. We will create two classes. So create Image.php file and paste this in:

[sourcecode language="php"]
<?php
class Image {
function __construct() {
echo 'Class Image loaded successfully <br />';
}
}
?>
[/sourcecode]

Now create Test.php file and paste this in:

[sourcecode language="php"]
<?php
class Test {

function __construct() {
echo 'Class Test working <br />';
}
}
?>
[/sourcecode]




Basically, we created 2 simple classes with constructors which echo some text out. Now, create a file index.php and paste this in:


[sourcecode language="php"]
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}

$a = new Test();
$b = new Image();
?>
[/sourcecode]





When you run index.php in browser, everything is working fine (assuming all 3 files are in the same folder). Maybe you don’t see a point, but imagine that you have 10 or more classes and have to write require_once as many times.

I will show you how to properly throw exception if you are using PHP 5.3 and above. Chane your index.php to look like this:
[sourcecode language="php"]
<?php
function __autoload($class_name) {
if(file_exists($class_name . '.php')) {
require_once($class_name . '.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}

try {
$a = new Test();
$b = new Image();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
[/sourcecode]





Now, it checks if file exists and throws a proper Exception if it doesn’t.

That’s it. A handy functionality to spare some typing.

Sunday, 18 March 2012

PHP 5.4 is Released — What’s New?

It’s difficult to believe almost three years have elapsed since PHP 5.3.0. The next version should have been PHP 6.0 but unicode problems have delayed development. This latest version provides many of the features planned for version 6.0.

PHP 5.4 is available to download from the php.net website. There’s a PHP 5.3 migration guide if you want to keep your old settings. While it’s stable, you’d be advised to test your sites and applications before installing it on live servers. The PHP team often release a bug-fix version a few weeks after the initial release.

So let’s look at the best new features and improvements…

Short Array Syntax


It’s now possible to use finger-saving JavaScript-like square brackets rather than using the old array(…) construct, e.g.


  1. $array1 = [1, 2, 3];

  2. $array2 = [

  3. "one" => "first",

  4. "two" => "second",

  5. "three" => "third"

  6. ];



Traits


Traits reduce some limitations of single inheritance. In essence, traits are similar to abstract classes and can contain any number of properties and methods. A class can then use any number of traits, e.g.



  1. trait Hello

  2. {

  3. function sayHello() {

  4. return "Hello";

  5. }

  6. }

  7. trait World

  8. {

  9. function sayWorld() {

  10. return "World";

  11. }

  12. }

  13. class MyWorld

  14. {

  15. use Hello, World;

  16. }

  17. $world = new MyWorld();

  18. echo $world->sayHello() . ' ' . $world->sayWorld();



For more information, refer to Using Traits in PHP 5.4 on PHPmaster.com.

Built-in Web Server


PHP 5.4 offers a built-in web server which runs from the Windows, Mac or Linux command line. While it’s not Apache or IIS, it’s fine for simple testing. I suspect many of the better PHP IDEs will implement support shortly.

For more information, refer to PHP 5.4′s New Built-in Web Server.

New Commands


A number of useful commands have been implemented:

  1. hextobin(string $hex): coverts a hex representation of data to binary.

  2. http_response_code(int $code): allows you to set or get the HTTP response code, e.g. http_response_code(404);

  3. header_register_callback(string $function): allows you to register a function which is called when PHP starts sending output.

  4. trait_exists(string $name [,bool $autoload]): determines whether a trait exists and, optionally, whether it should be autoloaded.


Miscellaneous Updates


If that’s not enough…

  • Class members can be accessed on instantiation, e.g. (new MyClass)->MyMethod()

  • <?=$variable?> is always available regardless of how your short_open_tag ini option is set.

  • Binary numbers can be declared, e.g. 0b11110000

  • Session upload progress has been implemented so PHP can track the state of file uploads.

  • Some users are reporting speed increases of up to 25% with a memory reduction of 35%.


Compatibility Issues


Most older PHP code should run without modification but there are a few gotchas to look out for:

You should also note that PHP 5.4.x will be the last edition to support Windows XP and Windows 2003.

PHP 5.4 isn’t quite as radical has 5.3, but there are enough new features to keep developers happy for a while. Let us know if you have any positive or negative experiences with the latest version.

Tuesday, 17 January 2012

Regular Expressions Cheat Sheet

The Regular Expressions cheat sheet is a one-page reference sheet. It is a guide to patterns in regular expressions, and is not specific to any single language.

regular-expressions-cheat-sheet

Wednesday, 14 December 2011

How to Install Apache, PHP, MySQL and PHPMyAdmin in Ubuntu 11.04

If you are a PHP based web developer, you need all the software running and configured properly. Here I am talking about installing them One by One in your Ubuntu Desktop. We are installing all the applications from terminal.

How to Open Terminal:
So, to fire up the terminal follow any of these steps:

  1. If you are running Unity Desktop, click on the Ubuntu Logo at top left corner and type Terminal in the search application bar. Then click on the terminal icon.

  2. If you are running GNome Desktop, click on Applications->Accessories->Terminal

  3. For shortcut, you can also press Ctrl+Alt+T at once, to open the terminal.


How to install Apache:

1. Make sure you have the internet connection. To install apache execute the following command in the terminal:










1


sudo apt-get install apache2




It takes some time to download and install apache. After the setup completes, type http://localhost/ in your browser window to make sure apache is installed and running properly. If you see the page with It Works!, the setup of apache2 completes successfully.

How to Install PHP:

1. To install PHP 5, type following commands in the terminal one by one:










1

2


sudo apt-get install php5

sudo apt-get install libapache2-mod-php5




The first line installs PHP5 in the computer. The second one provides the PHP5 module for the Apache 2 webserver. If second one is not installed, then Apache cannot parse PHP codes in a web page.

2. After installing PHP5 and PHP module for apache, restart the apache with following code:










1


sudo /etc/init.d/apache2 restart




3. While restarting the apache server, if you see a warning as “Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName”, then you can fix this by creating a file with the Server name. To do this type the following command in the terminal:










1


sudo gedit /etc/apache2/conf.d/fqdn




When the text editor opens, type “ServerName localhost” inside the file and click Save. Then close it. Now restart again with the above code and you will see that the warning message has gone.

4. Now, we have successfully installed php and apache web server. However, still we don’t know if PHP is successfully installed. To check this, create a file inside /var/www/ folder named test.php as:










1


sudo gedit /var/www/test.php




and write following code in it










1


<?php   phpinfo();  ?>




Save the file and type this in browser: http://localhost/test.php

If you see the various information about PHP and installed modules there, then we can confirm that Apache is parsing PHP codes. Hence the installation is successful up to this point.

How to Install MySQL:

1. To install MySQL Server in ubuntu, type following code in terminal window:










1


sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql




This will install latest mysql server and other necessary PHP modules for recognizing mysql functions from PHP code. While installing MySQL server, you may require to enter the password for MySQL root user.

How to Install PHPMyAdmin:

1. To Install PHPMyAdmin, type the following codes in the terminal:










1


sudo apt-get install phpmyadmin




While installing PHPMyAdmin, you may require to select the web server. In such case, tick the Apache2 Server and proceed with the installation. You may also require to input MySQL root user password during installation.

Once the installation completes, type this in your browser window to confirm the successful installation of PHPMyAdmin: http://localhost/phpmyadmin/index.php.

Now, you are finished. Your environment is setup and you can enjoy using all these applications. Next, you can install other applications that may be necessary such as Eclipse, GIMP etc.

Tuesday, 29 November 2011

The Right Way to Get a File Extension in PHP

I made a recent search on retrieving file extensions in PHP.

I found out that a lot have been re-inventing the wheel. They have been creating code for functionality that PHP already has. This is one example of re-inventing the wheel

function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}


Another example was this:

function file_extension($filename)
{
return end(explode(".", $filename));
}


PHP already has a function that does the same thing and more.

Welcome, pathinfo.

$file_path = pathinfo('/www/htdocs/your_image.jpg');
echo "$file_path ['dirname']\n";
echo "$file_path ['basename']\n";
echo "$file_path ['extension']\n";
echo "$file_path ['filename']\n"; // only in PHP 5.2+


// Output
/www/htdocs
your_image.jpg
jpg
your_image


A much easier way to use the constants:
[PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME]

PATHINFO_DIRNAME - the directory
PATHINFO_BASENAME - the file name
PATHINFO_EXTENSION - the extension
PATHINFO_FILENAME - the filename without the extension

echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);

// Output

jpg

Friday, 21 October 2011

Building your house

An elderly carpenter was ready to retire. He told his employer-contractor of his plans to leave the house-building business to live a more leisurely life with his wife and enjoy his extended family. He would miss the paycheck each week, but he wanted to retire. They could get by.



The contractor was sorry to see his good worker go & asked if he could build just one more house as a personal favor. The carpenter said yes, but over time it was easy to see that his heart was not in his work. He resorted to shoddy workmanship and used inferior materials. It was an unfortunate way to end a dedicated career.



When the carpenter finished his work, his employer came to inspect the house. Then he handed the front-door key to the carpenter and said, “This is your house…my gift to you.



“The carpenter was shocked!



What a shame! If he had only known he was building his own house, he would have done it all so differently.

So it is with us. We build our lives, a day at a time, often putting less than our best into the building. Then, with a shock, we realize we have to live in the house we have built. If we could do it over, we would do it much differently.



But, you cannot go back. You are the carpenter, and every day you hammer a nail, place a board, or erect a wall. Someone once said, “Life is a do-it-yourself project. “Your attitude, and the choices you make today, help build the “house” you will live in tomorrow. Therefore, build wisely!

2 Monks and a Pretty Lady

Once upon a time a big monk and a little monk were traveling together. They came to the bank of a river and found the bridge was damaged. They had to wade across the river.

There was a pretty lady who was stuck at the damaged bridge and couldn’t cross the river.

The big monk offered to carry her across the river on his back to which the lady accepted.

The little monk was shocked by the move of the big monk and was thinking “How can big brother carry a lady when we are supposed to avoid all intimacy with females?” But he kept quiet.

The big monk carried the lady across the river and the small monk followed unhappily. When they crossed the river, the big monk let the lady down and they parted ways with her.

All along the way for several miles, the little monk was very unhappy with the act of the big monk. He was making up all kinds of accusations about big monk in his head. This got him madder and madder. But he still kept quiet. And the big monk had no inclination to explain his situation.

Finally, at a rest point many hours later, the little monk could not stand it any further, he burst out angrily at the big monk. “How can you claim yourself a devout monk, when you seize the first opportunity to touch a female, especially when she is very pretty?”

All your teachings to me make you a big hypocrite.

The big monk looked surprised and said, “I had put down the pretty lady at the river bank many hours ago, how come you are still carrying her along?”

Moral: This very old Chinese Zen story reflects the thinking of many people today. We encounter many unpleasant things in our life, they irritate us and they make us angry. But like the little monk, we are not willing to let them go away. There is no point in remaining hurt by the unpleasant event after it is over. Learn to move on in life!

Monday, 3 October 2011

True Love is an Acceptance

It was a busy morning, about 8:30, when an elderly gentleman in his 80′s arrived to have stitches removed from his thumb. He said he was in a hurry as he had an appointment at 9:00 am.

I took his vital signs and had him take a seat, knowing it would be over an hour before someone would to able to see him. I saw him looking at his watch and decided, since I was not busy with another patient, I would evaluate his wound.

On examining,I saw that it was well healed, so I talked to one of the doctors, got the needed supplies to remove his stitches and redress his wound. While taking care of his wound, I asked him if he had another doctor’s appointment this morning, as he was in such a hurry. The gentleman told me no, that he needed to go to the nursing home to eat breakfast with his wife. I inquired as to her health.

He told me that she had been therefor a while and that she was a victim of Alzheimer’s Disease. As we talked, I asked if she would be upset if he was a bit late. He replied that she no longer knew who he was, that she had not recognized him in five years now. I was surprised, and asked him, “And you still go every morning, even though she doesn’t know who you are?”

He smiled as he patted my hand and said, “She doesn’t know me, but I still know who she is.”

I had to hold back tears as he left, I had goose bumps on my arm, and thought, ‘That is the kind of love I want in my life.’

Moral:

True love is neither physical, nor romantic.

True love is an acceptance of all that is,

has been, will be, and will not be.