Friday, November 27, 2009
How to use an image as a submit button
<form method="post" action="cgi-bin/someprogram.cgi">
<input name="yourname" type="text">
<input type="image" value="submitname" src="submit-button.gif" width="80" height="20" border="0" alt="SUBMIT!" name="image">
</form>
Thursday, November 26, 2009
PHP cURL functions tutorial
- Implement payment gateways’ payment notification scripts.
- Download and upload files from remote servers.
- Login to other websites and access members only sections.
PHP cURL library is definitely the odd man out. Unlike other PHP libraries where a whole plethora of functions is made available, PHP cURL wraps up a major parts of its functionality in just four functions.
A typical PHP cURL usage follows the following sequence of steps.
curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.
curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.
curl_exec – Executes a cURL session.
curl_close – Closes the current cURL session.
Below are some examples which should make the working of cURL more clearer.
Download file or web page using PHP cURL
The below piece of PHP code uses cURL to download Google’s RSS feed.
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://news.google.com/news?hl=en&topic=t&output=rss');
/**
* Ask cURL to return the contents in a variable
* instead of simply echoing them to the browser.
*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/**
* Execute the cURL session
*/
$contents = curl_exec ($ch);
/**
* Close cURL session
*/
curl_close ($ch);
?>
As you can see, curl_setopt is the pivot around which the main cURL functionality revolves. cURL functioning is controlled by way of passing predefined options and values to this function.
The above code uses two such options.
CURLOPT_URL: Use it to specify the URL which you want to process. This could be the URL of the file you want to download or it could be the URL of the script to which you want to post some data.
CURLOPT_RETURNTRANSFER: Setting this option to 1 will cause the curl_exec function to return the contents instead of echoing them to the browser.
Download file or web page using PHP cURL and save it to file
The below PHP code is a slight variation of the above code. It not only downloads the contents of the specified URL but also saves it to a file.
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://news.google.com/news?hl=en&topic=t&output=rss');
/**
* Create a new file
*/
$fp = fopen('rss.xml', 'w');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
/**
* Execute the cURL session
*/
curl_exec ($ch);
/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);
?>
Here we have used another of the cURL options, CURLOPT_FILE. Obtain a file handler by creating a new file or opening an existing one and then pass this file handler to the curl_set_opt function.
cURL will now write the contents to a file as it downloads a web page or file.
Wednesday, November 25, 2009
JQuery Validation with example
Here is the code we used for the form in the example.
script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"
script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required",// simple rule, converted to {required:true}
email: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">
Name *</span><input name="name" type="text"></div>
<div class="form-row"><span class="label">
E-Mail *</span><input name="email" type="text"></div>
<div class="form-row"><span class="label">
URL</span><input name="url" type="text"></div>
<div class="form-row"><span class="label">
Your comment *</span><textarea name="comment"></textarea></div>
<div class="form-row">
<input class="submit" value="Submit" type="submit"></div>
Remember to include the the jQuery library and the bassistance validation plugin. The link to the jQuery library must come first in the head section, otherwise the validation will not work.
Remember to assign the id attribute of the form and the name attribute of all the fields that you want to validate.
Now, let us see the validate() function in detail.
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", // simple rule, converted to {required: true}
email: { // compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the validate() function at http://docs.jquery.com/Plugins/Validation/validate#toptions.
The two parameters we used are:
rules: allows you to specify which fields you want to validate. In this case, we are validating name, email, url and comment. For each field, we specify if the field is required (required: true). We can specify that it must be a valid e-mail address, URL, etc.
messages: allows you to specify the error message for a particular field (like the comments field in the example above). If you don't specify it, a default message is provided that says "this field is required".
In the example above, we only used three validation methods (required, email and url). There are several other methods that can be used here. Here are a few of them:
remote: requests a resource to check the element for validity.
min: makes the element require a given minimum.
date: makes the element require a date.
creditcard: makes the element require a credit card number.
equalTo: requires the element to be the same as another one.
You can find an exhaustive list of built-in validation methods at http://docs.jquery.com/Plugins/Validation.
Writing Your Own Validation Method
Consider a form where the user chooses his favorite sport. If he submits the form without choosing a sport, he is prompted with an error message.
Favorite Sport
As there is no built-in method to validate a drop down menu, we need to define our own method.
jQuery.validator.addMethod(
"selectNone",
function(value, element) {
if (element.value == "none")
{
return false;
}
else return true;
},
"Please select an option."
);
$(document).ready(function() {
$("#form2").validate({
rules: {
sport: {
selectNone: true
}
},
});
});
We do so by calling the jQuery.validator.addMethod() method. It takes three parameters:
name: The name of the method, used to identify and referencing it, must be a valid javascript identifier.
method: the actual method implementation, returning true if an element is valid.
message: The default message to display for this method.
In the validate function, we specify that the 'sport' field should be validated using the selectNone method.
Being able to define your own validation methods allows you to validate pretty much anything that you can think of. Using this plugin, you can very quickly add validation to a form. However, let me remind you that this validation happens only on the client side. While JavaScript validation is useful because of its responsiveness, if there is a JavaScript error, the browser could ignore the remaining validation and submit the form to the server. So my final word of advice would be to validate the data again on the server side.
Monday, November 23, 2009
Sphinx search
Sphinx is a full-text search engine, distributed under GPL version 2. It is not only fast in searching but it is also fast in indexing your data. Currently, Sphinx API has binding in PHP, Python, Perl, Ruby and Java.
Sphinx features
- high indexing speed (upto 10 MB/sec on modern CPUs);
- high search speed (avg query is under 0.1 sec on 2-4 GB text collections);
- high scalability (upto 100 GB of text, upto 100 M documents on a single CPU);
- provides good relevance ranking through combination of phrase proximity ranking and statistical (BM25) ranking;
- provides distributed searching capabilities;
- provides document exceprts generation;
- provides searching from within MySQL through pluggable storage engine;
- supports boolean, phrase, and word proximity queries;
- supports multiple full-text fields per document (upto 32 by default);
- supports multiple additional attributes per document (ie. groups, timestamps, etc);
- supports stopwords;
- supports both single-byte encodings and UTF-8;
- supports English stemming, Russian stemming, and Soundex for morphology;
- supports MySQL natively (MyISAM and InnoDB tables are both supported);
- supports PostgreSQL natively.
There you go, so fire up your terminal or console, and let’s get thing done.
Installing sphinxsearch
- Download sphinx at sphinxsearch.com, for this tutorial, I use Sphinx 0.9.8.1
$wget http://sphinxsearch.com/downloads/sphinx-0.9.8.1.tar.gz
- Open your terminal, extract and install sphinx
$tar -xvf sphinx-0.9.8.1.tar.gz
- sphinx need mysql-dev install, if you use ubuntu linux install this
$sudo apt get install libmysqlclient15-dev
- Install sphinx to your system
$cd sphinx-0.9.8.1/
$./configure
$make
$sudo make installNote if you want to use sphinx with PostgreSQL, configure with this argument –with-pgsql
$./configure --with-pgsql
Test your installation
$search This should come up in your terminal
Sphinx 0.9.8.1-release (r1533)
Copyright (c) 2001-2008, Andrew Aksyonoff
Usage: search [OPTIONS] [word2 [word3 [...]]]
Options are:
-c, --config use given config file instead of defaults
-i, --index search given index only (default: all indexes)
-a, --any match any query word (default: match all words)
-b, --boolean match in boolean mode
-p, --phrase match exact phrase
-e, --extended match in extended mode
-f, --filter only match if attribute attr value is v
-s, --sortby sort matches by 'CLAUSE' in sort_extended mode
-S, --sortexpr sort matches by 'EXPR' DESC in sort_expr mode
-o, --offset print matches starting from this offset (default: 0)
-l, --limit print this many matches (default: 20)
-q, --noinfo dont print document info from SQL database
-g, --group group by attribute named attr
-gs,--groupsort sort groups by
--sort=date sort by date, descending
--rsort=date sort by date, ascending
--sort=ts sort by time segments
--stdin read query from stdin
This program (CLI search) is for testing and debugging purposes only;
it is NOT intended for production use. Well done. You have Sphinx at your service. But before you can play with this full text search engine you have just installed, you have to understand how Sphinx works.
Sphinx installed 4 program in your environment, but most of the time we will only use indexer, search and searchd. To begin with, we have to create an index for our source. Let’s create a file name sphinx.conf, and here is a sample of sphinx.conf look like.
source book
{
type = mysql
sql_host = localhost
sql_user = root
sql_pass = root
sql_db = library
sql_port = 3306# optional, default is 3306
sql_query = SELECT id, title, summary, author from library
sql_query_info = SELECT * FROM library_book WHERE id=$id
}
index book
{
source = book
path = data/book
docinfo = extern
charset_type = sbcs
}
indexer
{
mem_limit = 32M
}
searchd
{
port = 3312
log = log/searchd.log
query_log = log/query.log
read_timeout = 5
max_children = 30
pid_file = log/searchd.pid
max_matches = 1000
}
For more information about sphinx configuration, please go to sphinx documentation.
Create log folder for our searchd log file and another folder named data for our index data. Run indexer to index our database.
$mkdir log
$mkdir data
$indexer --all
Sphinx 0.9.8.1-release(r1533)
Copyright (c) 2001-2008, Andrew Aksyonoff
using config file ./sphinx.conf'...
indexing index 'book'...
collected 12 docs, 0.0 MB
sorted 0.0 Mhits, 100.0% done
total 12 docs, 10319 bytes
total 0.018 sec, 571436.48 bytes/sec, 664.53 docs/sec
You can use search program to test search index you have just created. Assuming you have book with title contain PHP in your database, then run search PHP will give you some results.
$search PHP
Done.
Important Linux Commands
- chmod – change permission of a file or directory Linux has something called permission on file or folder.
r – Read permission. Permission to read a file or browse a folder
w – Write permission. Permission to write to file or create new file in the folder
x – Execute permission. Permission to execute file
$ls -al -rw-r--r-- 1 gchandrasa gchandrasa 43 2009-02-15 15:00 sample.txt
the first 3 characters after -,rw-belong to users permission.
the second 3 charactersr--belong to group permission.
the third 3 charactersr--belong to others user permission.
One way to change this permission is using the number
r = 4
w = 2
x = 1
So if you want to change the sample.txt permission to others, give read and write permissions.
r = 4 and w = 2, so rw = 4 + 2 = 6
$chmod 646 sample.txt
Give read and write permission to users, read permission to group, and read and write permission to others. - cd – change directory
Use this command to change your current directory.
Example : you need to change directory to Documents$ cd Documents
- cp – copy files and directories
Example : copy file index.php from directory a to directory b$ cp a/index.php b/
- ls – list files in a directory
Example : list files in current directory$ ls
Example : list files in current directory, and show hidden files.
$ ls -a
- man – display manual for a command
$ man mv
- mkdir – create new directories
$ mkdir newfolder
- mv – move (rename) files
Use this command to move your file(s) or to rename file(s).$ mv oldfolder newfolder
- rm – remove files or directories.
Delete all files with extension jpg in current directory.$ rm *.jpg
- tar – The GNU version of the tar archiving utility
Untar and extract file$ tar -xvf test.tar.bz2
- unzip – list, test and extract compressed files in a ZIP archive
Extract file zip$ unzip test.zip
rmdir – remove directory with folders and files
$ rmdir -fr foldername
Installing CakePHP on Ubuntu
- Install Apache Server, MySQL, PHP
sudo apt-get install apache2 mysql-server php5
- Download CakePHP
Go to http://cakephp.org and download latest cakephp. I downloaded cake_1.2.1.8004.tar.bz2 - Copy and extract to web root
Open your terminal where you put cakephp you just downloaded.sudo cp cake_1.2.1.8004.tar.bz2 /var/www/
cd /var/www
sudo tar -xvf cake_1.2.1.8004.tar.bz2
sudo mv cake_1.2.1.8004 cakephp - Change tmp folder permisssion
sudo chmod -R 777 cakephp/app/tmp
- Enable mod-rewrite
sudo a2enmod rewrite
- Open file /etc/apache2/sites-enabled/000-default and change AllowOverride None to AllowOverride All
sudo vim /etc/apache2/sites-enabled/000-default
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from allto
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all - Restart Apache
sudo /etc/init.d/apache2 restart
- Open your browser and type address http://localhost/cakephp/ and you’ll see CakePHP message
If you can see CakePHP message in colour, then you have cakephp running in your hand.
Tuesday, November 17, 2009
Function in PHP to post data in twitter
{
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)).
"Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(array('status' => $message)),
'timeout' => 5,
),
));
$ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);
return false !== $ret;
}
$a = tweet('From PHP, yeah...', 'email@email.com', 'mypassword');
print_r($a);
How to Tweet Using PHP without any Twitter App!
Code
$username = 'myUserName';
$password = 'myPassword';
$status = 'This is a new Tweet!';
if ($status) {
$tweetUrl = 'http://www.twitter.com/statuses/update.xml';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "$tweetUrl");
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status");
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($curl);
$resultArray = curl_getinfo($curl);
if ($resultArray['http_code'] == 200)
echo ‘Tweet Posted’;
else
echo ‘Could not post Tweet to Twitter right now. Try again later.’;
curl_close($curl);
}
Note:
- Change $username to YOUR username
- Change $password to YOUR password
- Edit $status to the Tweet that you want posted.
So this is it. Additionally you can add some more Javascripts that counts the amount of characters in the Tweet field.
Monday, November 16, 2009
A GUI Password Change in Ubuntu?
In GUI to change password, goto System -> Preferences -> About Me. When you bring up this dialog, there's a Change Password button in the right hand corner. Follow the prompts and you'll achieve exactly the same thing as if you'd used the command line.
Ubuntu: Change your password using the command line
How do you change your password in Ubuntu using command line?
To change your password through the command line, you simply type in passwd and hit return. You'll be prompted to enter your current password first, then your new password twice. The password is changed now.