Saturday, December 27

Check multiple e-mail Id from a file PHP

    $file_string = file_get_contents("example.txt"); // Load text file contents
    $matches_email_id=array();

// don't need to preassign $matches, it's created dynamically


// this regex handles more email address formats like a+b@google.com.sg, and the i makes it case insensitive

    $reg_pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
/*******************OR******************/
    $reg_pattern = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';

// preg_match_all returns an associative array

    preg_match_all($reg_pattern, $file_string, $matches_email_id);

// the data you want is in $matches[0], dump it with var_export() to see it

    var_export($matches_email_id[0]);


OUTPUT:


array (

  0 => 'test1+2@gmail.com',
  1 => 'test-2@yahoo.co.jp',
  2 => 'test@test.com',
  3 => 'test@test.co.uk',
  4 => 'test@google.com.sg',
)

Thursday, December 18

How to Set Up Apache Virtual Hosts on Ubuntu 13.10

Introduction

Virtual Hosts

Virtual Hosts are a way to host more than one domain from a single IP address/server. This could be helpful, for example, to people who wish to host more than one website from a single droplet. The visitors of the websites will be shown the correct information based on the domain they are accessing, whereas, without virtual hosts correctly setup, all domains would display the same information. There is no limit to the number of virtual hosts (e.g. domains) that can be added to a server, given enough computing and storage capacity.

Prerequisites
In order to run the commands in this tutorial, the user must have root privileges. If you log into your droplet using your root user account, you mustn’t worry about this. If you don’t, you can see how to set that up in the article Initial Server Setup.

Additionally, you need to have Apache installed and running on your cloud server. If you don’t already, you can install it using the following command:

   sudo apt-get install apache2

If you are going to be hosting websites that rely on PHP or MySQL (e.g. Wordpress), the easiest way to setup a LAMP (Linux, Apache, MySQL, PHP) stack is to run this command:

   sudo tasksel install lamp-server

What the Red Means
The lines that a user needs to enter or customize will be in red troughout this tutorial!

The rest is copy-and-pastable.

Step One – Create a New Folder/Directory

The first step is to create a directory where we will store the files (and folders) for your new domain. Normally, the name of this new directory should correspond to the name of the domain you are trying to setup, but that isn’t a rule. You can name the new directory anything you want, as long as you remember what it's called, since we will be needing the directory path later for the virtual host configuration file.

   sudo mkdir -p /var/www/mysite.com

The -p flag ensures that all the parents of this directory exist, and if they don’t it generates them.

mysite.com is a placeholder address – replace it with your correct domain name.

Step Two – Granting Permissions

First, we need to grant ownership of the directory to the user Apache is running as.

   sudo chown -R www-data:www-data /var/www/mysite.com
Next, we need to set the correct permissions for the directory so that the files are accessible to everyone.

   sudo chmod -R 755 /var/www
That does it for this step.

Step Three – Create a Page
We will now create a sample index.html file so that we can test whether our virtual host is working correctly.

For this step, you will want to make sure you have the nano text editor installed.

   sudo apt-get install nano
Next, create the index.html file.

   sudo nano /var/www/mysite.com/index.html
You can copy and paste the code below to the newly created index.html file.

   <html>

     <head>


       <title>www.mysite.com</title>


     </head>


     <body>

       <h1>Success: You Have Set Up a Virtual Host</h1>
     </body>
   </html>

Save and exit using Ctrl+O then Enter then Ctrl+X.

Step Four – Create a New Virtual Host Configuration File
Now we will set up the virtual host configuration file. Luckily for us, Ubuntu ships with a template for this configuration file. We simply have to make a copy of that file for our use by using the command below.

    sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-                                               available/example.com.conf
Do note that adding the .conf to the end is required as of Ubuntu 13.10, which differs from previous versions.

Step Five – Modifying the Configuration File
Next, we need to modify the virtual host configuration file to match our setup for the domain. Open the new configuration file.

    sudo nano /etc/apache2/sites-available/example.com.conf
When you open this file, you should be greeted with a message similar to this.

    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost

    DocumentRoot /var/www

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,

    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are

    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

Modifying this file to match the configuration for our domain name is easy. Firstly, remove the # symbol from in front of ServerName and add your domain in front of it. Doing so should make the line look exactly like this.

   ServerName mysite.com
If you want your site to be accessible from more than one name, with a www in the name for instance, you will want to add a ServerAlias line after the ServerName line.

   ServerAlias www.mysite.com
After you have followed the above steps, you will also need to modify the DocumentRoot line to match the directory you created for your domain name.

   DocumentRoot /var/www/mysite.com
After you have followed all these steps correctly, your file should look similar to this.

   ServerAdmin webmaster@mysite.com

   ServerName mysite.com

   ServerAlias www.mysite.com

   DocumentRoot /var/www/mysite.com
Those are all the changes you will need to make to this file. Now save and exit.

To activate the host, use this command.

   sudo a2ensite mysite.com
And now restart Apache to let your changes take effect.

   sudo service apache2 restart

Friday, December 12

Do you Know this About PHP ?

. Test Boolean Results with Switch. We all know that we can use switch to test cases, like this:

<?php

switch ($a) {

case 'a':
echo 'Yay it is A';
break;

case 'b':

echo 'Yahoo! Its B!';
break;
}
But did you know that you can test for Boolean values with a switch?
The trick is to use it as follows:
<?php

switch (TRUE) {

case ($a == 'A'):
echo 'Yay it is A';
break;

case ($a == 'B'):

echo 'Yahoo! Its B!';
break;
}
The principle might not hit you until you think about it, but once it does it's quite clear that switch can actually make things very simple for you if you use it in this way as well.



2. Variable Variables.

This is my favorite accidental find in programming. What it comes down to is that a variable can have a variable name. Where would you use something like this? Well, image we have a class name that is dependent on the url in some way. For the sake of simplicity I am going to fore-go filtering and validation and simply say
<?php
$class_name = $_GET['class_name'];

Now, let's assume that once we have the class name, we need to instantiate the class and the object name also needs to be the same as the class name. Thus we can say

$$class_name = new $class_name();
And therefore, if the value of $class_name is 'water', we will have an object named $water. See the power here?
Many developers consider it a hack. But with the right filtering and careful validation, in other words if you code it properly, it can work very well. PHP was built to be able to do this and you can apply it to function names, arrays, variables or objects.





3.Extract is your friend. Ever been in the situation where you need to say something like:


<?php
$name = $array['name'];
$surname = $array['surname'];
$message = $array['message'];

Then you may want to recall that you can use extract() to do the same.
Put simply, extract will remove the work behind this.
In this case, saying:

<?php
extract($array);

Will automatically make $name = $array['name'];
So, you can say "hello ".$name." ".$surname." Without do all of the declarations.
Of course, you always need to be mindful of validation and filtering, but there is a right way and a wrong way to do anything with PHP.

Losing transparency of png with php and imagemagick when rotation is applied?

re is working code for above problem.


<?php

    /* GD CODE */
        //save file
        $OutPutFileName = 'rotate_png.png';
        $angle=30;
        $left=10;
        $top=10;
       
        $png_image = imagecreatefrompng( 'source path/rotate_png.png' );
        $transparency = imagecolorallocatealpha( $png_image,0,0,0,127 );
        // rotate, last parameter preserves alpha when true
        $rotated = imagerotate( $png_image, $angle, $transparency, 1);
       
        // disable blendmode, we want real transparency
        imagealphablending( $rotated, false );
        // set the flag to save full alpha channel information
        imagesavealpha( $rotated, true );
       
        // now we want to start our output
        ob_end_clean();
        // we send image/png
        //header( 'Content-Type: image/png' );
        imagepng( $rotated, 'destination path/'.$FileName );
        // clean up the garbage
        imagedestroy( $png_image );
        imagedestroy( $rotated );
    /* End of GD CODE */
   
    /* Imagick CODE */
        //Let's read the images.
        $im = new Imagick();
        $im->readImage('source path/glass.jpg');
       
        $indexImg = new Imagick();
        $indexImg->readImage('destination path/'.$FileName);
       
        //Composite one image onto another
        $im->compositeImage($indexImg, Imagick::COMPOSITE_OVER, $left, $top);
       
        //Merges a sequence of images
    $im->flattenImages();
       
        //Save final Image
        $im->setImageFileName('destination path/final.jpg');
        // Let's write the image.
        if  (FALSE == $im->writeImage())
        {
            throw new Exception();
        }
        $im->destroy();
    /* End of Imagick CODE */

?>