Wednesday, 6 August 2014

Solving the Forbidden access Error of wamp server in windows8

When you installed your wamserver in your windows8 Pc & tried accessing localhost you may gone through an error like this.
Inorder to resolve this problem, please follow the following steps.

1) Click on the wampserver tray icon. From it click on Apache-> htppd.conf

Open the file in edit mode then.

Find these lines

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

Change it to


<Directory />
     Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    Allow from all
</Directory>



2)Find another line in the same file

#   onlineoffline tag - don't remove
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1

change it as

#   onlineoffline tag - don't remove
    Order Deny,Allow
    Allow from all
    Allow from 127.0.0.1


3)Now your server will be working. But when you try to access the phpmyadmin,it will show error.

So inorder to rectify it, we have to make changes in phpmyadmin config file. So for this :-
explore to \wamp\alias\phpmyadmin.conf
Open this file and find this code

<Directory "c:/wamp/apps/phpmyadmin3.4.10.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1

</Directory>

change it to

<Directory "D:/Server/wamp/apps/phpmyadmin3.4.10.1/">    Options Indexes FollowSymLinks MultiViews    AllowOverride all        Order Deny,Allow Allow from all</Directory>

Now you can see that everything is working fine..




Wednesday, 14 May 2014

Sending Emails with attachment using SMTP Server

When we do large projects in php, we have to send emails to users and admins to give some notification to them. In Php projects most of the people use the default mail function .It is very easy to use and will work Perfectly. But the problem is that the mail may go to spam or junk folder. So many users may not notice these mails. So Inorder to get rid of it, we have to use SMTP mails. So it will not go to junk folders.
In this Post Iam explaining how to send SMTP mails from your Server. It is very simple and easy to integrate.

For doing this, first you have to make sure that PEAR mail package is enabled on your server. If not please install it. It is free to intsall. If you didn't know how to manage extensions in server just ask server service provider to do it for you.

Now download PEAR mail script from here

Now place it your folder where the mail script resides.
 Place this script to the sending portion of your script.
<?php
require_once "Mail.php"; //includes all mail library for smtp mails
include 'Mail/mime.php' ; // includes mime library for sending multimedia mails with attachment
include('Mail/mail.php');     // adds the enhanced send function 
$from = "<".$frommail.">";
$to = "<".$toemail.">";

$body = $description;

$host = "hostname";
$port = "25";
$username = $usernamea;
$password =$password;

$crlf = "\r\n"; 
$mime = new Mail_mime($crlf); 
$mime->setHTMLBody($description); 
$ds          = DIRECTORY_SEPARATOR;  //1

 //attaching images/docs in mail
if (!empty($_FILES) && isset($_FILES)) {

for($k=0;$k<count($_FILES);$k++){


 $name=$_FILES['attachment']['name'][$k];
 $size=$_FILES['attachment']['size'][$k];
$tmpname=$_FILES['attachment']['tmp_name'][$k];
$uploader->uploadmultiFile($name,$size,$tmpname);// my own function call just leave it.. its image storing code
$image      =   $uploader->getUploadName();

    $tarfil='../upload/'.$image;
$mime->addAttachment($tarfil, 'text/plain'); // adding attachment to mail
}

     
}


$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);

$body = $mime->get(); 
$hdrs = $mime->headers($headers);

$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $hdrs, $body);
if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
 } 
?>

Try it and have fun.. have a great day :-)

Monday, 12 May 2014

Generating PDF in PHP using mPDF

When you work on large inventory projects in php, there may araise situation where you have to generate pdf dynamically for reports and all. So here Iam explaining about a simple php to PDF library named mpdf.
you can download it from here.
Now please download the latest version of the mpdf library and place it in your root folder of your project.
Here with the help of mpdf  you can generate pdf according to various styles using css. You can include css also using this library.

Now i will provide a sample code for generating report using mpdf.


<?php

// fetching data from database.. You can use your own methods
include("db.php");
$id=$_GET['id'];
$quo=new Quotation();
$orders=$quo->getuserquotations($id);
$orderdet=$quo->getdetails($id);
$prd=new Product();/
$amount=0;

//we have to save our design in this $html variable
$html = '
<h1>Report Detail</h1>
<p style="color:green"> Description here </p>
</br>';
$html.='<p><strong>Attn </strong>: Mr/Ms &nbsp;';
$html.=$orderdet[0]['name'];
$html.='&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Email</strong>:&nbsp;';
$html.=$orderdet[0]['email'];
$html.='</p>';
$html.='<p><strong>Mobile</strong>:  &nbsp;';
$html.=$orderdet[0]['mobile'];
$html.='&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;<strong>Tel</strong>:&nbsp;';
$html.=$orderdet[0]['phone'];
$html.='</p>';
$html.='<p><strong>Fax</strong>:  &nbsp;';
$html.=$orderdet[0]['fax'];
$html.='&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;<strong>Date</strong>:&nbsp;';
$html.=$orderdet[0]['date_booked'];
$html.='</p>';

$html.='<table border="1"><tbody>
<tr> <td><strong>Sr No. </strong></td><td><strong>Product Image </strong></td><td><strong>Description </strong></td><td><strong>QTY </strong></td> <td><strong>Rate </strong></td> <td><strong>Amount </strong></td> </tr>';
for($i=0;$i<count($orders);$i++){
$productid= $orders[$i]['prod_id']; 
     $proddet=$prd->getdetails($productid);

     $tt= $orders[$i]['qty']*$orders[$i]['price']; 
     $amount=$amount+$tt;
$html.='<tr><td>';
$html.=$i+1;
$html.='</td><td><img src="../upload/';
$html.=$proddet[0]['product_img'];
$html.='" width="150px"></td><td>';
$html.=$proddet[0]['description'];
$html.='</td><td>';
$html.=$orders[$i]['qty'];
$html.='</td><td>';
$html.=$orders[$i]['price'];
$html.='</td><td>';
$html.=$tt;
$html.='</td></tr>';
}

$html.='<tr><td></td> <td></td> <td></td> <td></td> <td>Total:</td> <td><span style="color:red">'.$amount.'</span>/-</td> </tr>';


$html.='
</tbody></table>
<p>&nbsp;</p>
';
// $html variabl ends here...

//now its time to include our library and generate report
include("mpdf.php");

$mpdf=new mPDF('c','A4','','',32,25,27,25,16,13); 

$mpdf->SetDisplayMode('fullpage');

$mpdf->list_indent_first_level = 0; // 1 or 0 - whether to indent the first level of a list

// LOAD a stylesheet
$stylesheet = file_get_contents('mpdfstyletables.css');
$mpdf->WriteHTML($stylesheet,1); // The parameter 1 tells that this is css/style only and no body/html/text
$mpdf->SetJS('this.print();'); // will print the pdf
$mpdf->WriteHTML($html,2);
$ext="pdf";
$savename="quote-".substr(md5(rand(1111,9999)),0,8).".".$ext;
$mpdf->Output($savename,'I'); // will display pdf to you in browser
exit;
?>
If you use

$mpdf->Output($savename,'D');

it will download the pdf to your computer.

If you use
$mpdf->Output($savename,'F');

it will download pdf to your local folder..you can set the path $savename variable

If you use
$mpdf->Output($savename,'I');
it will display pdf in your browset window itself..

Wednesday, 9 April 2014

Saving PHP Code in MYSQL database and executing the Code

In my latest project I got a task to save php code as it is into the mysql database and execute it on the userside by fetching from the database. If we use the normal method of saving and retreiving it will Fail because Php syntaxed code can't be saved as it is because it may break the sql code . So we have to use two php built in functions to make it possible.
 mysql_real_escape_string($string);
This function is used to save Php syntaxed code to the database without sql code breaking.

eval($string);
This function is used to excute the fetched content as php code.

Because normally If we retrive value from databse using normal method it only consider the result as a string and will display the whole php code without executing it. But thie eval() function will make it executable as our normal php code.

So Before trying to save Php code we have to know about eval() function and What should be the input given to it for its successful exceution.

For its successful execution we have to give it an input like
 for eg:


 echo $compname; 
 echo '|';
 echo $country; 
 echo '|';
 echo $state; 
 echo '|';
 echo $city; 
 echo '|';
 echo $location; 


Every string should be a php type code ending with semicolon. and for strings don't forget to put  opening and closing apostrophies :-

echo 'string';

So just give this above type text for saving and while saving use
$datatosave= mysql_real_escape_string($string);
$query="insert query here"//;
to save to database.

And during retreiving for eg:-


$query="Select query to retreive";
$row=mysql_fetch_assoc($query);
$description=$row['description'];

Dont  forget to assign values to variables which we have given in the php code:-
$compname,$country,$state,$city,$location.etc:_

If we assign values to these variables like:

$compname="Mycompany";
$country="India";
$state="Kerala";
$city="Alleppey';
$location="Nedumudy";

Then it is executed like :

<?php  echo eval($description);  ?>

You will get the php variables executed. and result will be like:

Mycompany|India|Kerala|Alleppey|Nedumudy


Hope you Understand it... have a great day ;-)






Thursday, 20 March 2014

Using MEMCACHE for caching PHP Website for increasing Website Speed

In the case of  Large dynamic websites, it may become slower for some pages where it has to fetch large data from the database. So Solution in PHP is using the PHP cache methods.
Their are many cache tools available for php sites. Some of them are:-


  • APC 
  • Xcache
  • Memcache
  • E Accelerator .etc.
In this Post I will explain how to use memcache & its basic functions. I know that their are many vast tutorials explaining this but am just trying to figure out basic functions for new programmers.
Try to install memcache in your windows or linux or Mac by any methods. Iam not covering the installation process here.So I hope that your memcache is installed in your system & you are ready for the magic.


Many common processes utilized in web application development (for example generating large amounts of HTML or fetching data via complex SQL queries) are processor and disk intensive. Serializing and caching the generated data to disk solves the first of those problems, but you still get a small performance hit each time you read the data to disk, plus you have to write routines to automatically purge old cached data. 
Memcached solves this problem for you by letting you write frequently accessed data directly to RAM, where it can be fetched almost instantaneously; plus you can tell memcached how long to store the cached data and it will automatically purge stale data without any further intervention from you, the programmer. 
Many web sites & applications such as Facebook, LiveJournal, Flickr, Slashdot, WikiPedia/MediaWiki, SourceForge, Digg and Twitter use memcached to enhance their performance. 

What is Memcached? 
Memcached (Memory Cache Daemon) was developed by the team at LiveJournal to improve performance of their social blogging site by minimizing the impact of the bottleneck caused by reading data directly from the database. Memcached is a server that caches Name Value Pairs in memory. The “Name”, or key, is limited to 250 characters, and the “Value” is limited to 1MB in size. Values can consist of data, HTML 
Fragments, or binary objects; almost any type of data that can be serialized and fits in memcached can be stored.

Drawbacks/Limitations to Memcached 
• Memcached is not a persistent data storage mechanism. The data cannot be 
queried SQL-style or dumped to disk; the only way to access the information in Memcached is retrieve the data from the server via the correct key (or “Name”) for the information stored. There is no fail-over/high availability support; if a memcached server goes down or the service is restarted, the data is gone. 
• In many cases there is much less RAM available than disk space, so the amount of 
memory you can dedicate to memcached is more than likely fairly limited. 
• Things like resource variables (file handles, etc.) and internal PHP classes cannot 
be stored using memcached, because they cannot be serialized.


Initializing memcache


PHP provides both procedural and object-oriented interfaces to memcached. My 
examples will use the object-oriented interface. If you're interested in using the 
procedural interface, consult the PHP manual (http://www.php.net/memcache). 
We'll assume that our memcached instance is listening on localhost on port 12345. 
 $cache = new Memcache(); 
$cache->connect('localhost', 12345);

Before you start storing data, you'll want to make sure that you actually were able to 
connect to the memcached instance. 
 if ($cache->getServerStatus() == 0) die('Could not connect to 
 memcached!'); 

In memcache you have the power to add more than one server, so we can add server by:-

$cache->addServer('mem1.domain.com'1121133);$cache->addServer('mem2.domain.com'1121167);

Or Adding servers using an array

$servers = array(
    array(
'mem1.domain.com'1121133),
    array(
'mem2.domain.com'1121167)
);
$cache->addServers($servers);

But in this case if we didn't check before adding The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

So we can code something Like this :-
$server=$cache->getServerList();


foreach ($servers as $server) 
       if($server['host'] == $host and $server['port'] == $port) //checking whether server already added
               //already exist
//code here 
                } 
But Since we are talking about only one server our previous connect method is enough.


Flush all cache data

You may also at some point want to flush the cache without restarting the service: 
 $cache->flush();


Storing Data 
The next step is to actually store some data in the memcached instance. Each bit of data you store will be identified by a unique "key." You'll need to be sure that you don't use the same key to store two different bits of data; if you do, the second bit will overwrite the first, as you might expect. 
 $mydata = array( 
'user_id' => 1234,
 'fullname' => 'John Doe',
 'phone' => '(123) 234-3456' 
); 
$cache->set('my-memcached-key', $mydata, MEMCACHED_COMPRESSED, 
 1500); 
$cache->set('uncompressed-data', 'Just a string ...', null, 0); 
Now you've stored the contents of $mydata in the cache! 
The third and fourth options in the set() method specify whether or not to compress the cached data using zlib (use null for no compression) and how long in milliseconds to keep the cached data (use 0 for no expiration) respectively. Remember that setting no expiration date doesn't mean that the data will be cached forever ... if memcached runs out of memory it will start to remove old data, even data with no expiration date. 

Retreiving and Replacing Data

Retrieving cached data is very straightforward; you do need to remember to let 
memcached know if the data you are fetching was compressed. 
 echo $cache->get('my-memcached-key', MEMCACHED_COMPRESSED); 
echo $cache->get('uncompressed-data'); 
If you want to replace cached data, you've got two options. First, you can use the 
Memcache::replace() function, which will return false and not store your data if the 
cache key does not exist, or you can use Memcache::set(), which will replace the data if 
it exists, and store the value if it does not exist. 
 $cache->replace('uncompressed-data', 'New Value', null, 1500); 
or $cache->set('uncompressed-data', 'New Value', null, 1500); 

But In my opinion using set is more secure than using replace.

Deleting data

Deleting data is also straightforward ... 
 $cache->delete('my-memcached-key');


Incrementing and Decrementing Numeric Values 
Memcached also provides the Memcache::increment() and Memcache::decrement() 
methods for increasing or decresing the value of cached numeric values by a certain 
value. These funtions will NOT create the value if it does not exist, though. 
 $cache->set('connection-count', 1, null, 60000); $cache->increment('connection-count', 1); 
$cache->decrement('connection-count', 1); 

To append data to a variable

For adding data to a already existing cache method,we can use append method.
For eg: if we set variable name like:-

$cache->set('varname',$data);
$cache->append('varname',$moredate);


Sample Usage of memcache

$cache=new Memcache();
$cache->connect('localhost',1235);
$ip=$cache->get('data');
if(!$ip){
if($cache->getResultCode()==Memcached:RES_NOTFOUND){
$data_db=getdata();// fetch data from db
$cache->set('data',$data_db);

}
}else{
$ip=$cache->get('data');
echo $ip;

}


Wednesday, 19 March 2014

Using PDO in MYSQL PHP project

PDO stands for PHP data Objects.PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms.
PDO supports many of the popular databases as seen on the list below.

  • DBLIB: FreeTDS / Microsoft SQL Server / Sybase
  • Firebird (http://firebird.sourceforge.net/): Firebird/Interbase 6
  • IBM (IBM DB2)
  • INFORMIX - IBM Informix Dynamic Server
  • MYSQL (http://www.mysql.com/): MySQL 3.x/4.0
  • OCI (http://www.oracle.com): Oracle Call Interface
  • ODBC: ODBC v3 (IBM DB2 and unixODBC)
  • PGSQL (http://www.postgresql.org/): PostgreSQL
  • SQLITE (http://sqlite.org/): SQLite 3.x
In this Tutorial I will explain about PDO and its usage in MYSQL.

1. Connection with database

<?php
/*** mysql hostname ***/$hostname 'localhost';

$dbname
= 'mytable';/*** mysql username ***/$username 'username';
/*** mysql password ***/$password 'password';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database';
    }
catch(
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>


2. For Closing database connection
Just set the connection variable to null

 $dbh null;


3. For Executing Query statements like INSERT,UPDATE,DELETE

<?php  
//Insert query  
$query="INSERT INTO tablename(fieldname, fieldname) VALUES ('value1', 'value2')";
//Update query
$query="UPDATE tablename set fieldname='value' where condition";
//Delete query
$query="DELETE FROM table where condition;

 $dbh->exec($query);

    
/*** echo the number of affected rows ***/
?>


4. Executing query statements like SELECT

/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM animals";
    foreach (
$dbh->query($sql) as $row)
        {
        print 
$row['value1'] .' - '$row['value2'] . '<br />';
        }



FETCH Modes


  • FETCH ASSOC



To fetch an associative array from our results the constant PDO::FETCH_ASSOC is used and returns the column names as indexes or keys of the resulting array

$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_ASSOC);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }



  • FETCH NUM



Like PDO::FETCH_ASSOC, the PDO::FETCH_NUM produces a numerical index of the result set rather than the field names.


/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_NUM);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }



  • FETCH BOTH



There may be times you need to fetch both numerical and associative indexes. PDO::FETCH_BOTH produces a numerical and associative index of the result set so you can use either, or both.


/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_BOTH);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }


5. For getting last insert Id


    $dbh->exec("INSERT INTO tablename(fieldname,fieldname) VALUES ('value1', 'value2')");

    
/*** display the id of the last INSERT ***/
    
echo $dbh->lastInsertId();


I have covered only basic things about PDO. Hope that this post is helpful to some people...

Speed Up your Website by Enabling Browser cache

When you create a website,the main success factor of that website would be its speed. But however we tried to increase a website speed it takes some default time to load a page. Here am trying to explain about 
Browser caching.
Before moving to the tricks,I will explain what is browser caching?? and what is the significance of it??
When a web browser displays your webpage it has to load several things like your logo, your CSS file, and other resources.

What browser caching does is "remember" the resources that the browser has already loaded. This means that when a visitor goes to another page on your website it does not have to go get your logo or CSS file again, because it already has it "remembered". The end result of this is that your pages load much faster.

If you have tested your webpage for speed and found out that you need to use browser caching, here is how you do it.

To acheive this you have to write something in your htaccess file.
Open your htaccess files and add lines below:-

</IfModule>

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType text/js "access plus 1 year"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>

Here You can set its expire period too.
Change the period you want after access plus . For eg: access plus 1 month, access plus 1 week, access plus 1 year are vaild statements.

Save your htaccess file and refresh the page. 


Monday, 17 March 2014

Generating Picture Thumbnails in Virtual domains

During my Previous project, I got a situation where I have to generate thumbnail images in a virtual subdomain. Many thumbnail function we use will fail to work when it is used in virtual subdomains.
I didn't want to confuse you with my techie language. Let me explain with an eg:-
Consider a project of blogger, Where users can create their own user urls. Like litto.blogger.com, kevin.blogger.com. etc. Actually these subdomain urls are not created anywhere whereas it is redirected to a particular code or folder via htaccess. and it will continue executing from their. but the url remains the same. This is known as virtual url & virtual subdomain.
So when we want to display images in these domains we have to give absolute urls. Like Normally in php websites we give image url like ../upload/imagename.png. But Here we have to give url like http://sitename.com/upload/imagename.png.

So When we use normal thumbnail script for this images it will show error & will not generate. So In thsi situation what we can do is:-
1) During page reloading download the image to domain s local folder as thumbnails and show this images.

So here I tried it and I suceeded in it.
If you want it you can also gave it a try.


First step :- 1)Function to resize image & download it to local server
Name it as resize_image.php & include it in your server

<?php
/**
 * easy image resize function
 * @param  $file - file name to resize
 * @param  $width - new image width
 * @param  $height - new image height
 * @param  $proportional - keep image proportional, default is no
 * @param  $output - name of the new file (include path if needed)
 * @param  $delete_original - if true the original image will be deleted
 * @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
 * @param  $quality - enter 1-100 (100 is best quality) default is 100
 * @return boolean|resource
 */
  function smart_resize_image($file,
                              $width              = 0,
                              $height             = 0,
                              $proportional       = false,
                              $output             = 'file',
                              $delete_original    = true,
                              $use_linux_commands = false,
                                $quality = 100
           ) {
     
    if ( $height <= 0 && $width <= 0 ) return false;

    # Setting defaults and meta
    $info                         = getimagesize($file);
    $image                        = '';
    $final_width                  = 0;
    $final_height                 = 0;
    list($width_old, $height_old) = $info;
    $cropHeight = $cropWidth = 0;

    # Calculating proportionality
    if ($proportional) {
      if      ($width  == 0)  $factor = $height/$height_old;
      elseif  ($height == 0)  $factor = $width/$width_old;
      else                    $factor = min( $width / $width_old, $height / $height_old );

      $final_width  = round( $width_old * $factor );
      $final_height = round( $height_old * $factor );
    }
    else {
      $final_width = ( $width <= 0 ) ? $width_old : $width;
      $final_height = ( $height <= 0 ) ? $height_old : $height;
      $widthX = $width_old / $width;
      $heightX = $height_old / $height;
     
      $x = min($widthX, $heightX);
      $cropWidth = ($width_old - $width * $x) / 2;
      $cropHeight = ($height_old - $height * $x) / 2;
    }

    # Loading image to memory according to type
    switch ( $info[2] ) {
      case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
      case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
      case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
      default: return false;
    }
   
   
    # This is the resizing/resampling/transparency-preserving magic
    $image_resized = imagecreatetruecolor( $final_width, $final_height );
    if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
      $transparency = imagecolortransparent($image);
      $palletsize = imagecolorstotal($image);

      if ($transparency >= 0 && $transparency < $palletsize) {
        $transparent_color  = imagecolorsforindex($image, $transparency);
        $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);
      }
      elseif ($info[2] == IMAGETYPE_PNG) {
        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);
      }
    }
    imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
   
   
    # Taking care of original, if needed
    if ( $delete_original ) {
      if ( $use_linux_commands ) exec('rm '.$file);
      else @unlink($file);
    }

    # Preparing a method of providing result
    switch ( strtolower($output) ) {
      case 'browser':
        $mime = image_type_to_mime_type($info[2]);
        header("Content-type: $mime");
        $output = NULL;
      break;
      case 'file':
        $output = $file;
      break;
      case 'return':
        return $image_resized;
      break;
      default:
      break;
    }
   
    # Writing image according to type to the output destination and image quality
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
      case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
      case IMAGETYPE_PNG:
        $quality = 9 - (int)((0.9*$quality)/10.0);
        imagepng($image_resized, $output, $quality);
        break;
      default: return false;
    }

    return true;
  }
?>


Step 2: Include it in your file:-

<?php include("resize_image.php");          ?>


Step 3: Loop the images in file


<?php
      while($rows=mysql_fetch_array($sql_p))
      {
$loc=$rows['photo_loc'];
$filenameIn  = "http://yoursite.com/upload/".$loc; // Give the images actual url
$filenameOut = __DIR__ . '/images/' .$loc; // Give here where image to be downloaded  your virtual domain folder
$out="http://yoursite.com/user/template/adv001/images/".$loc;// Full path of image in virtual domain
//$contentOrFalseOnFailure   = file_get_contents($filenameIn);
//$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
$file = $filenameIn ;

//indicate the path and name for the new resized file
$resizedFile = $filenameOut;

//call the function
smart_resize_image($file , 150 , 150 , false , $resizedFile , false , false ,100 );
      ?>
                      <li>  <img src="http://<?php echo $server_name; ?>/user/template/adv001/images/<?php echo $rows['photo_loc'];?>" alt="" width="150px" height="150px">  </li>
              
<?php } ?>