Thursday 26 July 2012

Add CSS File To Specific Pages In Drupal

adding certain CSS files to only certain pages of a Drupal project, rather than every page. This is commonly desired when you are using a drastically different front page in comparison to your drill pages. To achieve this you will want to use the drupal_add_css() function provided by the Drupal API.



it’s very basic in functionality: drupal_add_css(path_to_theme() . '/layout-fixed.css', 'theme', 'all'); Given a path to a CSS file, it will load it where ever the function is called. The second param specifies whether you are theming a “theme” or a “module” with it, and the third param reffers to the “media” attribute of the tag
To remove an existing CSS file per page, try something like:

$arrCSS = drupal_add_css();
unset($arrCSS['all']['theme']['path/to/css-file.css']);
 $vars['styles'] = drupal_get_css($css);
 return $vars;

Include CSS or Javascript file for specific node in Drupal 6

you need to do is add a node preprocess function that adds those files for you. You can do this either in a module or in a custom theme. For a module this would be:
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if (!empty($node) && $node->nid == $the_specific_node_id) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . "/file.js", "module");
    drupal_add_css(drupal_get_path('module', 'mymodule') . "/file.css", "module");
  }
}

or for a theme:
 
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  if (!empty($node) && $node->nid == $the_specific_node_id) {
    drupal_add_js(path_to_theme() . "/file.js", "theme");
    drupal_add_css(path_to_theme(). "/file.css", "theme");
  }
} 
 when you want to insert inline code into something other than technically a node so there's no node id and no PHP input option available.

http://drupal.org/project/js_injector and http://drupal.org/project/css_injector

Wednesday 18 July 2012

How to view result for Computing a field from a view


  // Views handles this page
  $view = views_get_view('view name');
  $view->set_display('default');
  $view->set_arguments(array($tid));
  $view->sort_form = $sort_form;
  // apply the 'Topics per page' setting from core Forum
  $view->display['default']->handler->options['items_per_page']=$forum_per_page;
  
$view->execute();

foreach($view->result as $row){
/**
* DO YOUR STUFF HERE  
*/
}


Friday 13 July 2012

Here is the list of 43 short tips you can use for writing an optimized and more efficient PHP code:


  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than print.
  3. Use echo's multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Unset your variables to free memory, especially large arrays.
  6. Avoid magic like __get, __set, __autoload
  7. require_once() is expensive
  8. Use full paths in includes and requires, less time spent on resolving the OS paths.
  9. If you need to find out the time when the script started executing, INSERT:CONTENT:END SERVER['REQUEST_TIME'] is preferred to time()
  10. See if you can use strncasecmp, strpbrk and stripos instead of regex
  11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  13. It's better to use select statements than multi if, else if, statements.
  14. Error suppression with @ is very slow.
  15. Turn on apache's mod_deflate
  16. Close your database connections when you're done with them
  17. $row['id'] is 7 times faster than $row[id]
  18. Error messages are expensive
  19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  21. Incrementing a global variable is 2 times slow than a local var.
  22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  26. Methods in derived classes run faster than ones defined in the base class.
  27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++operations. A similar method call is of course about 15 $localvar++ operations.
  28. Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
  29. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  33. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
    Example:if (strlen($foo) < 5) { echo "Foo is too short"; }
    vs.
    if (!isset($foo{5})) { echo "Foo is too short"; }
    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
  34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  36. Do not implement every data structure as a class, arrays are useful, too
  37. Don't split methods too much, think, which code you will really re-use
  38. You can always split the code of a method later, when needed
  39. Make use of the countless predefined functions
  40. If you have very time consuming functions in your code, consider writing them as C extensions
  41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
  43. Excellent Article about optimizing php by John Lim

Securing PHP Files using HTTP Authentication



IntroductionIt is quite common to have the need to password protect a certain file or a set of files, in order to prevent unauthorized access to those files. There are many different alternatives on how to do this including, sessions, cookies, JavaScript and HTTP authentication. The latter of these is what we are going to concentrate on in this article.
Usually this form of authentication is called Apache HTTP Authentication as it is only available for Apache based web server. To be honest, that is a lie as it is also possible with Microsoft's IIS web server, however, is much more difficult to implement and requires many configuration changes in order for it to run successfully. Hence, we will only focus on getting this working under Apache.
Apache
For those of you who don't know what Apache is, it is a web server. Therefore, it is the 'program' that is running PHP and that accepts incoming requests for web pages and sends out the correct data. As we are focusing on Apache in this article, it is important to know if you are running Apache or not. This is fairly simple to find out, using thephpinfo() function. Simple create a PHP page with the following code:
phpinfo();
?>
Run this new file and you should get an output which contains a lot of information about your current PHP setup. The most important section is the top section, and should look something like the following:
Look at the Server API field and make sure that it says Apache. If it does, then you are running the perfect configuration – Apache with PHP as a module. The field may say CGI, if it does, you will have to scroll down the page, and check if there is an 'Apache' section. If there isn't, it is likely that you aren't running Apache, hence this article probably won't be of much use. If you want, you can always install Apache on your PC by checking out this auto-installer.
If you are running Apache and CGI-mode, then there is a slight chance that the code supplied will not work, however, I have modified it so that your chances are quite high. By default though, HTTP Authentication doesn't work in CGI mode, however with a small trick it can be made to work.
What is HTTP Authentication?
You may not consciously know what HTTP Authentication is; however, it is most likely that you have used it once or twice, if not many of times. It is used commonly as login interfaces to the administration areas of some PHP scripts, as well as some popular websites, such as vBulletin.com. To refresh your memory, here is a small image of the login process:
Now that you know what HTTP Authentication is, it's time to find out how to implement it for single and multiple files.
Protecting Single and Multiple FilesWe are going to start off adding password protection to a single file, and then modify that so we add it to multiple files. The way HTTP authentication works, is by using HTTP headers which the browser and the web server (Apache) both understand. By using the correct headers we can produce a page which asks for the user to login. If the entered information is correct, we show the page, otherwise we show a nice error message.
As I mentioned, the basis of HTTP authentication is using HTTP headers, which are accessible by using the PHPheader() function. This specifics of this function have been explained before in great detail in Speed Limit File Downloads. However, for the sake of drilling it into your brains, the most important thing about the header() function is that there can be no output to the browser before calling header(). If there is, you will receive a nasty error and the script will cease to function.
Here's the code:
HTTP Authenticationif (@$_SERVER['PHP_AUTH_USER'] != 'john' && @$_SERVER['PHP_AUTH_PW'] != 'secret') {
header('WWW-Authenticate: Basic realm="Site Administration Area"');
header('Status: 401 Unauthorized');
/* Special Header for CGI mode */
header('HTTP-Status: 401 Unauthorized');
?>
Access Unauthorized
Access to the requested page denied
You have been denied access to this page for entering an
incorrect or non-exist username and password.
Press 'Refresh' to retry the login procedure.
exit;
}
echo 'Welcome to our site, username ' . $_SERVER['PHP_AUTH_USER'];
?>
This code contains all the important aspects of HTTP authentication that you need to get started. First thing to notice is that there is no output before header() calls. Secondly, notice that we have two special variables inside the$_SERVER superglobal. These are PHP_AUTH_USER and PHP_AUTH_PW and they represent the current HTTP authenticated username and password. As they may not exist when we call our script, I have placed an 'at' symbol (@) before both of these variables. The @ symbol tells PHP to suppress any errors that may arise in the specified statement. Hence, we know that an error might occur because these variables may not yet exist, so we use @ to suppress it.
The way the headers are written are very important using this method of authentication, as very slight changes can result in the login procedure not working and everyone having access to your file(s). It is important that the orders of the headers are correct and that the actual content is correct. For example, for maximum compatibility, the B in Basicmust be capital, as well as the text in realm being surrounded in double quotes, not single.
In the first header, we have a realm option. This is where we can place some text that will go on our username / password request form. You shouldn't place too much text here, just a basic description of what the user is logging in to.
The usage of this script is a little strange to visualize, because first we check if the user is logged in, and if not, then we send some headers and then end the script. If actual usage, after the headers are sent, the browser waits from the input from the user. Once the user clicks on the OK button, it will then reload the script, to check if the username and password combination are correct. If not it will display the login again (up to three times), and then upon failure will show the error page. If the username is correct, it skips the headers section, and just displays the normal content of your script.
Securing Multiple Files
Most of the time when you are password protecting an area on your website, you will need to secure more than one page. What you would then do, if move all the above code into an include file, and then include the file on any page that you want to password protect. This could become cumbersome, especially if you are already including many files. The alternative is to convert this into a function, so that you can add it into a function library file (which you might already have). This way, the code is always available, and we can make it a little more reuseable.
Reusable Codefunction validateUser ($fUsername = 'john', $fPassword = 'secret') {
if (@$_SERVER['PHP_AUTH_USER'] != $fUsername && @$_SERVER['PHP_AUTH_PW'] != $fPassword) {
header('WWW-Authenticate: Basic realm="Site Administration Area"');
header('Status: 401 Unauthorized');
/* Special Header for CGI mode */
header('HTTP-Status: 401 Unauthorized');
?>
Access Unauthorized
Access to the requested page denied
You have been denied access to this page for entering an
incorrect or non-exist username and password.
Press 'Refresh' to retry the login procedure.
exit;
}
}
?>
Now we have a function called validateUser which takes two parameters; $fUsername and $fPassword. These are the username and password that you want the user to login with. I have also added default values so that if you do not specify a username or password (maybe you forget to), then the user can log in with the default values.
This function can then be added to a library file of functions. These are used to hold commonly used functions in your programs and are usually necessary if you are writing a lot of scripts. Commonly, I use global.php for my library functions.
index.phprequire_once('globa.php');
validateUser('john', 'newsecret');
echo 'Welcome to our secret area!';
?>
Here I have assumed that you have placed the function into a file called globa.php so that we can include it. I have used require_once() to include the file, so that if PHP cannot find the file, the script will exit and also the file will not be included more than once. Now to run the authentication routine, we just make a simple call to validateUser() with the username and password we expect the user to log in with.
These examples are useful if you only have one or two people logging into your site and they share the same username. However, sometimes you may want to allow a multitude of people to access this area. For this, it is common to use databases.
Allowing Multiple UsersThere are two main methods of allowing multiple users password protected access to your website. The first being username/password files and the second being username/password tables in a database. As many people use database nowadays, I will now focus on this method. In order to implement a file based version of this script, you will have to save usernames and passwords to a file (username,password on each line). You would then read each line, and check if the username and password match.
Back to the main topic of databases! They are useful in this sense, and often websites have a dynamic Content Management System (CMS) for their website which has allows for several users or authors to access this area. The author data is already stored in the database, so there is no need to add a file or more data. I'm going to assume you know a little about how to access MySQL databases in this section, but don't worry, it should be too difficult.
To start of with, we need a table of the usernames and passwords. This is SQL which can be executed by running MySQL via the command line, or by using a script such as phpMyAdmin.
CREATE TABLE 'users' (
'userID' INT NOT NULL AUTO_INCREMENT,
'username' VARCHAR( 20 ) NOT NULL ,
'password' VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( 'userID' ) ,
UNIQUE ( 'username')
);
Now, let's enter a few users:
INSERT INTO 'users' ( 'userID' , 'username' , 'password' )
VALUES ( '', 'john, 'secret');
INSERT INTO 'users' ( 'userID' , 'username' , 'password' )
VALUES ( '', 'peter', 'othersecret');
INSERT INTO 'users' ( 'userID' , 'username' , 'password' )
VALUES ( '', 'billy', 'ilovecats');
Now we have our database table setup called users. On my computer, I have this table in a database called myCms so we will use that in our examples.
To get going, we must first connect to the database. At the same time, we are also going to convert all this into our own function so that it is again reusable in the future.
Connect
function validateUser () {
mysql_connect('dbusername', 'dbpassword', 'localhost') or die(mysql_error());
mysql_select_db('myCms') or die(mysql_error());
}
?>
Here we have connected to the database using our database name and password. You must change the username and password for your setup. We then select our database (myCms). If any errors occur the script is terminated and the error is outputted using die(mysql_error()). This is especially useful in determining any bugs in your scripts.
Now we must query the database and check if the username and password that has been entered is correct:
function validateUser () {
mysql_connect('dbusername', 'dbpassword', 'localhost') or die(mysql_error());
mysql_select_db('myCms') or die(mysql_error());
$user = @addslashes($_SERVER['PHP_AUTH_USER']);
$password = @addslashes($_SERVER['PHP_AUTH_PW']);
$sql = "SELECT Count(*) as Number FROM users WHERE username='" . $user . "' AND password='" . $password . "'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
$NumberOfUsers = $result['Number'];
}
?>
This may be a little daunting but it is simple in essence. All we have done, is modified the input username and password by calling addslashes() on them. This is a security issue and should always be performed on user input to database, to prevent them from gaining unauthorized access.
We then have our query, which selects (gets) numbers of records that meets our conditions. Our conditions state the username and password must match the ones that the user has entered.
Following this, we execute the query, get the results and then assign the result called Number to a variable called$NumberOfUsers so that we can use it. Now all that's left to do, is the standard header output:
Altogether Now
function validateUser () {
mysql_connect('dbusername', 'dbpassword', 'localhost') or die(mysql_error());
mysql_select_db('myCms') or die(mysql_error());
$user = @addslashes($_SERVER['PHP_AUTH_USER']);
$password = @addslashes($_SERVER['PHP_AUTH_PW']);
$sql = "SELECT Count(*) as Number FROM users WHERE username='" . $user . "' AND password='" . $password . "'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
$NumberOfUsers = $result['Number'];
if ($NumberOfUsers != 1) {
header('WWW-Authenticate: Basic realm="Site Administration Area"');
header('Status: 401 Unauthorized');
/* Special Header for CGI mode */
header('HTTP-Status: 401 Unauthorized');
?>
Access Unauthorized
Access to the requested page denied
You have been denied access to this page for entering an
incorrect or non-exist username and password.
Press 'Refresh' to retry the login procedure.
exit;
}
}
?>
This is essentially the same as the code of the previous page, however this time, as we have queried the database for the number of users where the username/password match, we do not have to again check the input username/password. Instead, we have the number of users with the correct match – this should equal to 1 or 0, and never more. Hence, we check if the number does not equal to 1, if so, we send the headers.
As we have defined this all in a function, we can again move this into a library file and now we can call this on every page using this method:
Multiple Pages
require_once('global.php');
validateUser();
echo 'Welcome to the secured area!';
?>
This is almost the same as previously, except there are no parameters for the validateUser() function as all the username / password combinations are taken from the database.
I hope this article has helped you gain an understanding on how to password protect your website using this simple but efficient method. You should now try it out for yourself, or maybe consider implementing the file based version.

Add Pinterest "Pin It" Counter Button To Blogger

<a class='pin-it-button' count-layout='horizontal' expr:href='&quot;http://pinterest.com/pin/create/button/?url=&quot; + data:post.url'>Pin It Now!</a>
<a href='javascript:void(run_pinmarklet())' style='margin-left:-93px; width:43px; height:20px; display:inline-block;'/>
<script src='http://assets.pinterest.com/js/pinit.js' type='text/javascript'/>
<script type='text/javascript'>
function run_pinmarklet() {
var e=document.createElement('script'); e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random()*99999999);
document.body.appendChild(e);
}
</script>

How to Add Twitter’s Official Tweet Button in WordPress


<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
   <a href="http://twitter.com/share"
      data-url="<?php the_permalink(); ?>"
      data-via="wpbeginner"
      data-text="<?php the_title(); ?>"
      data-related="syedbalkhi:Founder of WPBeginner"
      data-count="vertical">Tweet</a>

How to Ajax auto refresh after x seconds


Use of setInterval function

just alert “Naru” to test this function
setInterval( "alert('Hello Naru')", 5000 );  ///////// 5 seconds

Example : With jquery,update div contents after 5 seconds

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 5000 );  ///////// 10 seconds

$(function() {
SANAjax = function(){

$('selector').prepend("Hi This is auto refresh example for you - w3cgallery.com <br><br>").fadeIn("slow");

}
 });
</script>

Node.js integration to Drupal.


Node.js integration
===================
This module adds Node.js integration to Drupal.
Setup
=====
1. Install Node.js.

 Installing Node.js and NPM on Ubuntu/Debian

How to Install Node.js

2. Install required Node.js modules with the Node Package Manager (NPM).
Make sure you are in the nodejs module directory - NPM needs the package.json
file that comes with the nodejs module to install the right modules.
cd path/to/your/nodejs/module/directory
npm install
npm uninstall express
npm install express@2.5.9
3. Create a 'nodejs.config.js' file in your nodejs module directory.
Read the 'nodejs.config.js.example' file. A basic configuration can be as simple as:
/**
* This configuration file was built using the 'Node.js server configuration builder'.
* For a more fully commented example see the file nodejs.config.js.example in the root of this module
*/
backendSettings = {
"scheme":"http",
"host":"192.168.1.61",
"port":8080,
"key":"/path/to/key/file",
"cert":"/path/to/cert/file",
"resource":"/socket.io",
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":80,
"host":"localhost",
"messagePath":"/drupal7/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":true,
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
Set debug to false when you are happy with your setup.
4. Run the node server with the command: node server.js
As long as you have 'debug: true' in your configuration file, you'll see lots of helpful messages.

Installing Node.js and NPM on Ubuntu/Debian


his is just short snippet on how to install Node.js (any version) and NPM (Node Package Manager) on your Ubuntu/Debian system.
Step 1 - Update your system
sudo apt-get update
sudo apt-get install git-core curl build-essential openssl libssl-dev
Step 2 - Install Node.js
First, clone the Node.js repository:
git clone https://github.com/joyent/node.git
cd node
Now, if you require a specific version of Node:
git tag # Gives you a list of released versions
git checkout v0.4.12
Then compile and install Node like this:
./configure
make
sudo make install
Then, check if node was installed correctly:
node -v
Step 3 - Install NPM
Simply run the NPM install script:
curl http://npmjs.org/install.sh | sudo sh
And then check it works:
npm -v
That's all.

How to Install Node.js Essay Steps


This was the first in a series of posts leading up to Node.js Knockout on how to use node.js.
I have been given permission to repost the articles from the contest here (in wheat format) for general consumption. Expect more to come.
In this post we detail how to install node on MacUbuntu, and Windows.

Mac

If you're using the excellent homebrew package manager, you can install node with one command: brew install node.
Otherwise, follow the below steps:
  1. Install Xcode.
  2. Install git.
  3. Run the following commands:
darwin_setup.sh
git clone git://github.com/ry/node.git cd node ./configure make sudo make install
You can check it worked with a simple Hello, World! example.

Ubuntu

  1. Install the dependencies:
    • sudo apt-get install g++ curl libssl-dev apache2-utils
    • sudo apt-get install git-core
  2. Run the following commands:
ubuntu_setup.sh
git clone git://github.com/ry/node.git cd node ./configure make sudo make install
 Step 3 - Install NPM
Simply run the NPM install script:
curl http://npmjs.org/install.sh | sudo sh
And then check it works:
npm -v
You can check it worked with a simple Hello, World! example.
Thanks to code-diesel for the Ubuntu dependencies.

Windows

Currently, you must use cygwin to install node. To do so, follow these steps:
  1. Install cygwin.
  2. Use setup.exein the cygwin folder to install the following packages:
    • devel → openssl
    • devel → g++-gcc
    • devel → make
    • python → python
    • devel → git
  3. Open the cygwin command line with Start > Cygwin > Cygwin Bash Shell.
  4. Run the below commands to download and build node.
cygwin_setup.sh
git clone git://github.com/ry/node.git cd node ./configure make sudo make install
For more details, including information on troubleshooting, please see the GitHub wiki page.

Hello Node.js!

Here's a quick program to make sure everything is up and running correctly:
hello_node.js
var http = require('http'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.end('Hello Node.js\n'); }).listen(8124, "127.0.0.1"); console.log('Server running at http://127.0.0.1:8124/');
Run the code with the node command line utility:
> node hello_node.js Server running at http://127.0.0.1:8124/ 
Now, if you navigate to http://127.0.0.1:8124/ in your browser, you should see a nice message.

Congrats!

You've installed node.js.

8 Practical PHP Regular Expressions


Validating a Username:
Quote: Something often overlooked, but simple to do with a regular expression would be username validation. For example, we may want our usernames to be between 4 and 28 characters in length, alpha-numeric, and allow underscores. PHP Code: $string = "userNaME4234432_";
if (preg_match('/^[a-z\d_]{4,28}$/i', $string)) {
echo "example 1 successful.";
}
Telephone Numbers:
Quote: Number in the following form: (###) ###-#### PHP Code: $string = "(232) 555-5555";
if (preg_match('/^(\(?[0-9]{3,3}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-9]{4,4}$/', $string)) {
echo "example 2 successful.";
}
Emails:
PHP Code: $string = "first.last@domain.co.uk";
if (preg_match(
'/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
$string)) {
echo "example 3 successful.";
}
Postal Codes:
PHP Code: $string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo "example 4 successful.";
}
Ip Address:
PHP Code: $string = "255.255.255.0";
if (preg_match(
'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',
$string)) {
echo "example 5 successful.";
}
Hexadecimal Colors:
PHP Code: $string = "#666666";
if (preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i', $string)) {
echo "example 6 successful.";
}
Multi-line Comments:
PHP Code: $string = "/* commmmment */";
if (preg_match('/^[(/*)+.+(*/)]$/', $string)) {
echo "example 7 successful.";
}
Dates:
Quote: MM/DD/YYYY format PHP Code: $string = "10/15/2007";
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $string)) {
echo "example 8 successful.";
}
Some might be more/less useful than the others but that will depend on the project you are working on.