Friday, 26 August 2011

Ajax Image Upload without Refreshing Page in PHP

PHP code for uploading images. Just five lines of JavaScript code, Using this you can upload files, image and videos.


Javascript Code
$("#photoimg").live('change',function(){})photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.  
 
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>

index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>

<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>

<div id='preview'>
</div>

Sample database design for Users.

Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)

ajaximage.php
Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention 
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB"; 
}
else
echo "Invalid file format.."; 
}
else
echo "Please select image..!";
exit;
}
?>

[+/-] Read More...

Image cropping in PHP


This script will allow you to make a smaller image of a bigger image, but at the same time crop it. This will prevent the image looking stretched and deformed.

We will create this using a class (Sorry using PHP 4 at the moment, but should work on 5)
Firstly lets set up the class.

PHP Code:
class cropImage{
 
//code here}  
Now we need to set up some variables to be used throughout the program.

PHP Code:
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;  
The variables above will be explained once we use them. Now we need to create the first function. This function will get the image we are going to crop, work out its dimension and then use them dimensions to work out how we are going to crop it.

PHP Code:

function setImage($image)
{
//Your Image
   
$this->imgSrc $image;
                     
//getting the image dimensions
   
list($width$height) = getimagesize($this->imgSrc);
                     
//create image from the jpeg
   
this->myImage imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
           
       if(
$width $height$biggestSide $width//find biggest length
       
else $biggestSide $height;
                     
//The crop size will be half that of the largest side
   
$cropPercent .5// This will zoom in to 50% zoom (crop)
   
$this->cropWidth   $biggestSide*$cropPercent;
   
$this->cropHeight  $biggestSide*$cropPercent;
                    
                     
//getting the top left coordinate
   
$this->= ($width-$this->cropWidth)/2;
   
$this->= ($height-$this->cropHeight)/2;
            
}  
Now we actually need to start creating the actual cropped image.

PHP Code:
function createThumb()
{
                   
  
$thumbSize 250// will create a 250 x 250 thumb
  
$this->thumb imagecreatetruecolor($thumbSize$thumbSize);

  
imagecopyresampled($this->thumb$this->myImage00,$this->x$this->y$thumbSize$thumbSize$this->cropWidth$this->cropHeight);
}  
Now all we need to do is render the image out.

PHP Code:
function renderImage()
{
                    
   
header('Content-type: image/jpeg');
   
imagejpeg($this->thumb);
   
imagedestroy($this->thumb);
}  
Now we just need to create the instance

PHP Code:
$image = new cropImage;$image->setImage($src);$image->createThumb();$image->renderImage();  
You can use this script to display a thumb of images on a new page, by using the following page.

PHP Code:
<img src="thumbcreate.php?src=images/largimg.jpg"//link to large image  
__________________

[+/-] Read More...

Thursday, 18 August 2011

How to converting numbers into words in PHP (upto one lakh)


Here is a way to convert numbers to words (upto one lakh). It can be extended as per your requirement as well. This is useful for billing etc. Note that only one parameter should be input, and not both. The second parameter is used only for some internal recursive calling.




<?php
function ConvertToWords($n, $followup='')
{
    if($n==0)
    {
        if($followup=='no')
        {
            return "";
            exit();
        }
        else
        {
            return "zero";
            exit();
        }
    }
    switch($n)
    {
        case 1: return "one"; break;
        case 2: return "two"; break;
        case 3: return "three"; break;
        case 4: return "four"; break;
        case 5: return "five"; break;
        case 6: return "six"; break;
        case 7: return "seven"; break;
        case 8: return "eight"; break;
        case 9: return "nine"; break;
        case 10: return "ten"; break;
        case 11: return "eleven"; break;
        case 12: return "twelve"; break;
        case 13: return "thirteen"; break;
        case 14: return "fourteen"; break;
        case 15: return "fifteen"; break;
        case 16: return "sixteen"; break;
        case 17: return "seventeen"; break;
        case 18: return "eighteen"; break;
        case 19: return "nineteen"; break;
        case 20: return "twenty"; break;
        case 30: return "thirty"; break;
        case 40: return "forty"; break;
        case 50: return "fifty"; break;
        case 60: return "sixty"; break;
        case 70: return "seventy"; break;
        case 80: return "eighty"; break;
        case 90: return "ninety"; break;
        case 100: return "one hundred"; break;
        case 1000: return "one thousand"; break;
        case 100000: return "one lakh"; break;
        default:
        {
            if($n<100)
            {
                return ConvertToWords(floor($n/10)*10, 'no')."-".ConvertToWords($n%10, 'no'); break;
            }
            elseif($n<1000)
            {
                return ConvertToWords(floor($n/100), 'no')." hundred ".ConvertToWords($n%100, 'no'); break;
            }
            elseif($n<100000)
            {
                return ConvertToWords(floor($n/1000), 'no')." thousand ".ConvertToWords($n%1000, 'no'); break;
            }
            elseif($n<10000000)
            {
                return ConvertToWords(floor($n/100000), 'no')." lakh ".ConvertToWords($n%100000, 'no'); break;
            }
            else
            {
                return "Something else"; break;
            }
        }
    }
}
?>

[+/-] Read More...

How to check Whether the URL valid or not in PHP


Whenever it is required to get some input url from user then the first things comes is checkwhether that url is working and valid or it is not working.

Here is a simple function which can be used to verify the liveness of the url.Just pass the url to this function and it will tell you whether the url is working and valid or invalid.In the function "check_url" we are going to open the given url with "fopen".If its opened then return true else return false.




<?php
//php function to check whether the url exists or not and validate it
function check_url($url)
{
$check = @fopen($url,"r"); // we are opening url with fopen
if($check)
 $status = true;
else
 $status = false;

return $status;
}
?>

Now we are going to use this function.you can pass the url from the GET or POST method to the function.Here we are going to specify it directly in the code.So we are asking our code to open the url http://www.techpdf.in with our function.



<?php
//$url = $_GET["url"]; // you can get the parameter from GET
$url = "http://www.techpdf.in";
if(check_url($url))
{
 echo "<div><a href=$url>$url</a> is a <b>valid</b> URL</div>";
}
else
{
 echo "<div><a href=$url>$url</a> is a <b>invalid</b> URL</div>";
}
?>


so after execution it will show the message as

http://www.techpdf.in is a valid URL.

[+/-] Read More...

How to List files of a Directory in php



You might require this code which lists all files from a specific directory in php. It shows the files from a folder you want.Even you can specify which files to ignore eg. when showing image you dont want to show thumbs.db file, so you can specify in the code neglect thumbs.db file.
So your code will show all files except thumbs.db 



<? php
$maindir = "." ; 
$mydir = opendir($maindir) ; 
$exclude = array("index.php","test.txt") ; 
while($fn = readdir($mydir)) 

if ($fn == $exclude[0] || $fn == $exclude[1]) continue; 
echo "
 \n <a href='$fn'>$fn</a>"; 

closedir($mydir); 
?>

[+/-] Read More...

Error while creating a cookie - Warning: Cannot modify header information


Are you getting this kind of error when creating a cookie or setting a cookie -

Warning: Cannot modify header information - headers already sent by (output started at e:\wamp\www\mysite\test.php:3) in e:\wamp\www\mysite\test.php on line 4

This error comes when some data is sent to the browser before setting the cookie.
So setcookie or setrawcookie function should be the first to be called means,

setcookie or setrawcookie function should be the first line on your page.

So if you use code like this

some html tags here or other contents or data

<?php
setcookie( "cookiename", "cookievalue", time()+3600);
?>

so the above code will give error.

So you should do following thing.


<?php
setcookie( "cookiename", "cookievalue", time()+3600);
?>


[+/-] Read More...

How to Extract Domain name from URL in PHP


Here is a simple function which can be used to parse the URL.

parse_url is a built in php function which can be used to parse url and get the type of request like whether its http or https or ftp, gives the domain name like www.google.com and path and the query.

eg. consider this url - http://www.chaprak.com/articles.php?cat_id=6

In http://www.chaprak.com/articles.php?cat_id=6 this url if you execute parse_url function then it will show the following result.

scheme - http
url - www.chaprak.com
path - /articles.php
query - cat_id=6


<?php
$url = "http://www.chaprak.com/articles.php?cat_id=6";
$parts = parse_url($url);
print_r($parts);


echo "
scheme - $parts[scheme]";
echo "
url - $parts[host]";
echo "
path - $parts[path]";
echo "
query - $parts[query]";
?>


[+/-] Read More...

Sunday, 14 August 2011

How to Rotate an Image Using PHP

Using the GD Library we can manipulate images in PHP. This script uses the imagerotate () function to rotate a photo. In our case we are rotating it 180 degrees but this can be changed in the script.


<?php
 // The file you are rotating
 $image = 'myfile.jpg' ;
 
 //How many degrees you wish to rotate
 $degrees = 180;
 
 // This sets the image type to .jpg but can be changed to png or gif
 header('Content-type: image/jpeg' ) ;
 
 // Create the canvas
 $source = imagecreatefromjpeg($image) ;
 
 // Rotates the image
 $rotate = imagerotate($source, $degrees, 0) ;
 
 // Outputs a jpg image, you could change this to gif or png if needed
 imagejpeg($rotate) ;
 ?>

Each line in the code is explained with comments. The most important part of this script, the rotating, is done with the imagerotate() function. The parameters of this function are: imagerotate (The_image, degrees_to_rotate, background_color, Optional_ignore_transparency). If the optional ignore transparency is blank or 0, then the transparency is preserved.

[+/-] Read More...

Blocking php curl from scraping website content

Here is the function for Blocking php curl from scraping website content


function disguise_curl($url)
{
	$curl = curl_init(); 

	// setup headers - used the same headers from Firefox version 2.0.0.6
	// below was split up because php.net said the line was too long. :/
	$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
	$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
	$header[] = "Cache-Control: max-age=0";
	$header[] = "Connection: keep-alive";
	$header[] = "Keep-Alive: 300";
	$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
	$header[] = "Accept-Language: en-us,en;q=0.5";
	$header[] = "Pragma: "; //browsers keep this blank. 

	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3)

	curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
	curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
	curl_setopt($curl, CURLOPT_AUTOREFERER, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_TIMEOUT, 10); 

	$html = curl_exec($curl); //execute the curl command
	if (!$html)
	{
		echo "cURL error number:" .curl_errno($ch);
		echo "cURL error:" . curl_error($ch);
		exit;
	}

	curl_close($curl); //close the connection 

	return $html; //and finally, return $html
}

[+/-] Read More...

How to use the Google Maps API with PHP


The Google Maps API are a very useful system to get geographic information. Maybe you are thinking cool! but i’m not a GIS developer so why i need to continue to read this post? Let me do an example. Scenario: you have to check the validity of the geo data of a list of customers stored into a database. Using the Google Maps API you can easly compare the data stored into your database with the google data and fix the errors.
In this post i propose a PHP class that uses the Google Maps API to provide geographic information from a generic address (city, country,street+city, etc). This class is named GMaps and in the follow there is a use case:

require_once 'GMaps.php';</p>
// Your google key
$google_key = '';

if (!empty($_POST)) {
$search= strip_tags($_POST['search']);
}
echo '<form action="example.php" method="post">';
echo '<input name="search" type="text" />';
echo '<input type="submit" value="Get geographic data!" />';
echo '</form>';
<p style="text-align: justify;">if (!empty($search)) {
// Get the Google Maps Object
$GMap = new GMaps($google_key);
if ($GMap->getInfoLocation($search)) {
echo 'Address: '.$GMap->getAddress().'<br>';
echo 'Country name: '.$GMap->getCountryName().'<br>';
echo 'Country name code: '.$GMap->getCountryNameCode().'<br>';
echo 'Administrative area name: '.$GMap->getAdministrativeAreaName().'<br>';
echo 'Postal code: '.$GMap->getPostalCode().'<br>';
echo 'Latitude: '.$GMap->getLatitude().'<br>';
echo 'Longitude: '.$GMap->getLongitude().'<br>';
} else {
echo "The response of Google Maps is empty";
}
}
To use the GMaps class we initialize it with a valid Google key (line 16) and we get the geographic information with the method getInfoLocation (line 17), that’s it!Here you can download the class GMaps.php with this example (GMaps.zip).
In order to execute the class you must have a valid Google API key. If you don’t have this key you can generate a new one here (every key is related to a specific url of your application).

[+/-] Read More...

what is Use of WSMessage in PHP Web Services


In a Web services invocation, there are two messages involved, for two way operations. One is the request message and the other is the response message. WSMessage class in the Web services framework for PHP is used to represent these messages.
The str member variable of the WSMessage class can hold the the message content, termed as payload, as an XML string.
If you are sending a request, form a client, you can fill in the request WSMessage instance with the XML payload and send it. The received response payload will be stored in a WSMessage instance as an XML string and returned to client.
If you are receiving a request, form a service, the received request payload will be contained in a WSMessage instance. You can process the request, prepare the response, store it in a WSMessage instance and return that instance.
WSMessage is more useful when sending and receiving attachments than when dealing with simple messages. We will look how to leverage WSMessage in case of attachments in the future.

[+/-] Read More...

PHP Soap Example


Discover what soap (data) services are available on the soap server.

/**
* figure out what soap functions and types are available
* @param object $client Soap Client
* @returns string $Response soap result
*/
public function fun_NWMLS_getSoapInfo()
{
        $WSDL = $this->WSDL; //class field, 'URL'

        $client = new SoapClient($WSDL, array('trace' => 1) ); //trace for getLastResponse();

        //debug (and figuring out what to do!)
        //get functions and params
        var_dump($client->__getFunctions());
        var_dump($client->__getTypes());

        $Response = $client->__getLastResponse();

        echo "\n\n\n";
        echo "Response:$Response\n";
        echo "\n\n\n";

        //debug
        //echo "REQUEST:\n" . $client->__getLastRequest() . "\n"; //Shows query just sent
        //echo "RESPONSE:\n" . $client->__getLastResponse() . "\n"; //gets the data

        return $Response;
}//end fun_NWMLS_getSoapInfo

Get Soap Response

How I get the NWMLS data
/**
* get NWMLS Data
* @param string $WSDL - soap url
* @param string $XMLQuery - query to send the nwmls
* @returns 
*/
private function fun_NWMLS_getSoapResponse($XMLQuery, $DataType = "RetrieveListingData")
{
        global $XmlQueryRef, $client, $intTimeStamp;

        $WSDL = $this->WSDL;
        $this->DataType = $DataType; //used in mysql import

        //debug
        echo "DataType:($DataType):XMLQuery\n";
        echo "XMLQuery:($XMLQuery):XMLQuery\n";
        echo "Soap:[[";
        
        if (!$XMLQuery)
        {
                $str = "\n error in fun_NWMLS_getSoapResponse: No XMLQuery($XMLQuery)\n";
                die($str);
        }

        if (!$DataType) //this is parameter no xml query
        {
                $str = "\n error in fun_NWMLS_getSoapResponse: No DataType($DataType)\n";
                die($str);
        }

        //Start the soap connection
        if (!$client)
        {
                $client = new SoapClient($WSDL, array('trace' => 1) ); //trace for getLastResponse();
                echo "Conn:YES";
        }
        else
        {
                echo "Conn:NO";
        }

        //nwmls xml query stirng                
        $params = array ('v_strXmlQuery' => $XMLQuery); //setup the parameters of the function/method that we are going to request arresponse to

        echo "Params:"; 

        if (in_array($DataType,$XmlQueryRef['DataType']))
        {
                try 
                {
                        echo "try func:TimeStamp1:($intTimeStamp)";
                        $result = $client->$DataType($params); //submit function type with xml query as param
                }
                catch (SoapFault $soapFault) 
                {
                        if ($soapFault)
                        {
                                echo "\n\nSoap Fail:TimeStamp2:($intTimeStamp)\n";
                                //var_dump($soapFault);
                                echo "\n\nRequest :\n", $client->__getLastRequest(), "\n\n";
                                echo "Response :\n", $client->__getLastResponse(), "\n\n";
                                //die("\n\nearly death in soap request\n\n");
                        }
                        else
                        {
                                echo "Soap Success:Returning Response:TimeStamp2:($intTimeStamp)\n";
                        }
                }
        }

        //this will prolly error on its on if fault is thrown
        $Response = $client->__getLastResponse();

        //debug
        //echo "REQUEST:\n" . $client->__getLastRequest() . "\n"; //Shows query just sent
        //echo "\nResponse:$Response\n\n\n\n";
        //die("\n\nearly death -> soap Response\n\n");
                
        //debug
        //die("\n\nwhat the\n\n");
        if (!$Response)
        {
                echo "\nSoap:No Rresponse\n";
        }

        echo "]]:Soap";

        return $Response;
}//fun_NWMLS_getSoapResponse

[+/-] Read More...