Thursday, December 30, 2010
Alter query to set foreign key
Wednesday, December 22, 2010
Skype not seen in notification area
"Notification area is missing.
Right click on Top/Bottom panel > Add to Panel > Notification area > Add
Wednesday, December 8, 2010
Removing the index.php file in Codeigniter
example.com/index.php/news/article/my_article
You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
In the above example, any HTTP request other than those for index.php, images, and robots.txt is treated as a request for your index.php file.
Friday, November 12, 2010
Printscreen in ubuntu using laptop
"This is how a screenshot looks like:"
Wednesday, October 13, 2010
What is PDO?
Friday, October 8, 2010
Handling White Screen of Death in PHP
Work around for this problem is to add the following in beginning of PHP code:
ini_set(“session.save_handler”, “files”);
The “save_handler” is just defined in php.ini with value “files”, redefining the save_handler before calling session_start() solves the problem.
configure Tata Indicom Photon+
* Connect the USB device
* Open terminal (Application > accessories> Terminal)
* install wvdial using the command sudo apt-get install wvdial
* After installation again type sudo gedit /etc/wvdial.conf on terminal , which will open the configuration file.
* Enter the following details in configuration file
[Dialer Defaults]
Modem = /dev/ttyUSB0
Init1 = ATZ
Phone = #777
Username = xxxxxxxxxx (your tata photon number)
Password = xxxxxxxxxx (your tata photon number)
New PPPD = yes
Stupid Mode = 1
* Now close the configuration file and type sudo wvdial. You should see a long list of arbit codes followed by some IPs. If you see the IPs then you are connected! Don’t close the terminal, or else you’ll get disconnected. To manually disconnect, just go to the terminal and press Ctrl+C.
Tuesday, September 14, 2010
eAccelerator
eAccelerator was born in December 2004 as a fork of the Turck MMCache project. Turck MMCache was created by Dmitry Stogov and much of the eAccelerator code is still based on his work.
eAccelerator stores compiled PHP scripts in shared memory and executes code directly from it. It creates locks only for a short time, while searching for a compiled PHP script in the cache, so one script can be executed simultaneously by several engines. Files that can't fit in shared memory are cached on disk only.
The latest release, 0.9.6.1, features support for PHP 5.3 and also works with PHP 5.1 and 5.2. The previous 0.9.5 branch supports PHP 4 and all PHP 5 releases including 5.2. In older releases, the encoder will only work with PHP versions from the 4.x.x branch.
Wednesday, August 25, 2010
PHP accelerator
List of PHP accelerators
Alternative PHP Cache
Alternative PHP Cache (APC) is a free, open source framework that optimizes PHP intermediate code and caches data and compiled code from the PHP bytecode compiler in shared memory. APC is quickly becoming the de-facto standard PHP caching mechanism as it will be included built-in to the core of PHP starting with PHP 6.
eAccelerator
eAccelerator was born in December 2004 as a fork of the Turck MMCache project. Turck MMCache was created by Dmitry Stogov and much of the eAccelerator code is still based on his work. eAccelerator also contained a PHP encoder and loader, but the development staff discontinued the encoder and removed this feature after December 2006.
XCache
XCache is a fast, stable PHP opcode cacher that has been tested and is now running on production servers under high load. It is tested on linux and supported under Windows, for thread-safe and non-thread-safe versions of PHP. This relatively new opcode caching software has been developed by mOo, one of developers of Lighttpd, to overcome some of the limitations of the existing solutions at that time; such as being able to use it with new PHP versions as they arrive.
Nusphere PhpExpress
PhpExpress is NuSphere's free PHP accelerator that speeds up the execution of regular PHP files and provides support for loading of PHP files encoded with NuSphere's PHP encoder Nu-Coder. PhpExpress loads both encoded and not encoded PHP files directly into the PHP engine, saving time and boosting performance of the PHP interpreter. PhpExpress also caches the files and thus provides a speed boost even for non-encoded files.
Zend Accelerator
Zend Accelerator is a component of Zend Server and Zend Server Community Edition. Accelerator speeds up PHP execution by opcode caching and optimization. It stores precompiled script bytecode in shared memory. This eliminates the stages of reading code from the disk and compiling it on future access. For further performance improvements, the stored bytecode is optimized for faster execution.
Zend Platform
Zend Platform (formerly Zend Cache and then Zend Accelerator) is a commercial Web Application Server product. It has a complete set of performance capabilities that includes more than a simple PHP accelerator. Features include code caching/acceleration, data caching, content (html output) caching, download optimization and off-line (asynchronous) processing capabilities that can result in significant performance improvements for most PHP applications. It also includes detailed PHP monitoring and root cause analysis support to help in tuning and debugging, session fail-over support for HA (High Availability) needs and other integration capabilities including Java integration.
Windows Cache Extension for PHP
A free, open source (New BSD License), PHP-accelerator developed by Microsoft for PHP under Windows. The extension includes PHP opcode cache, file cache, resolve file path cache, object/session cache, file change notifications and lock/unlock API's. Combination of all these caches results in significant performance improvements for PHP applications hosted on Windows. The extension is primarily used with Internet Information Services and non-thread-safe build of PHP via FastCGI protocol.
Zend Optimizer
Despite the name, Zend Optimizer is not a code accelerator. Rather, is a free, closed source PHP extension by Zend that enables PHP to run files encoded by Zend Guard.
FIND_IN_SET AND IN()
TABLE
(ID) (FLD) COMMA DELIMITED FIELD
1 42, 148
2 234, 25423,148
It wont be able to retrieve any records at all coz it will only check for the exact values inside that quote ’33, 148′. Even I put something like SELECT * FROM TABLE WHERE FLD IN(’148′) still won’t have any result coz I don’t have a record that’s only ’148′
So instead use something like SELECT * FROM TABLE WHERE FIND_IN_SET( ’148′, FLD) and these 2 rows will be retrieved. So I guess IN() is not a good way to retrieve fields with comma delimited values unless it’s the exact string. But if ur sql is like this SELECT * FROM TABLE WHERE ID IN(1,2), it won’t be a prob at all.
Btw. I tried the issue below and it’s not a prob anymore. I only used the sql like SELECT * FROM TABLE WHERE FIND_IN_SET( ’1487′, FLD) and it only retrieved 1487 .
FIND_IN_SET() return results containing a certain number in a comma-delimmeted
list in a TEXT field. Sometimes it returns false positives,
for example:mysql> SELECT pssmID_list FROM bccs WHERE FIND_IN_SET(1487, pssmID_list);
+-------------+
| pssmID_list |
+-------------+
| 7771,148 |
| 1487 |
+-------------+
2 rows in set (0.01 sec)
How to repeat:
This apparently happens when the last element of the list is a partial match for the query
string. It is difficult to repeat, since it only happens in some of these cases. If you
use static strings in the query, rather than querying the table, it won't happen. I
suspect it's caused by FIND_IN_SET going past the end of a text string and into the next
record.
To repeat, I recomend writing a script to check for excess returns. Create a large table
of lists of numbers, in which each number should appear in only one row. Then cound the
responses to find_in_set for each number. If you come back with more than 1, the error
has occured.
The lack of repeatability is the reason I marked this serious. For me, it caused problems
in 11 searches out 6000. But in some applications, this could be serious and hard to
notice.
Suggested fix:
As a workaround, you can append a comma to the delimited list:
mysql> SELECT pssmID_list FROM bccs WHERE FIND_IN_SET('1487', CONCAT(pssmID_list, ','));
+-------------+
| pssmID_list |
+-------------+
| 1487 |
+-------------+
1 row in set (0.00 sec)
The SET Type
For example, a column specified as SET('one', 'two') NOT NULL can have any of these values:
''
'one'
'two'
'one,two'
A SET can have a maximum of 64 different members.
Duplicate values in the definition cause a warning, or an error if strict SQL mode is enabled.
Trailing spaces are automatically deleted from SET member values in the table definition when a table is created.
When retrieved, values stored in a SET column are displayed using the lettercase that was used in the column definition. Note that SET columns can be assigned a character set and collation. For binary or case-sensitive collations, lettercase is taken into account when assigning values to the column.
MySQL stores SET values numerically, with the low-order bit of the stored value corresponding to the first set member. If you retrieve a SET value in a numeric context, the value retrieved has bits set corresponding to the set members that make up the column value
One of the least commonly used of the MySQL datatypes has to be the SET datatype. The SET datatype is a string type, but is often referred to as a complex type due to the increased complexity involved in implementing them. A SET datatype can hold any number of strings from a predefined list of strings specified during table creation. The SET datatype is similar to the ENUM datatype in that they both work with predefined sets of strings, but where the ENUM datatype restricts you to a single member of the set of predefined strings, the SET datatype allows you to store any of the values together, from none to all of them.
Storage
The MySQL SET datatype is stored as an integer value within the MySQL tables, and occupies from one to eight bytes, depending on the number of elements available.
Storage Required for MySQL SET Datatype Number of Elements Number of Bytes
1 - 8 1
9 - 16 2
17 - 24 3
25 - 32 4
33 - 64 8
The SET elements are stored in the MySQL table as a bitmap: each element is represented by a single bit. To demonstrate this, lets look at the following sample table, which will be the basis for the rest of this tutorial. (NOTE: In the examples that follow, there are never whitespaces between elements and their comma seperators. Also note that only during the definition of a set are the elements individually wrapped in single quotes, otherwise the set as a whole gets only one set of quotes. Please do likewise.)
CREATE TABLE set_test(
rowid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
myset SET('Travel','Sports','Dancing','Fine Dining')
);
Each element in our set is assigned a single bit in our bitmap (note that in spite of there only being 4 elements our set will still occupy 1 byte). If our row incorporates a given element, the associated bit will be a one. Because of this storage approach, each element also has an associated decimal value.
Element SET Value Decimal Value
Travel 00000001 1
Sports 00000010 2
Dancing 00000100 4
Fine Dining 00001000 8
Multiple elements can be represented by adding their decimal values (for example, a person's interests in Travel and Fine Dining can be represented as 00001001 or the decimal value of 8 + 1 = 9).
Why You Shouldn't Use SET
The MySQL SET datatype is not commonly used for a few reasons; First, using the MySQL SET datatype limits you to 64 elements. While you could get around this by using multiple SETs, this still represents a loss of versatility. Second, you cannot include commas in your set elements, as the comma is an element separator. Third, using a set means your data is not normalized. In our above example, we are tracking a person's interests for a hypothetical dating site. In a normalized schema, there should be three tables: one for the person, one for all possible interests, and one that links a person to their particular interests. Fourth, an INDEX on a set datatype is going to refer to the set as a whole and will not be used for searching individual elements (this may or may not be a problem for certain applications).
So why do we use the MySQL SET datatype? Well there are a few reasons; The MySQL SET datatype allows us to handle multiple values with a lot less trouble than if we had our table fully normalized. Our schema is simplified because we only need one column instead of three tables to store our list of interests. The MySQL SET datatype allows us to compare multiple values without using complex JOIN operations. We can manipulate the set with binary functions to do complex comparisons by comparing bit values on a single column instead of comparing multiple rows of multiple tables.
You may find that the MySQL SET datatype is something that you never need to use. If you find that it's advantages outweigh the disadvantages, read on to discover how to use it.
INSERTing SET Data
There are two ways to INSERT data into MySQL SET columns: by decimal value or by using strings. To INSERT the combination of Travel and Sports into our sample tables, we can use the following:
INSERT INTO set_test(myset) VALUES(3);
INSERT INTO set_test(myset) VALUES('Travel,Sports');
Because the decimal value of Travel is 1 and the decimal value of Sports is 2, the combination of the two can be inserted at the sum of the decimal values, or 3. Another example of matching INSERT statements:
INSERT INTO set_test(myset) VALUES(7);
INSERT INTO set_test(myset) VALUES('Travel,Sports,Dancing');
UPDATEing SET Data
There are three kinds of UPDATE that we need to deal with: complete replacement of the SET data, addition of set members, and removal of set members. We will deal with these in the order listed above.
To completely replace the data in a SET, we simply specify the new values:
UPDATE set_test SET myset = 'Travel,Dining' WHERE rowid = 1;
UPDATE set_test SET myset = 2 WHERE rowid = 2;
To add an element to an existing SET we use the CONCAT() function to add the new element to our comma separated list. To work with decimal values, we can use the bitwise OR operator |.
UPDATE set_test SET myset = CONCAT(myset,",Travel")
WHERE rowid = 3;
UPDATE set_test SET myset = myset | 1 WHERE rowid = 3;
We can also use the CONCAT_WS() function, which handles list separators for us:
UPDATE set_test SET myset = CONCAT_WS(',',myset,'Dancing')
WHERE rowid = 6;
To remove set elements from an existing set, we use the REPLACE function to remove the element. If using decimal values, we use a combination of the bitwise AND operator & with the bitwise NOT operator ~.
UPDATE set_test SET myset = REPLACE(myset,'Dancing','')
WHERE rowid = 6;
UPDATE set_test SET myset = myset & ~2 WHERE rowid = 6;
With the bitwise operators we can add and remove multiple items at once by using the sum of the decimal values of the elements we wish to remove.
SELECTing SET Data
There are several ways we can select data from a SET column, but they come down to two distinct types: SELECT queries that have a specific WHERE clause, and SELECT queries that have pattern matching in the WHERE clause.
Before discussing the different WHERE clauses, it would probably be good to cover what the data will look like as it is returned from the SELECT query. If the column is merely SELECTed, you will get a comma separated list of the elements involved in your SET. If you add a +0 to the column name, you will see the integer values in the columns.
mysql> SELECT rowid, myset, myset+0
-> FROM set_test;
+-------+-----------------------+---------+
| rowid | myset | myset+0 |
+-------+-----------------------+---------+
| 1 | Sports | 2 |
| 2 | Travel,Sports | 3 |
| 3 | Travel,Dancing | 5 |
| 4 | Travel,Sports | 3 |
| 5 | Travel,Sports,Dancing | 7 |
| 6 | Travel,Dancing | 5 |
| 7 | Sports | 2 |
| 8 | Travel,Dancing | 5 |
+-------+-----------------------+---------+
8 rows in set (0.00 sec)
All of the SELECTs we will be doing will be based on one of these two values.
Let's look at WHERE clauses with specific values. When searching against a specific set of values, we can specify them in our where clause:
SELECT * FROM set_test WHERE myset = 'Travel,Sports';
SELECT * FROM set_test WHERE myset = 3;
To check for items with a specific element, we can use a couple of methods:
SELECT * FROM set_test WHERE myset LIKE '%Sports%';
SELECT * FROM set_test WHERE myset & 2;
It should be noted that the bitwise AND exhibits an OR-like behavior when used with combinations of values. Take for example the following query, which involves Travel (1) and Sports (2).
SELECT * FROM set_test WHERE myset & 3;
This query actually returns rows that contain Travel OR Sports, and not just rows that contain both. For rows with have both Travel AND Sports, we need to also check the result of our bitwise AND (&) operation against the value we are performing the bitwise AND (&) against, or use an AND clause in our query:
SELECT * FROM set_test WHERE myset & 3 = 3;
SELECT * FROM set_test WHERE myset & 1 AND myset & 2;
This returns all rows that contain Travel AND contain Sports, and also returns the combination of the two. The & 3 = 3 syntax is preferable as it does not require an increasing number of AND clauses.
We can also use multiple wildcard queries like the following:
SELECT * FROM set_test WHERE myset LIKE '%Travel%Sports%';
It should be noted that the elements must be in order (that is, in the order they are listed in the initial table creation) as order is important in the multiple wildcard queries. For example '%Travel%Sports%' will return rows, but '%Sports%Travel%' will not.
Another way to retrieve rows is to use the FIND_IN_SET() function as follows:
SELECT * FROM set_test WHERE FIND_IN_SET('Sports',myset) > 0;
FIND_IN_SET() will return 0 if there is no match and a number greater than zero if there is a match. NULL will be returned if either the set or the search string is NULL.
Clever Bit Tricks
We can take advantage of the bitmap approach to storing SET data to rank our users in order of matching interests to help our users find people who best match their own interests, thus allowing you to find users who also like Sports, Travel, and Dancing (or at least like some of the things you do).
Here's how it works: each of our users has their interests stored in the SET datatype defined above. We want to rank their fellow users by how well their interests overlap. First let's look at the interests in binary form using the BIN() function (we use LPAD() to add leading zeroes):
mysql> SELECT rowid, myset, LPAD(BIN(myset+0),4,'0') AS binset
-> FROM set_test;
+-------+-----------------------------------+--------------+
| rowid | myset | binset |
+-------+-----------------------------------+--------------+
| 1 | Travel,Sports,Dancing | 0111 |
| 2 | Travel,Dancing | 0101 |
| 3 | Travel | 0001 |
| 4 | Dancing | 0100 |
| 5 | Dancing | 0100 |
| 6 | Sports,Dancing | 0110 |
| 7 | Travel,Sports,Dancing,Fine Dining | 1111 |
| 8 | Travel,Fine Dining | 1001 |
| 9 | Sports,Fine Dining | 1010 |
| 10 | Travel,Dancing,Fine Dining | 1101 |
+-------+-----------------------------------+--------------+
10 rows in set (0.00 sec)
What we want to do is order our table by the number of matching interests. For our example, we will order our users by how well they match with user 8, who is interested in Travel, Dancing, and Fine Dining.
mysql> SELECT A.rowid, A.myset, BIN(A.myset+0 & B.myset+0)
-> FROM set_test AS A, set_test AS B
-> WHERE b.rowid = 8
-> AND A.rowid != 8
-> ORDER BY BIT_COUNT(A.myset & B.myset) DESC;
+-------+-----------------------------------+---------+
| rowid | myset | matches |
+-------+-----------------------------------+---------+
| 7 | Travel,Sports,Dancing,Fine Dining | 2 |
| 10 | Travel,Dancing,Fine Dining | 2 |
| 1 | Travel,Sports,Dancing | 1 |
| 2 | Travel,Dancing | 1 |
| 3 | Travel | 1 |
| 9 | Sports,Fine Dining | 1 |
| 4 | Dancing | 0 |
| 5 | Dancing | 0 |
| 6 | Sports,Dancing | 0 |
+-------+-----------------------------------+---------+
9 rows in set (0.00 sec)
This results in our users being organized by how well they match with user 8. The BIT_COUNT() function in the above example will return the number of set bits in the expression passed to it. Our first two matches (users 7 and 10) have two overlapping interests, the next four have one match, and the remaining three users have no overlapping interests (they could be trimmed out by adding the following to the WHERE clause:
AND BIT_COUNT(A.myset & B.myset)
Because of the functions being performed on the rows, this type of query cannot benefit from an index. This means that the entire table will have to be scanned to find matches to user 8. However, as this is a bitwise operation, it should be quite efficient in spite of the full table scan (I was able to perform this operation on a randomly generated table of 500,000 rows and have 250,000 rows returned in 1.89 seconds on my 1.6 Ghz PC).
By comparison, performing this operation on the normalized three table schema I described above would require a three table JOIN with N AND clauses in the WHERE section of the query, one for every interest user 8 possessed.
Retrieving Set Members
To retrieve a list of the set members, use the DESCRIBE syntax as follows:
mysql> DESCRIBE set_test myset;
+-------+-------------------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------------------------------------+------+-----+---------+-------+
| myset | set('Travel','Sports','Dancing','Dining') | YES | | NULL | |
+-------+-------------------------------------------+------+-----+---------+-------+
1 row in set (0.00 sec)
If working programmically, you need to use the second column and strip the 'set(' and ')' to have a comma separated list, which most programming languages can break into an array automatically
Friday, July 30, 2010
Clear Soap Cache PHP
.htaccess for force download microsoft technologies using php
i.e.
a href="........./files/somefile.pdf">Download Pdf
for PHP
?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
?
You will get a pop-up box asking whether you want to save the file or open it normally.
Now you want to download it so open .htaccess file and write there some lines according yo your requirement mentioning extension of files which you want to download directly.
Place the following code into your .htaccess file.
AddType application/octet-stream .pdf
AddType application/octet-stream .doc
AddType application/octet-stream .csv
This script will force download all files having extensions .pdf, .doc or .csv.
.htaccess files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
There is .htaccess file present by default at the root directory of your server. If not, you can always create a file named as .htaccess, code it and upload it in the desired directory or at the root level of your website.
In several web servers (most commonly Apache), .htaccess (hypertext access) is the default name of directory-level configuration files. A .htaccess file is placed in a particular directory, and the directives in the .htaccess file apply to that directory, and all subdirectories thereof. It provides the ability to customize configuration for requests to the particular directory. The file name starts with a dot because dot-files are by convention hidden files on Unix-like operating systems.
AddType application/vnd.ms-word.document.macroEnabled.12 .docm for docx in .htaccess in ubuntu
Monday, July 19, 2010
Auto Refresh
Meta HTTP-EQUIV="REFRESH"
html>
head>
meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
meta http-equiv="refresh" content="0;
url=
title>Refresh Page
/head>
body>
p>test
p>##
p>If you are not re-directed to the page automatically,
please use the link above.
/body>
/html>
meta http-equiv="refresh" content="0;
url=http://www.google.com" />
Content="0"?... What is that?
The "0" is the number of seconds before the page will automatically refresh! So, it could be anything.
And don't forget to add a link further down the page so that the next time a Search Engine Spider crawls around in those old pages, their index will be updated!
Refresh / re-direct using PHP
We can use PHP's header() function
We can re-direct or refresh our web pages by simply doing either of the following in our PHP scripts
or codes:
Method I: using header('location...')
You probably know this ol' favourite...
php:
// refresh / re-direct without delay
// ---------------------------------
header( 'location:http://www.desilva.biz/webdsn/' );
?>
Method II: using header('refresh...')
php:
// refresh / redirect to an internal web page
// ------------------------------------------
header( 'refresh: 5; url=/webdsn/' );
echo '
You will be re-directed in 5 seconds...
';// refresh / redirect to an internal web page
// ------------------------------------------
header( 'refresh: 3; url=/' ); # redirects to our homepage
echo '
You will be re-directed in 3 seconds...
';// refresh / redirect to an external web page
// ------------------------------------------
header( 'refresh: 0; url=http://www.example.net' );
echo '
You won\'t know what hit you!
';?>
Tuesday, July 13, 2010
How to reset the all users' settings in Gnome?
Monday, July 12, 2010
Mysql Remote database connect from terminal
user>mysql --host=hostname --user=root --password
To change the password from the mysql command prompt is
mysql>SET PASSWORD FOR root@localhost = OLD_PASSWORD('mypassword');
Thursday, July 8, 2010
Using Memcache
Basically, what this means is that memcached is a daemon running on a server which allows you to save and retrieve variables in the server memory. This is primarily used to ease database load on websites and applications. The logic for doing something like this is…
- Before running a query, check if the result is available in memcache.
- If the result is in memcache, return the cached result.
- If not, run the query on the database, and store the result in memcache.
To install memcached, simply run the following command:
sudo apt-get install memcached
Once it’s installed, edit /etc/memcached.conf and change the line beginning ‘-m’ which is the amount of memory (in megabytes) to allocate to the server. You can also change the IP address that the server listens on in the line beginning ‘-l’.
Now restart the daemon by running
/etc/init.d/memcached restart
Now you have memcache set up and running on your server. A great feature of memcached is that you can easily cluster servers. If you want to do this, simply install memcache on your other servers before continuing.
At this point, I’d recommend downloading memcache.php which is a php script showing you a lot of useful information about your memcached servers. Once downloaded, put it in a web facing directory on your server, and modify the $MEMCACHE_SERVERS array with your server addresses.
Using memcache in php scripts is very easy. There are either procedural, or object oriented functions already available. Here is an example of a script which will store a simple variable and then retrieve it and display it.
$memcache = new Memcache;
$memcache->addServer(’10.2.0.245′, 11211) or die (“Could not connect”);
$memcache->addServer(’10.2.0.249′, 11211) or die (“Could not connect”);
$memcache->set(‘mytestvariable’, “this is the data in my test variable”, false, 60) or die (“Unable to save the data to the server”);
echo “Data has been stored in the cache
”;
$result = $memcache->get(‘mytestvariable’);
echo “Retrieved data from the server:
”;
var_dump($result);
?>
Obviously if you only have one server then only use one addServer line.
The script above will store the test variable in the cache for 60 seconds. If you drop the timeout down to something like 1 second, and then sleep for 3 seconds before attempting to get the data, you will find that the data has expired and nothing will be returned.
It’s also useful to know that you can store anything which can be serialized in memcache. This means it’s safe to store things like arrays in the cache without having to ‘flatten’ the data beforehand.
Obviously how and where you implement a cache is entirely dependant on how your system works. If you have a lot of intense database usage then you will find that even caching with a short timeout will vastly reduce the amount of database queries. You should find that memcache is considerably faster than normal database access, and even faster than the mysql query cache. You also have total control over what data is cached, and how long it is cached for before your queries fall back to checking a database.
Memcache
Introducing memcached. Memcached is a cache server originally developed by the LiveJournal people and now being used by sites like Digg, Facebook, Slashdot and Wikipedia.
How it works
* Memcached consists of a server and a client part.. The server is a standalone program that runs on your servers and the client is in this case a PHP extension.
* If you have 3 webservers which all run Memcached, all webservers connect to all 3 memcached servers. The 3 memcache servers are all in the same 'pool'.
* The cache servers all only contain part of the cache. Meaning, the cache is not replicated between the memcached servers.
* To find the server where the cache is stored (or should be stored) a so-called hashing algorithm is used. This way the 'right' server is always picked.
* Every memcached server has a memory limit. It will never consume more memory than the limit. If the limit is exceeded, older cache is automatically thrown out (if the TTL is exceed or not).
* This means it cannot be used as a place to simply store data.. The database does that part. Don't confuse the purpose of the two!
* Memcached runs the fastest (like many other applications) on a Linux 2.6 kernel.
* By default, memcached is completely open.. Be sure to have a firewall in place to lock out outside ip's, because this can be a huge security risk.
Install Memchache In Ubuntu
sudo apt-get install php5-dev
sudo apt-get install php-pear
sudo apt-get install zlib1g-dev
sudo apt-get install memcached
sudo pecl install Memcache
Don't forget to enable the extension in /etc/php5/apache2/php.ini by adding the line extension=memcache.so and restarting the webserver.
Tuesday, June 8, 2010
Save JPEG file and force download
//get our width and height in integers from the post values
$width = (int)$_POST['width'];
$height = (int)$_POST['height'];
$data = $_POST['data']; //data of the image
//begin our image
$temp_img = imagecreatetruecolor($width, $height);
//fill in white space
imagefill($temp_img, 0, 0, 0xFFFFFF);
$rows = 0;
$cols = 0;
$data_row = explode("|", $data);
//replace data with color values
for($rows = 0; $rows < $height; $rows++){
$c_row = explode(",", $data_row[$rows]);
for($cols = 0; $cols < $width; $cols++){
$value = $c_row[$cols];
if($value != ""){
$hex = $value;
while(strlen($hex) < 6){
$hex = "0" . $hex;
}
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
$test = imagecolorallocate($temp_img, $r, $g, $b);
imagesetpixel($temp_img, $cols, $rows, $test);
}
}
}
//output to jpg and prompt download
header("Content-Type: image/jpeg");
header("Content-Disposition: attachment; filename=image_save.jpg");
imagejpeg($temp_img, "", 100);
Sent Post data to Curl request
define('POSTVARS', 'secretPassCode=bsjenl392kmsnbu2039jnnsh33&MemID=195093&LastName=Menndez'); // POST VARIABLES TO BE SENT
$ch = curl_init(POSTURL);
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,POSTVARS);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_HEADER ,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
$Rec_Data = curl_exec($ch);
print_r($Rec_Data);
Monday, May 24, 2010
PHP localhost mail function
In terminal, run the following command one by one:
sudo pear install mail
sudo pear install Net_SMTP
sudo pear Auth_SASL
sudo pear install mail_mime
After installing the pear packages, you need to install and configure postfix, first, run the following command to install postfix:
sudo apt-get install postfix
after installation, a configuration window will be displayed, you need to configure it:
Step 1: Choose Internet Site
Step 2: Enter localhost at the input area
For the rest of the steps, just follow the default settings. After complete the configuration, it’s time to test the PHP script. Create a PHP file called sendmail.php at your localhost, and copy and paste the code below into it (remember to change the email addresses to yours)
include('Mail.php');
include('Mail/mime.php');
// Constructing the email
$sender = "shi
$recipient = "Leigh
$subject = "Test Email";
$text = 'This is a text message.';
$html = '
This is a html message
';$crlf = "\n";
$headers = array(
'From' => $sender,
'Return-Path' => $sender,
'Subject' => $subject
);
// Creating the Mime message
$mime = new Mail_mime($crlf);
// Setting the body of the email
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
// Set body and headers ready for base mail class
$body = $mime->get();
$headers = $mime->headers($headers);
// SMTP params
$smtp_params["host"] = "localhost"; // SMTP host
$smtp_params["port"] = "25"; // SMTP Port (usually 25)
// Sending the email using smtp
$mail =& Mail::factory("smtp", $smtp_params);
$result = $mail->send($recipient, $headers, $body);
if($result == 1)
{
echo("Your message has been sent!");
}
else
{
echo("Your message was not sent: " . $result);
}
?>
Thursday, May 20, 2010
Ioncube
In today's world, copyright is a very important issue, especially when talking about websites. By default, when creating a website, your code is publicly available for everyone - all they have to do is use the “View Source” option to check the code with their web browser, or download your files and review the product of your hard work for free. To prevent this, a lot of companies have created special tools, which can obfuscate your code and make it impossible for anyone but you to view it, not affecting your website work at all. They are called Encoders, and one of the most popular combinations is the ionCube Loader and Encoder.
ionCube Loader is a software tool, with the help of which you can run files encoded with the ionCube PHP Encoder. It protects the PHP 4 and PHP 5 source code, as well as other files in your website, and prevents them from stealth and unauthorized modification. What is even more, the encoded files run smoothly, showing excellent performance on any web server having ionCube support.
ionCube Encoder
When using encrypted web pages, there are always two tools that you need to use. The first one is the decoder, which is server based and will decode the encrypted web pages, allowing the user to actually see them online. The second one is the actual Encoder, which is software you need to have on your machine in order to encode your files. The ionCube Encoder will do that for you, protecting your files from unauthorized changes and modifications.
How to check if ionCube is installed on the server ?
There is an easy way to check if the ionCube Loader is already present on your web server - by using a phpinfo.php file. This is a simple file, which makes usage of the "phpinfo()" function. When accessed online, this function will show you complete information about the PHP settings on the server, alongside with the installed modules.
Wednesday, April 14, 2010
Install ioncube in ubuntu
ionCube protects software written using the PHP programming language from being viewed, changed, and run on unlicensed computers.
1. Download ionCube loaders
sudo wget http://downloads.ioncube.com/loader_downloads/ioncube_loaders_lin_x86.tar.gz
2. Extract
sudo tar zxvf ioncube_loaders_lin_x86.tar.gz
3. Move to a permanent location
sudo mv ioncube /usr/local/
4. Add reference to your php.ini file (sudo pico /etc/php5/apache2/php.ini)
zend_extension = /usr/local/ioncube/ioncube_loader_lin_5.2.so
There are a few versions of the loader in the tar archive. Use the one that matches your PHP version.
5. Restart apache
sudo /etc/init.d/apache2 restart6. check installation using following command:
php -v
you should see following output:
PHP 5.1.6 (cli) (built: Apr 7 2009 08:00:04)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
with the ionCube PHP Loader v3.1.34, Copyright (c) 2002-2009, by ionCube Ltd.
Monday, April 12, 2010
How do I open rar archive files under Linux / UNIX operating systems
Under Debian Linux, you need to type apt-get as follows to install unrar program:
# apt-get install unrar
Thursday, April 8, 2010
Full text search
Full-text searching is performed using MATCH() ... AGAINST syntax. MATCH() takes a comma-separated list that names the columns to be searched. AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a literal string, not a variable or a column name. There are three types of full-text searches:
* A boolean search interprets the search string using the rules of a special query language. The string contains the words to search for. It can also contain operators that specify requirements such that a word must be present or absent in matching rows, or that it should be weighted higher or lower than usual. Common words such as “some” or “then” are stopwords and do not match if present in the search string. The IN BOOLEAN MODE modifier specifies a boolean search.
* A natural language search interprets the search string as a phrase in natural human language (a phrase in free text). There are no special operators. The stopword list applies. In addition, words that are present in 50% or more of the rows are considered common and do not match. Full-text searches are natural language searches if no modifier is given.
* A query expansion search is a modification of a natural language search. The search string is used to perform a natural language search. Then words from the most relevant rows returned by the search are added to the search string and the search is done again. The query returns the rows from the second search. The WITH QUERY EXPANSION modifier specifies a query expansion search.
Object Serialization
serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.
In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.
If an application is using sessions and uses session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This means that these objects can show up on any of the application's pages once they become part of the session. However, session_register() is deprecated as of PHP 5.3.0, and removed as of PHP 6.0.0. Reliance on this function is not recommended.
It is strongly recommended that if an application serializes objects, for use later in the application, that the application include the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.
Comparing Objects
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
Patterns
Factory
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.
Example #1 Parameterized Factory Method
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception('Driver not found');
}
}
}
?>
Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:
// Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>
Singleton
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Example #2 Singleton Function
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark()
{
echo 'Woof!';
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
This allows a single instance of the Example class to be retrieved.
// This would fail because the constructor is private
$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();
// This will issue an E_USER_ERROR.
$test_clone = clone $test;
?>
Oops concept in PHP5
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Static Keyword
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
Scope Resolution Operator (::)
The Scope Resolution Operator or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
Magic Methods
The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
Late Static Bindings
PHP5 implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will no longer be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
Class Abstraction
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Object Interfaces
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
implements
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Autoloading Classes
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. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Visibility
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
Property Visibility
Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public.
Object Cloning
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
$copy_of_object = clone $object;
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.
Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Wednesday, April 7, 2010
Symmetrical Session and Sticky Session
Distributed sessions are intrinsically more complicated than single-server sessions. Single-server session can be implemented as a simple memory-based Hashtable. Distributed sessions must communicate between machines to ensure the session state remains consistent.
Load balancing with multiple machines either uses sticky sessions or symmetrical sessions. Sticky sessions put more intelligence on the load balancer, and symmetrical sessions puts more intelligence on the JVMs. The choice of which to use depends on what kind of hardware you have, how many machines you're using and how you use sessions.
Distributed sessions can use a database as a backing store, or they can distribute the backup among all the servers using TCP.
Symmetrical Sessions
Symmetrical sessions happen with dumb load balancers like DNS round-robin. A single session may bounce from machine A to machine B and back to machine B. For JDBC sessions, the symmetrical session case needs the always-load-session attribute described below. Each request must load the most up-to-date version of the session.
Distributed sessions in a symmetrical environment are required to make sessions work at all. Otherwise the state will end up spread across the JVMs. However, because each request must update its session information, it is less efficient than sticky sessions.
Sticky Sessions
Sticky sessions require more intelligence on the load-balancer, but are easier for the JVM. Once a session starts, the load-balancer will always send it to the same JVM. Resin's load balancing, for example, encodes the session id as 'aaaXXX' and 'baaXXX'. The 'aaa' session will always go to JVM-a and 'baa' will always go to JVM-b.
Distributed sessions with a sticky session environment add reliability. If JVM-a goes down, JVM-b can pick up the session without the user noticing any change. In addition, distributed sticky sessions are more efficient. The distributor only needs to update sessions when they change. So if you update the session once when the user logs in, the distributed sessions can be very efficient.
always-load-session
Symmetrical sessions must use the 'always-load-session' flag to update each session data on each request. always-load-session is only needed for jdbc-store sessions. tcp-store sessions use a more-sophisticated protocol that eliminates the need for always-load-session, so tcp-store ignores the always-load-session flag.
The always-load-session attribute forces sessions to check the store for each request. By default, sessions are only loaded from persistent store when they are created. In a configuration with multiple symmetric web servers, sessions can be loaded on each request to ensure consistency.
always-save-session
Sticky Session
Sticky session means that when a request comes into a site from a client all further requests go to the same server initial client request accessed. I believe that session affinity is a synonym for sticky session.
Using SELECT to INSERT records
INSERT INTO tabelename (the table you want to copy into)
SELECT * from tablename (the table you want to copy from)
WHERE Field10 = (some condition)
This is a clean and easy way to copy data.
The same concept using a simple query without a condition
INSERT INTO table1
SELECT * from table2
Thursday, April 1, 2010
extract and compact
extract — Import variables into the current symbol table from an array
Import variables from an array into the current symbol table.
Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.
example
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
compact — Create array containing variables and their values
Creates an array containing variables and their values.
For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().
Any strings that are not set will simply be skipped.
$city= "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city", "state");
$result = compact("event", "nothing_here", $location_vars);
print_r($result);
Mysql Commands
ALTER TABLE my_table ENGINE = InnoDB;
Command to set foreign keys in Mysql, Oracle and Sql Server
MySQL:
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
Oracle:
ALTER TABLE ORDERS
ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
SQL Server:
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
Thursday, March 18, 2010
File uploads problem in PHP
I’ve seen that many of my friends are struggling with the uploads of the bigger or larger files in PHP. After looking at their struggle, i’m here to solve the problem of uploading larger or bigger files in PHP.
Most of the web servers are configured such a way that a user can only upload the maximum file size of 2MB. So there might be the problem for the people who wants to upload the .pdf file of size around 15MB. But, you can increse the maximum upload file size limit by using .htaccess file.
Here is a small tips for you which you can use to upload such a large file using file field of the form and move_uploaded_file() function in PHP.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP. In the above .htaccess file, uploading capability is increased by the four parameter first one is maximum file size for uploading, second one is maximum size of the post data , third one is maximum time in seconds a script is allowed to run before it is terminated by the parser and last one is maximum time in seconds a script is allowed to parse input data such as like file uploads, POST and GET data.
You can change the above parameter to upload the bigger file size than 20MB.
Wednesday, February 24, 2010
Url rewrite Enabling in Ubuntu
Open this file and give allow override All in
Then now to enable the rewrite
sudo a2enmod rewrite
Now restart apache
sudo /etc/init.d/apache2 restart
To disable the rewrite
sudo a2dismod rewrite
Tuesday, February 23, 2010
Load Balancer and Apache Cluster
The advantage of using a load balancer compared to using round robin DNS is that it takes care of the load on the web server nodes and tries to direct requests to the node with less load, and it also takes care of connections/sessions. Many web applications (e.g. forum software, shopping carts, etc.) make use of sessions, and if you are in a session on Apache node 1, you would lose that session if suddenly node 2 served your requests. In addition to that, if one of the Apache nodes goes down, the load balancer realizes that and directs all incoming requests to the remaining node which would not be possible with round robin DNS.
For this setup, we need four nodes (two Apache nodes and two load balancer nodes) and five IP addresses: one for each node and one virtual IP address that will be shared by the load balancer nodes and used for incoming HTTP requests.
Example setup
* Apache node 1: webserver1.example.com (webserver1) - IP address: 192.168.0.101; Apache document root: /var/www
* Apache node 2: webserver2.example.com (webserver2) - IP address: 192.168.0.102; Apache document root: /var/www
* Load Balancer node 1: loadb1.example.com (loadb1) - IP address: 192.168.0.103
* Load Balancer node 2: loadb2.example.com (loadb2) - IP address: 192.168.0.104
* Virtual IP Address: 192.168.0.105 (used for incoming requests)
Install netbeans in ubuntu
http://netbeans.org/community/releases/68/install.html#downloadoptions
download netbeans from the following link. Select the technology which you want to use and then download. if u want all then click the link provided at the end.
http://netbeans.org/downloads/index.html
A sh file is downloaded now. Give full permission for the downloaded file as
sudo chmod 777 netbeans.sh
Then double click the file and run in terminal. This will install netbeans and you can just follow the steps it takes to.
Configuring Airtel Broadband in Ubuntu
The first part in setting up the connection is to set up static IP on the computer. Open System > Administration > Network. In the Network Manager dialog, click on the Wired device, right click and open the Properties dialog of the Wired Network Device. In the device properties dialog, unselect the "Enable Roaming Mode" checkbox, select static IP as the configuration and enter the following values
IP Address: 192.168.1.2
Network Mask: 255.255.255.0
Gateway: 192.168.1.1
Once these settings are entered done press OK and close the dialog.
or you can type sudo gedit /etc/network/interfaces and change the values in the opened file
Go back to the Network Settings dialog and click on the DNS tab. Click on the Add button and add the following IP Addresses as the DNS Servers in the same order as below.
202.56.215.6
202.56.230.6
208.67.222.222
208.67.220.220
or change the calues in resolv.conf file by sudo gedit /etc/resolv.conf
The second part is to configure the modem to connect automatically to the Internet by configuring PPPOE on the modem directly. Open a browser and type 192.168.1.1 in the Address bar. Enter 'admin' and 'password' as the username and password respectively in the password dialog.
The modem administration control panel will open up in the browser. Click the WAN link given on the left menu. Click the edit button. In the page that comes up enter VPI - 1 and VCI 32. Click Next. Select PPPOE as the connection type and LLC/SNAP-BRIDGING as the encapsulation mode. Click Next and continue to the next page. In the next page enter your login details for the Airtel Broadband connection. Your PPP username must be of the form _dsl@airtelbroadband.in and is the one you would have got from Airtel.
Enter the PPPOE service name as 'airtel' and the authentication mode to auto. Continue to the next page and disable IGMP multicast and enable WAN service. Change the service name to 'airtel'. Click next and then click on SAVE to save your settings and then in the WAN Setup page click on save/reboot to reboot the router.
Once the router is rebooted run
sudo /etc/init.d/networking restart
in a terminal. Open a browser and start browsing :).
Monday, February 15, 2010
Htaccess File
Custom Error Pages
The first use of the .htaccess file which I will cover is custom error pages. These will allow you to have your own, personal error pages (for example when a file is not found) instead of using your host's error pages or having no page. This will make your site seem much more professional in the unlikely event of an error. It will also allow you to create scripts to notify you if there is an error (for example I use a PHP script on Free Webmaster Help to automatically e-mail me when a page is not found).
You can use custom error pages for any error as long as you know its number (like 404 for page not found) by adding the following to your .htaccess file:
ErrorDocument errornumber /file.html
For example if I had the file notfound.html in the root direct
ory of my site and I wanted to use it for a 404 error I would use:
ErrorDocument 404 /notfound.html
If the file is not in the root directory of your site, you just need to put the path to it:
ErrorDocument 500 /errorpages/500.html
These are some of the most common errors:
401 - Authorization Required
400 - Bad request
403 - Forbidden
500 - Internal Server Error
404 - Wrong page
Then, all you need to do is to create a file to display when the error happens and upload it and the .htaccess file.
Stop A Directory Index From Being Shown
Sometimes, for one reason or another, you will have no index file in your directory. This will, of course, mean that if someone types the directory name into their browser, a full listing of all the files in that directory will be shown. This could be a security risk for your site.
To prevent against this (without creating lots of new 'index' files, you can enter a command into your .htaccess file to stop the directory list from being shown:
Options -Indexes
Deny/Allow Certian IP Addresses
In some situations, you may want to only allow people with specific IP addresses to access your site (for example, only allowing people using a particular ISP to get into a certian directory) or you may want to ban certian IP addresses (for example, keeping disruptive memembers out of your message boards). Of course, this will only work if you know the IP addresses you want to ban and, as most people on the internet now have a dynamic IP address, so this is not always the best way to limit usage.
You can block an IP address by using:
deny from 000.000.000.000
where 000.000.000.000 is the IP address. If you only specify 1 or 2 of the groups of numbers, you will block a whole range.
You can allow an IP address by using:
allow from 000.000.000.000
where 000.000.000.000 is the IP address. If you only specify 1 or 2 of the groups of numbers, you will allow a whole range.
If you want to deny everyone from accessing a directory, you can use:
deny from all
but this will still allow scripts to use the files in the directory.
Alternative Index Files
You may not always want to use index.htm or index.html as your index file for a directory, for example if you are using PHP files in your site, you may want index.php to be the index file for a directory. You are not limited to 'index' files though. Using .htaccess you can set foofoo.blah to be your index file if you want to!
Alternate index files are entered in a list. The server will work from left to right, checking to see if each file exists, if none of them exisit it will display a directory listing (unless, of course, you have turned this off).
DirectoryIndex index.php index.php3 messagebrd.pl index.html index.htm
Redirection
One of the most useful functions of the .htaccess file is to redirect requests to different files, either on the same server, or on a completely different web site. It can be extremely useful if you change the name of one of your files but allow users to still find it. Another use (which I find very useful) is to redirect to a longer URL, for example in my newsletters I can use a very short URL for my affiliate links. The following can be done to redirect a specific file:
Redirect /location/from/root/file.ext http://www.othersite.com/new/file/location.xyz
In this above example, a file in the root directory called oldfile.html would be entered as:
/oldfile.html
and a file in the old subdirectory would be entered as:
/old/oldfile.html
You can also redirect whole directoires of your site using the .htaccess file, for example if you had a directory called olddirectory on your site and you had set up the same files on a new site at: http://www.newsite.com/newdirectory/ you could redirect all the files in that directory without having to specify each one:
Redirect /olddirectory http://www.newsite.com/newdirectory
Then, any request to your site below /olddirectory will bee redirected to the new site, with the
extra information in the URL added on, for example if someone typed in:
http://www.youroldsite.com/olddirecotry/oldfiles/images/image.gif
They would be redirected to:
http://www.newsite.com/newdirectory/oldfiles/images/image.gif
This can prove to be extremely powerful if used correctly.
The .htaccess File
Adding password protection to a directory using .htaccess takes two stages. The first part is to add the appropriate lines to your .htaccess file in the directory you would like to protect. Everything below this directory will be password protected:
AuthName "Section Name"
AuthType Basic
AuthUserFile /full/path/to/.htpasswd
Require valid-user
There are a few parts of this which you will need to change for your site. You should replace "Section Name" with the name of the part of the site you are protecting e.g. "Members Area".
The /full/parth/to/.htpasswd should be changed to reflect the full server path to the .htpasswd file (more on this later). If you do not know what the full path to your webspace is, contact your system administrator for details.
The .htpasswd File
Password protecting a directory takes a little more work than any of the other .htaccess functions because you must also create a file to contain the usernames and passwords which are allowed to access the site. These should be placed in a file which (by default) should be called .htpasswd. Like the .htaccess file, this is a file with no name and an 8 letter extension. This can be placed anywhere within you website (as the passwords are encrypted) but it is advisable to store it outside the web root so that it is impossible to access it from the web.
Entering Usernames And Passwords
Once you have created your .htpasswd file (you can do this in a standard text editor) you must enter the usernames and passwords to access the site. They should be entered as follows:
username:password
where the password is the encrypted format of the password. To encrypt the password you will either need to use one of the premade scripts available on the web or write your own. There is a good username/password service at the KxS site which will allow you to enter the user name and password and will output it in the correct format.
For multiple users, just add extra lines to your .htpasswd file in the same format as the first. There are even scripts available for free which will manage the .htpasswd file and will allow automatic adding/removing of users etc.
Accessing The Site
When you try to access a site which has been protected by .htaccess your browser will pop up a standard username/password dialog box. If you don't like this, there are certain scripts available which allow you to embed a username/password box in a website to do the authentication. You can also send the username and password (unencrypted) in the URL as follows:
http://username:password@www.website.com/directory/
.htaccess file
create a file .htaccess in the root folder of the project and include the following lines.
php_value auto_prepend_file "/var/www/foldername/config.php"
Open this file and give allow override All in
sudo gedit /etc/apache2/sites-enabled/000-default
Thursday, February 4, 2010
How to install fonts in Ubuntu 8.04?
Just download the fonts you want from free online web sites and archives, if necessary - unzip them to the desktop or another directory of your choice.
Then using terminal create a directory for your new fonts where the fonts are stored on your system.
The /usr/share/fonts is the location in Ubuntu Linux:
So, please open a Terminal from the menu Applications->Accessories->Terminal and type:
sudo mkdir /usr/share/fonts/myfonts
give your user password when requested, you don't see nothing when you type it, then press enter.
Then still using Terminal to install them:
sudo cp /home/user/Desktop/*.ttf /usr/share/fonts/myfonts/
and refresh your font cache like this:
sudo fc-cache -f
* If you exchange docs with Windows users using OpenOffice please also install some basic Win truetype fonts provided by the msttcorefonts deb package.
First using Synaptic please first enable the universe repository:
Launch Synaptic from menu: System->Administration->Synaptic package manager
From Synaptic menu: Settings->Repositories-> Tab Ubuntu software
enable "Community Maintained open source software (universe)"
Close Synaptic
Then using Terminal simply install package, please type:
sudo apt-get update
sudo apt-get install msttcorefonts
Wednesday, February 3, 2010
Another instance of skype running problem
ps -A | grep skype
Then kill all the instances using the kill it
kill -9 processid
eg : kill -9 12578
Now restart the skype and it will be working for u.
Tuesday, February 2, 2010
Installing skype in Ubuntu Linux
To enable audio in skpe follow the below given instructions
killall pulseaudio
sudo apt-get remove pulseaudio
sudo apt-get install esound
sudo apt-get install pulseaudio
Monday, January 4, 2010
Mysql Useful Queries
SELECT CONCAT(name, ' - ', description) FROM products;
which would give us a resultset like this:
+----------------------------------+
| CONCAT(name, ' - ', description) |
+----------------------------------+
| Faao - Blah blah faao blah |
| Baar - Blah blah baar blah |
| Bddaz - Blah blah bddaz blah |
| Bffat - Blah blah bffat blah |
+----------------------------------+
2. Find the length of the longest string
SELECT MAX(LENGTH(field_to_query)) FROM table_to_query;
3. Renaming a table
RENAME TABLE tablename TO tablename_renamed
4. How to change the storage engine
ALTER TABLE products ENGINE = innodb
5. Listing tables and their structure
mysql> show tables;
mysql> desc table_name;
you can show the indexes from a particular table like so:
mysql> show keys from table_name;