Showing posts with label Php. Show all posts
Showing posts with label Php. Show all posts

Friday, March 19, 2010

Truncate text using php

[sourcecode language="php"]
<?php
function truncate($string, $length='' , $k = ''){
if( $length == '') $length = 50;
if( $k == '') $k = '...';
settype($string, 'string');
settype($length, 'integer');
for($a = 0; $a < $length AND $a < strlen($string); $a++){
$output .= $string[$a];
}
if( strlen($string) > $length)
$output .= $k;
return($output);
}
?>
[/sourcecode]
truncate text using php


$my_string = 'I am kajal Mondol.I live in Kolkata.';
echo truncate($my_string);
echo truncate($my_string,10);
echo truncate($my_string,10,',,,');

This will output:

I am kajal Mondol.I live in Kolkata.
I am kajal...
I am kajal,,,

This function truncates a variable to a character length, default is 50.
'...' is the default text to append if truncation occurs.
Second parameter determines how many characters to truncate to.

Thursday, March 4, 2010

Function to create GD thumbnail using Php

function thumbnail($src,$destimagename,$dimension)
{
$src_path=explode("/",$src);
$name=$src_path[count($src_path)-1];
array_pop($src_path);
$oldpath=implode("/",$src_path);
$newpath=$oldpath;
$newpath=$newpath."/".$destimagename;

if(copy($src,$newpath))
{
$name_extension=substr($name,strrpos($name,".")+1);
if (preg_match("/gif/i",$name_extension))
{
$src_img=imagecreatefromgif($newpath);
}
if (preg_match("/jpg|jpeg/i",$name_extension))
{
$src_img=imagecreatefromjpeg($newpath);
}
if (preg_match("/png/i",$name_extension))
{
$src_img=imagecreatefrompng($newpath);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

$thumb_w = $dimension;
$thumb_h = floor(($old_y/$old_x) * $dimension);

$dst_img=@ImageCreateTrueColor($thumb_w,$thumb_h);
@imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

if(preg_match("/png/i",$name_extension))
{
@imagepng($dst_img,$newpath);
}
if(preg_match("/jpg|jpeg/i",$name_extension))
{
@imagejpeg($dst_img,$newpath);
}
if(preg_match("/gif/i",$name_extension))
{

@imagegif($dst_img,$newpath);
}
@imagedestroy($dst_img);
@imagedestroy($src_img);

}

}

Wednesday, March 3, 2010

PHP Headers and Popular Mime Types

Atom


header('Content-type: application/atom+xml');

Javascript


header('Content-type: text/javascript');

JPEG Image


header('Content-type: image/jpeg');

PDF


header('Content-type: application/pdf');

XML


header('Content-type: text/xml');

RSS


header('Content-Type: application/rss+xml; charset=ISO-8859-1');

CSS


header('Content-type: text/css');

Create Backup of MySQL Database Using PHP

[sourcecode language="php"]
<?php

$dbName = "db_name";

$dbhost="localhost";

$dbuser="root";

$dbpass="";

$backupFile = $dbName . date("Y-m-d-H-i-s") . '.gz';

$command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbName | gzip > $backupFile";

system($command);

header('Content-disposition: attachment; filename='.$backupFile);

header('Content-type: application/x-gzip');

readfile($backupFile);

?>
[/sourcecode]

Tuesday, February 23, 2010

Fatal error: Allowed memory size of 8388608 bytes exhausted.

Fatal error: Allowed memory size of 8388608 bytes exhausted.

Sometime PHP script may returns the above error. Normally this error is generated when your script exhausted and used up the default memory requirement of 8 MB memory allocation.

* Default memory limit is set in php.ini file ( php configuration file.)
* memory_limit = 8M;

How can we manage with the memory problems comes in some php scripts?
you should check following things when such kind of memory errors occurs in your script.

1. check the default memory_limit variable in your php.ini file.
memory_limit = 8M;
you can change this memory limit and again check for the error.

a. Edit in php.ini

memory_limit = 12M;
restart the apache service.



b. code Level
@ini_set('memory_limit', '12M');



c. htaccess
php_value memory_limit 12M
___________________________________________________________________

2. If the error is not resolved after above step, then you should start debugging your code in order to find out the reason of memory limit exceed.
You have to first find out at what position in your code the memory limit is exceeding. you can use the php's built in function for this purpose.

Function description

memory_get_usage — This function returns the amount of memory allocated to PHP.

Syntax : int memory_get_usage ( true / false );

It returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

Set the option to this function to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is returned.

How to use this function

1. Write this code ( echo memory_get_usage( true ); ) repeteadly after some no of lines.
2. Run it in browser
3. Compare the counts given by each echo and you can check which block of your code needs extra memory.
4. Once you identify the block of code which needs extra memory then you can start deallocating the unused memory spaces allocated by some unused variables and some infinite loops.
5. use following wherever necessary.
a. unset($var_name);
b. mysql_free_result($result_set); — Free result memory
c. Look for include("file.php") in loops, by mistake.
Just try to free the memory everywhere if the variable / array is no longer used.
6. Best of luck.


Function description

bool
mysql_free_result ( resource $result )
It frees all the memory associated with the result identifier result .

Object Oriented Programming with PHP




Object Oriented Programming With PHP 5 #1[gigya width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=oop1-090302214803-phpapp02&stripped_title=object-oriented-programming-with-php-5-1" quality="high" wmode="tranparent" ]

Object Oriented Programming with PHP




Object Oriented Programming With PHP 5 #2[gigya width="455" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=oop2-090302220926-phpapp02&stripped_title=object-oriented-programming-with-php-5-2" quality="high" wmode="tranparent" ]

Monday, February 22, 2010

How to get current page URL using PHP?

<?php

function currentPageURL()

{

$pageURL = 'http';

if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}

$pageURL .= "://";

if ($_SERVER["SERVER_PORT"] != "80")

{

$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

} else {

$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

}

return $pageURL;

}

?>

You can now get the current page URL using the line:

<?php
echo currentPageURL ();
?>

Thursday, February 18, 2010

Date format converting Code In PHP

In database date are stored with a format like 0000-00-00.But sometime we need to change the format.The following function help you to change the time format.

function dateFormat($Date)

{

$Date =explode("-",$Date);

$new_date= $Date[2]."/".$Date[1]."/".$Date[0]; //date format will be like21/12/2010

return $new_date ;

}

Breaking a big array into small parts

<?php

$smallarray1=array_slice($bigarray, 0, sizeof($bigarray) / 2);
$smallarray2=array_slice($bigarray, sizeof($bigarray) / 2);

?>

Code for Fav icon

<LINK REL="SHORTCUT ICON" href="images/shortcut.jpg" />

how to get File extention using PHP

<?php

$file_extension = strtolower(substr(strrchr($filename,"."),1));

?>

Saturday, January 30, 2010

Pie chart using php

<?php
$myImage = ImageCreate(300,300);
$white = ImageColorAllocate ($myImage, 255, 255, 255);
$red  = ImageColorAllocate ($myImage, 255, 0, 0);
$green = ImageColorAllocate ($myImage, 0, 255, 0);
$blue = ImageColorAllocate ($myImage, 0, 0, 255);
$lt_red = ImageColorAllocate($myImage, 255, 150, 150);
$lt_green = ImageColorAllocate($myImage, 150, 255, 150);
$lt_blue = ImageColorAllocate($myImage, 150, 150, 255);

for ($i = 120;$i > 100;$i–) {
ImageFilledArc ($myImage, 100, $i, 200, 150, 0, 90, $lt_red, IMG_ARC_PIE);
ImageFilledArc ($myImage, 100, $i, 200, 150, 90, 180, $lt_green, IMG_ARC_PIE);
ImageFilledArc ($myImage, 100, $i, 200, 150, 180, 360, $lt_blue, IMG_ARC_PIE);
}

ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green, IMG_ARC_PIE);
ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue, IMG_ARC_PIE);
header (“Content-type: image/png”);
ImagePNG($myImage);
ImageDestroy($myImage);
?>

Dynamic bar chart using php

<?php
header(“Content-type: image/jpeg”);
$data = array(‘3400′,’2570′,’245′,’473′,’1000′,’3456′,’780′);
$sum = array_sum($data);

$height = 255;
$width = 320;
$im = imagecreate($width,$height); // create width , height px of chart background
/*    $background_color = imagecolorallocate($im, 0, 0, 0);
*/    $white = imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im,0,0,0);
$red = imagecolorallocate($im,255,0,0);
//create the X & Y axis lines.
imageline($im, 10, 5, 10, 230, $black);
imageline($im, 10, 230, 300, 230, $black);

$x = 15;
$y = 230;
$x_width = 20;
$y_ht = 0;

for ($i=0;$i<7;$i++){
$y_ht = ($data[$i]/$sum)* $height;
imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$red);

/*    $colorHandle = imageColorAllocate($im, 225, 192, $i); // allocate color
imageFilledRectangle($im, $x,$y,$x+$x_width,($y-$y_ht), $colorHandle);// use it for drawing
*/
imagestring( $im,2,$x-1,$y+10,$data[$i],$black);
$x += ($x_width+20);
}
imagejpeg($im);
?>

Friday, January 29, 2010

DIRECTORY_SEPARATOR in php

DIRECTORY_SEPARATOR = strtoupper(substr(PHP_OS,0,3)=='WIN')?'\\':'/';

Tuesday, January 19, 2010

How to get current time in php

<?php

$time = date('g:i a');

echo $time;

?>

Wednesday, January 13, 2010

How to Get the Current Page URL

<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>

You can now get the current page URL using the line:
<?php
echo curPageURL();
?>

Tuesday, January 12, 2010

Captcha using php


<form name=”form1″ method=”post” action=”form.php” “>
<table width=”342″ align=”center” cellspacing=”0″ bgcolor=”#D4D0C8″>
<tr>  <td align=”center”><img src=”php_captcha.php”></td>
<td align=”center”> Please enter the string shown in the image in the form.<br>
</td><td align=”center”>
<input name=”number” type=”text”></td><td><input name=”Submit” type=”submit”   value=”Submit”></td> </tr></table></form>


The <ima src=…> is given a page php_captcha.php. Lets create the page.

The following code use to create random numbers and this number are embedding with existing image file, the first line used to initiate session, which use to carry the user inputs.

<?php
session_start();
$RandomStr = md5(microtime());
$ResultStr = substr($RandomStr,0,5);
$NewImage =imagecreatefromjpeg(“img.jpg”);
?>
The second line [md5 (microtime ())] use to generate the random string, and the resultant string is trim by using third line [substr], which returns the portion of string specified by the start and length parameters.
The function imagecreatefromjpeg (“img.jpg”) is use to create a image by existing image file and as back ground ,so that you need to give an image file path.

<?php
$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imageline($NewImage,1,1,40,40,$LineColor);
imageline($NewImage,1,100,60,0,$LineColor);
imagestring($NewImage, 5, 20, 10, $ResultStr, $TextColor);
?>
After creation of back ground image, we generate some linear line, which is use to avoid the phrasing from random numbers, the respective lines are create by the function named imageline () and imagestring () use to draw a random string horizontally.

<?php
$_SESSION['key'] = $ResultStr;
?>
The resultant random number [trimmed one], carry through session especially for validation purpose.

<?php
header(“Content-type: image/jpeg”);
imagejpeg($NewImage);
?>
Finally above two functions are uses to display/out put the image to browser. So we can just call the particular file by through image source path, it will display the final image.

<?php
if(isset($_REQUEST['Submit'])){
$key=substr($_SESSION['key'],0,5);
$number = $_REQUEST['number'];
if($number!=$key){
echo ‘ Validation string not valid! Please try again!’;}
else{
echo ‘ Your string is valid!’;}
}
?>

Monday, January 11, 2010

File upload using PHP

<html>
<head>
<title>A File Upload Script</title>
</head>
<body>
<div>
<?php
if ( isset( $_FILES['fupload']
) ) {


print "name: ".     $_FILES['fupload']['name'] ."<br />";
print "size: ".     $_FILES['fupload']['size'] ." bytes<br />";
print "temp name: ".$_FILES['fupload']['tmp_name'] ."<br />";
print "type: ".     $_FILES['fupload']['type'] ."<br />";
print "error: ".    $_FILES['fupload']['error'] ."<br />";

if ( $_FILES['fupload']['type'] == "image/gif" ) {

$source = $_FILES['fupload']['tmp_name'];
$target = "upload/".$_FILES['fupload']['name'];
move_uploaded_file( $source, $target );// or die ("Couldn't copy");
$size = getImageSize( $target );

$imgstr = "<p><img width=\"$size[0]\" height=\"$size[1]\" ";
$imgstr .= "src=\"$target\" alt=\"uploaded image\" /></p>";

print $imgstr;
}
}
?>
</div>
<form enctype="multipart/form-data"
action="<?php print $_SERVER['PHP_SELF']?>" method="post">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="102400" />
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>
</body>
</html>

Displaying current date in php

<html>

<head>
<title>Kajal's blog tutorial.</title>
</head>
<? print(Date("l F d, Y")); ?>

<body>
</body>
</html>