Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

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.

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

 

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.

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.

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

Wednesday, 24 August 2011

Difference between require, require_once, include and include_once

All these functions require, require_once, include and include_once are used to include the files in the php page but there is slight difference between these functions.

Difference between require, require_once, include, include_once
Difference between require and include is that if the file you want to include is not found then include function give you warning and executes the remaining code in of php page where you write the include function. While require gives you fatal error if the file you want to include is not found and the remaining code of the php page will not execute.

If you have many functions in the php page then you may use require_once or include_once. There functions only includes the file only once in the php page. If you use include or require then may be you accidentally add two times include file so it is good to use require_once or include_once which will include your file only once in php page. Difference between require_once and include_onceis same as the difference between require and include.

Different types of errors in PHP

Here are three basic types of runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behavior.

2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Tuesday, 2 August 2011

PHP Magic Constants __LINE__ And __FILE__

Going through the php document I came across magic constant __LINE__.

-What this contants does?
returns the current Line No. of the file.

-How we can use this constant in development?
I started using this function for most of the debugging purposes. I simply append it with my echo messages. So when I need to go to code, I can directly go the same line.


I more magical constant I used along with __LINE__ of __FILE__. __FILE__ gives the name of the current script file name.

These two functions reduced 20% of my debugging time.

Example :

// Returns the line number of file
echo __LINE__;

Output : 21

// Returns the line number and full file name.....
echo __LINE__.of.__FILE__;

Otuput :

23 of /opt/lampp/htdocs/demos/demo.php

Sunday, 17 July 2011

5 useful url rewriting examples using .htaccess

1) Rewriting product.php?id=12 to product-12.html
It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
2) Rewriting product.php?id=12 to product/ipod-nano/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
3) Redirecting non www URL to www URL
If you type yahoo.com in browser it will be redirected to www.yahoo.com. If you want to do same with your website then put the following code to .htaccess file. What is benefit of this kind of redirection??
RewriteEngine On
RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]
4) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
5) Redirecting the domain to a new subfolder of inside public_html.
Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

Sunday, 29 May 2011

PHP Multilanguage Site Using Arrays

PHP Multilanguage

Here we can develop multilanguage site with the use of arrays

So, here we go:

First of all we need a configuration setting inside our script’s config.php file. For the sake of our example, we’ll add a manual variable change:

// language settings
$lng = 'en';

Next, our header file, dubbed header.php (could be head.php or top.php in your script) will contain these lines:

include('includes/config.php');
include('languages/'.$lng.'.php');

You now, obviously, have to create a languages directory and create a new file called en.php. This file will hold our array of words and expressions:

/*
@Package: My Multilanguage Script
@Language: English (English)
*/

$lang = array();

$lang['REGISTER'] = 'Register';
$lang['USERNAME'] = 'Username';
$lang['PASSWORD'] = 'Password';
$lang['LOGIN'] = 'Log in';
$lang['LOGOUT'] = 'Log out';
$lang['DASHBOARD'] = 'Dashboard';

Notice how I tried to keep the array index name as close to translation as possible. For example, you’ll have the string “Separate tags with commas” as $lang['SEPARATE_TAGS_COMMAS']. It’s easier after a couple of months when you’ll make changes.

Also, try to keep consistent naming of your language files, such as fr.php, de.php, ru.php, cn.php.

Now, call in you script . It will display “Register”, just as you translated it in your language file.

Sunday, 1 May 2011

Zend Framework Form(Zend_Form) tutorial

Here you can see how you can use Zend_Form component for creating html form easily, handling filters and errors messages and how to see how easily you can fetch data from the data source and present that in html form and let the visitors change/modify the existing data and save changes to the data source.
I am gona break this topic in three steps.
1. Creating Zend_Form
Although I’ve already discussed creation of Zend_Form in some of my articles but it will be better to discuss it here again.
Creating Zend form is simple is this.
class CustomForm extend Zend_Form
{
public function init()
{
}
}

defined a class by extending it from Zend_Form. This allow access to many of methods already defined in Zend_Form.
The only thing you need to do is to override init() method and create your own element such as input box, select statement, checkboxes, radio buttons and so on.
Defining your own elements don’t take much code. Have a look at the following code.
class CustomForm extend Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('process/form');

$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);

$this->addElement($username);
}
}

In the code above we have overridden init() method of Zend_Form, set the form request method and action and then defined input element called username. You can put as many elements in this form as you wish. The last statement is used to add element to the forms. To add several elements to the form at once, use addElements() passing array of elements as an argument. You will look an example in the next example.

My entire form look likes
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$id = $this->createElement('hidden','id');
$firstname = $this->createElement('text','firstname');
$firstname->setLabel('First Name:')
->setAttrib('size',50);
$lastname = $this->createElement('text','lastname');
$lastname->setLabel('Last Name:')
->setAttrib('size',50);
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);
$email = $this->createElement('text','email');
$email->setLabel('Email:')
->setAttrib('size',50);
$password = $this->createElement('password','password');
$password->setLabel('Password:')
->setAttrib('size',50);
$password2 = $this->createElement('password','password2');
$password2->setLabel('Confirm Password::')
->setAttrib('size',50);
$register = $this->createElement('submit','register');
$register->setLabel("Register")
->setIgnore(true);
$this->addElements(array(
$firstname,
$lastname,
$username,
$email,
$password,
$password2,
$id,
$register
));
}
}

Most of the functions are simple and self explanatory. The only method that I think I’d better explain here is setIgnore() method. The method setIgnore() has a very valuable usage. Well, if we see the entire form you will feel that we need all values when form is submitted. The only value we don’t need is the value of the submit button as this only used to submit the form. We are not interested in its value, so we call setIgnore() method passing Boolean value true.

2. As we have now created a form, next step is to create its object in controller and write code that will save data for us. Create a controller as
class UsersController extends Zend_Controller_Action
{
.....

public function addAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;

if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}
}

What we are doing here, is pretty simple. Create an object of Users model. Well I haven’t discussed Users model yet. I would discuss it for you soon. The next line creates an object of the form created earlier. Next we assign the form to the view template, in our case the template is add.phtml.
Next few lines are of much importance.
We check whether the request is first one or the post back. If form has been submitted, method $this->getRequest()->isPost() return ture. In this case we will need to take care of the data being submitted.
To handle the post back we get the data been posted back through form, check its validity, check if the password and confirm password matches, and insert the values in the “users” table using $users->insert(); statement.
If form is not valid, the code for inserting the data in the database will not be executed.
Now lets discuss “Users” model.
We have a table in our database called “users” containing different fields such as username, firstname, lastname etc.
We will need to create our model as
class Users extends Zend_Db_Table
{
protected $_name = "users";
}

That’s it, a simple model.
3. The third step in creating a full fledge form application in Zend Framework is presentation layer, called view/template.
In your scripts/users/ directory create add.phtml and put the following code in it
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>

The code above is self explanatory.
The above process only shows a form and submits data to the database. If you want to create edit form, you will need to make a bit of change in your controller.
Let’s create another action called editAction containing the following code.
class UsersController extends Zend_Controller_Action
{
.....

public function editAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$form = new CustomForm();

$id = $this->_getParam("id",1);
$select = $users->select()
->where("id = ?",$id);
$data = $users->fetchRow($select);
$form->populate($data->toArray());
if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
//Zend_Debug::dump($formData);exit;
$users->update($formData,"id = $id");
}
}
$this->view->form = $form;
}

}

You can clearly see that I’ve made only few lines of changes.
First I get the id of the user through $this->_getParam() method. I then create a select statement on the users table and then fetch a row. Once I get the data row, I populate the form using populate() method.
The only thing you will need now, is to create a view template in your scripts/users/ directory named edit.phtml and write the following code.
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>

Well I was thinking to explain everything in three steps, but I think it would be incomplete if I don’t explain how to show the data inserted in the database. For this reason I going to add 4th step.
4. Showing list of data
Create an action called indexAction in your controller with the following code.
class UsersController extends Zend_Controller_Action
{
public function indexAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
//Zend_Debug::dump($data->toArray());
}

.....

}

First we create an object of our mode. And then fetch the data using the fetchAll() method. The last statement assigns the fetched data to the view template.
Now create scripts/users/index.phtml and write the following code in it.
<h4>List of users</h4>
<h5><a href="add">Add new user</a></h5>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tboody>
<?php foreach ($this->data as $d) {?>
<tr>
<td><?=$d['firstname']?></td>
<td><?=$d['lastname']?></td>
<td><?=$d['username']?></td>
<td><?=$d['email']?></td>
<td><a href="edit/id/<?=$d['id']?>">Edit</a></td>
</tr>
<?php }?>
</tbody>
</table>

Here we are creating a table that shows the list of data.

Wednesday, 20 April 2011

PHP – Take advantage of language constructs



  • Fastest things in PHP are the language constructs.




  • They are highly optimized in the interpreter




  • Don’t require calling external libraries




  • Don’t call a function if there is a language construct. As an example, using a casting operator like (int) $total is much more efficient than using the function intval($foo)




  • Function calling generate considerably amount of overhead. Using a language construct avoid




  • isset() and unset() are both language constructs, even though they mostly act like functions. However calling them does not generate the function overhead.




Some common language constructs are:





  1. echo()




  2. empty()




  3. isset()




  4. unset()




  5. eval()




  6. exit()




  7. die()




  8. include()




  9. include_once()




  10. require()




  11. require_once()




  12. return



What is Web Service?

Web Services is a generic umbrella that describes how disparate systems can integrate with each other over the web.
Most major sites offer some form of web services:
– Amazon
FedEx
eBay
– PayPl
– del.icio.us

Why use Web Services?

  • Someone else has data you need

  • Easier than scraping pages also more reliable

  • Automate processes

  • Provide additional information to your clients


REST

REST Request

http://library.example.com/api.php?devkey=123&action=search&type=book&keyword=style

After the request, we will get the answer or response as an XML file. we can simple parse them using PHP’s SimpleXMLElement (SAX API) or DOM API to retrieve data

Zend Framework for developing Web Application using PHP

There are many frameworks for developing web applications using PHP. CodeIgniter, CakePHP, Symphony and more.. I’ve not much experience in all the frameworks. I’ve a good experience in using CodeIgniter and some small MVC frameworks.

Recently I am Working on Zend Framework .  I noticed Zend Framework is a nice framework to develop web application. Zend finally give special notice to develop a very good framework. And I hope very soon, Zend Framework will lead among all. I found this framework is very essential and powerful.

Recently,

What is Zend Framework?

  1. Zend Framework is a simple, straightforward, open-source software framework for PHP 5 designed to eliminate the tedious details of coding and let you focus on the big picture.

  2. It follows Model-View-Controller (MVC)

  3. ZF follows good coding-convention.


Documentation:
Documentation is really rich. Its not take much time to grasp a basic concept of this framework to develop application. Because there is quick start, api documentation, component based documentation. Overall I rate 10 out of 10 grade in documentation.

Goals of Zend Framework Components:


  1. Zend_Acl


    Zend_Acl provides lightweight and flexible access control list (ACL) functionality and privileges management.


  2. Zend_Auth


    Zend_Auth provides an API for authentication and includes concrete authentication adapters for common use case scenarios, as well as “Identity 2.0″ adapters such as OpenID and Microsoft InfoCard.


  3. Zend_Cache


    Zend_Cache provides a flexible approach toward caching data, including support for tagging, manipulating, iterating, and removing subsets.


  4. Zend_Config


    Zend_Config simplifies the use of configuration data for web applications.


  5. Zend_Controller and Zend_View


    These components provide the infrastructure for a Model-View-Controller (MVC) website.


  6. Zend_Date


    Zend_Date offers a detailed but simple API for manipulating dates and times.


  7. Zend_Db


    This is a lightweight database access layer, providing an interface to PDO and other database extensions in PHP. It includes adapters for each database driver, a query profiler, and an API to construct most SELECT statements.


  8. Zend_Db_Table


    The Zend_Db_Table component is a lightweight solution for object-oriented programming with databases.


  9. Zend_Feed


    This component provides a very simple way to work with live syndicated feeds.


  10. Zend_Filter and Zend_Validate


    These components encourage the development of secure websites by providing the basic tools necessary for input filtering and validation.


  11. Zend_Filter_Input


    This is a configurable solution for declaring and enforcing filtering and validation rules. This component serves as a “cage” for input data, so they are available to your application only after being validated.


  12. Zend_Form


    This component provides an object-oriented interface for building forms, complete with input filtering and rendering capabilities.


  13. Zend_Gdata (Zend Google Data Client)


    The Google Data APIs provide read/write access to such services hosted at google.com as Spreadsheets, Calendar, Blogger, and CodeSearch.


  14. Zend_Http_Client


    This component provides a client for the HTTP protocol, without requiring any PHP extensions. It drives our web services components.


  15. Zend_Json


    Easily convert PHP structures into JSON and vice-versa for use in AJAX-enabled applications.


  16. Zend_Layout


    Easily provide sitewide layouts for your MVC applications.


  17. Zend_Loader


    Load files, classes, and resources dynamically in your PHP application.


  18. Zend_Locale


    Zend_Locale is the Framework’s answer to the question, “How can the same application be used around the whole world?” This component is the foundation of Zend_Date, Zend_Translate, and others.


  19. Zend_Log


    Log data to the console, flat files, or a database. Its no-frills, simple, procedural API reduces the hassle of logging to one line of code and is perfect for cron jobs and error logs.


  20. Zend_Mail and Zend_Mime


    Almost every Internet application needs to send email. Zend_Mail, assisted by Zend_Mime, creates email messages and sends them.


  21. Zend_Measure


    Using Zend_Measure, you can convert measurements into different units of the same type. They can be added, subtracted, and compared against each other.


  22. Zend_Memory


    Zend_Memory offers an API for managing data in a limited memory mode. A PHP developer can create a Zend_Memory object to store and access large amounts of data, which would exceed the memory usage limits imposed by some PHP environments.


  23. Zend_Pdf


    Portable Document Format (PDF) from Adobe is the de facto standard for cross-platform rich documents. Now, PHP applications can create or read PDF documents on the fly, without the need to call utilities from the shell, depend on PHP extensions, or pay licensing fees. Zend_Pdf can even modify existing PDF documents.


  24. Zend_Registry


    The registry is a container for storing objects and values in the application space. By storing an object or value in the registry, the same object or value is always available throughout your application for the lifetime of the request. This mechanism is often an acceptable alternative to using global variables.


  25. Zend_Rest_Client and Zend_Rest_Server


    REST Web Services use service-specific XML formats. These ad-hoc standards mean that the manner for accessing a REST web service is different for each service. REST web services typically use URL parameters (GET data) or path information for requesting data and POST data for sending data.


  26. Zend_Search_Lucene


    The Apache Lucene engine is a powerful, feature-rich Java search engine that is flexible about document storage and supports many complex query types. Zend_Search_Lucene is a port of this engine written entirely in PHP 5.


  27. Zend_Service: Akismet, Amazon, Audioscrobbler, Delicious, Flickr, Nirvanix, Simpy, StrikeIron and Yahoo!


    Web services are important to the PHP developer creating the next generation of mashups and composite applications. The Zend Framework provides wrappers for service APIs from major providers to make it as simple as possible to use those web services from your PHP application.


  28. Zend_Session


    Zend_Session helps manage and preserve session data across multiple page requests by the same client.


  29. Zend_Translate


    The Zend_Translate component provides the Zend Framework with message translation functionality.


  30. Zend_Uri


    Zend_Uri is a component that aids in manipulating and validating Uniform Resource Identifiers (URIs). Zend_Uri exists primarily to service other components such as Zend_Http_Client but is also useful as a standalone utility.


  31. Zend_XmlRpc


    Zend_XmlRpc makes it easy to communicate with and create XML-RPC services from PHP.