Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, March 14, 2012

Create PNG Image Using PHP

<?php
header (“Content-type: image/png”);
$im = @ImageCreate (100, 20)
or die (“Image Create Problem”);
$background_color = ImageColorAllocate ($im, 255, 255, 255);
$text_color = ImageColorAllocate ($im, 233, 14, 91);
ImageString ($im, 5, 5, 5, “SunilKumar VC”, $text_color);
ImagePNG ($im);
?>

Create Clock Image Using PHP

<?php
header(“Content-type: image/gif”);
$imSize        =    256;
$clockSize        =    $imSize – 8;
$today        =    getdate();
$hour            =    $today[hours];
$minutes        =    $today[minutes];
$seconds        =    $today[seconds];
if ($hour >= 12)
{
$hour    -=    12;
}
$hourDegress    =    $hour * 30;
$hourDegress    +=    $minutes / 2;
$minDegress    =    $minutes * 6;
//*    the cordinate system stars at 3:00
$hourDegress    -=    90;
if ($hourDegress < 0)
{
$hourDegress    +=    360;
}
$minDegress    -=    90;
if ($minDegress < 0)
{
$minDegress    +=    360;
}
//*    convert to radians
$hourRadians    =    $hourDegress / 57.295779513082;
$minRadians    =    $minDegress / 57.295779513082;
$myImage        =    ImageCreate($imSize, $imSize);
$white        =    ImageColorAllocate($myImage, 255, 255, 255);
$black        =    ImageColorAllocate($myImage, 0, 0, 0);
//    $red            =    ImageColorAllocate($myImage, 255, 0, 0);
//    $green        =    ImageColorAllocate($myImage, 0, 255, 0);
$blue            =    ImageColorAllocate($myImage, 0, 0, 255);
ImageFill($myImage, 0, 0, $blue);
Imageinterlace($myImage, 1);
//*    draw the clock circle
Imagearc($myImage, $imSize/2, $imSize/2, $clockSize, $clockSize, 0, 359, $white);
//*    draw the hour hand
$hourHandLen    =    ($clockSize / 2) * 0.6;
$x2                =    $imSize/2 + ($hourHandLen * cos($hourRadians));
$y2                =    $imSize/2 + ($hourHandLen * sin($hourRadians));
ImageLine($myImage, $imSize/2, $imSize/2, $x2, $y2, $white);
//*    draw the minute hand
$minHandLen        =    ($clockSize / 2) * 0.9;
$x2                =    $imSize/2 + ($minHandLen * cos($minRadians));
$y2                =    $imSize/2 + ($minHandLen * sin($minRadians));
ImageLine($myImage, $imSize/2, $imSize/2, $x2, $y2, $white);
if ($minutes < 10)
{
$minutes    =    “0$minutes”;
}
Imagestring($myImage, 3, 5, $imSize – 15, ($hour . “:” . $minutes), $white);
Imagegif($myImage);
Imagedestroy($myImage);
?>

Thumbnail Generation Using PHP

/* Seetings needs to be done */
$file = File Name which you created using timestamp
$photos_dir = Directory Path of the file Original files Stored Path
$thumbs_dir = Directory Path where the thumb photos to be stored
$square_size = Width of the file, You can specifiy the width here ex: 100px
set_thumb($file, $photos_dir,$thumbs_dir, $square_size, $quality=100);
function set_thumb($file, $photos_dir,$thumbs_dir, $square_size, $quality=100) {
//check if thumb exists
if (!file_exists($thumbs_dir.”/”.$file)) {
//get image info
list($width, $height, $type, $attr) = getimagesize($photos_dir.”/”.$file);
//set dimensions
if($width> $height) {
$width_t=$square_size;
//respect the ratio
$height_t=round($height/$width*$square_size);
//set the offset
$off_y=ceil(($width_t-$height_t)/2);
$off_x=0;
} elseif($height> $width) {
$height_t=$square_size;
$width_t=round($width/$height*$square_size);
$off_x=ceil(($height_t-$width_t)/2);
$off_y=0;
}
else {
$width_t=$height_t=$square_size;
$off_x=$off_y=0;
}
$system=explode$file = File Name which you created using timestamp
$photos_dir = Directory Path of the file Original files Stored Path
$thumbs_dir = Directory Path where the thumb photos to be stored
$square_size = Width of the file, You can specifiy the width here ex: 100px
set_thumb($file, $photos_dir,$thumbs_dir, $square_size, $quality=100);
function set_thumb($file, $photos_dir,$thumbs_dir, $square_size, $quality=100) {
//check if thumb exists
if (!file_exists($thumbs_dir.”/”.$file)) {
//get image info
list($width, $height, $type, $attr) = getimagesize($photos_dir.”/”.$file);
//set dimensions
if($width> $height) {
$width_t=$square_size;
//respect the ratio
$height_t=round($height/$width*$square_size);
//set the offset
$off_y=ceil(($width_t-$height_t)/2);
$off_x=0;
} elseif($height> $width) {
$height_t=$square_size;
$width_t=round($width/$height*$square_size);
$off_x=ceil(($height_t-$width_t)/2);
$off_y=0;
}
else {
$width_t=$height_t=$square_size;
$off_x=$off_y=0;
}
$system=explode(“.”,$file);
$fileName = $photos_dir.”/”.$file;
if (preg_match(“/jpg|jpeg/”,$system[1])){$thumb=imagecreatefromjpeg($fileName);}
if (preg_match(“/gif/”,$system[1])){$thumb=imagecreatefromgif($fileName);}
if (preg_match(“/png/”,$system[1])){$thumb=imagecreatefrompng($fileName);}
// $thumb=imagecreatefromjpeg($photos_dir.”/”.$file);
$thumb_p = imagecreatetruecolor($square_size, $square_size);
//default background is black
$bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
imagefill ( $thumb_p, 0, 0, $bg );
imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height);
imagejpeg($thumb_p,$thumbs_dir.”/”.$file,$quality);
}
}(“.”,$file);
$fileName = $photos_dir.”/”.$file;
if (preg_match(“/jpg|jpeg/”,$system[1])){$thumb=imagecreatefromjpeg($fileName);}
if (preg_match(“/gif/”,$system[1])){$thumb=imagecreatefromgif($fileName);}
if (preg_match(“/png/”,$system[1])){$thumb=imagecreatefrompng($fileName);}
// $thumb=imagecreatefromjpeg($photos_dir.”/”.$file);
$thumb_p = imagecreatetruecolor($square_size, $square_size);
//default background is black
$bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
imagefill ( $thumb_p, 0, 0, $bg );
imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height);
imagejpeg($thumb_p,$thumbs_dir.”/”.$file,$quality);
}
}

Fetching the data from RSS Feed using PHP

$feed = “http://www.webdevstuff.com/wp-feed.php”;
<?php
ini_set(“display_errors”, “on”);
$feed = “http://www.webdevstuff.com/wp-feed.php“;
$xml = simplexml_load_file($feed);
$s1 = ’style=”font-size:1.7em”‘;
$s2 = ’style=”text-transform:uppercase;font-size:1.2em”‘;
$header  = ‘<strong ‘ . $s1 . ‘>’ . $xml->channel->title . ‘</strong><br />’;
$header .= ‘<span ‘ . $s2 . ‘>’ . $xml->channel->description . ‘</span><br />’;
$header .= ‘<br />’;
echo $header;
foreach ($xml->channel->item as $item)
{
$output  = ‘<a href=”‘ . $item->link . ‘”>’ . $item->title . ‘</a><br />’;
$output .= ‘Published on ‘ . $item->pubDate . ‘<br />’;
$output .= $item->description . ‘<br />’;
$output .= ‘<br />’;
echo $output;
}
?>

Multiple files Upload in PHP

Paste the Html code in html page, create one more php page called upload.php
HTML Code :
<html>
<head>
<title>Upload Multiple Files</title>
<script>
var rowid=0;
function addTableRow()
{
var div = document.createElement(‘DIV’);
div.className = “rowdiv”;
div.id = ‘dynamicRow’+(rowid++);
div.name = ‘dynamicRow[]‘;
div.innerHTML = ‘<div>’+
//File name column
‘<div>’+
‘<table border=”0″>’+
‘<tr>’+
‘<td>Image Caption</td>’+
‘<td><input type=”text” name=”image_caption[]” id=”image_caption’+rowid+’”  /></td>’+
‘</tr><tr><td>Upload Image</td>’+
//Browse button
‘<td ><div id=”ufile_field’+rowid+’”>’+
‘imagepath[]” id=”imagepath’+rowid+’”  />’+
‘</div>’+
‘rowid-1)+’)” value=”Remove” style=”color:#009999;border:0px;background:transparent;cursor:pointer;”>’+
‘</td></tr>’+
‘</table></div>’+
‘</div>’;
document.getElementById(‘dynamicTable’).appendChild(div);
}
function deleteItem(id)
{
document.getElementById(‘dynamicTable’).removeChild(document.getElementById(‘dynamicRow’+id));
}
function do_submit(f){
var chk = false;
text_array = document.getElementsByName(‘image_caption[]‘);
var number_text_rows = text_array.length;
for(var k=0;k<text_array.length;k++){
text_value = text_array[k].value;
if(text_value == “”){
alert(“Please enter image caption”);
return false;
}
}
files_array = document.getElementsByName(‘imagepath[]‘);
var number_rows = files_array.length;
for (var i=0;i<files_array.length;i++){
filename = files_array[i].value;
if(filename != ”){
var lastDot = filename.lastIndexOf(“.”);
var pathLength = filename.length;
var fileType = filename.substring(lastDot,pathLength);
if((fileType == “.jpg”) || (fileType == “.gif”) || (fileType == “.png”)) {
chk = true;
} else {
alert(“Invalid file format.”);
return false;
}
}else{
var img_cnt = i + 1;
alert(“Please Upload for Image. “+ img_cnt);
return false;
}
}
if (chk == true)
return true;
}
</script>
</head>
<body style=”text-align: center;”>
<form enctype=”multipart/form-data” action=”upload.php” method=”post” onSubmit=”return do_submit(this)” enctype=”multipart/form-data”>
<table>
<tr>
<td>Image Caption</td>
<td><input type=”text” name=”image_caption[]” id=”image_caption” /></td>
</tr>
<tr>
<td>Upload Image</td>
<td>
imagepath[]” id=”imagepath” />
<a href=”javascript://” onclick=”addTableRow();”>Attach a file</a>
</td>
</tr>
</table>
<table>
dynamicTable”>
</table>
<input type=”submit” name=”upload” value=”Upload” />
</form>
</body>
</html>

PHP Code :
<?php
$files = $_FILES['imagepath'];
$number_of_files = count(reArrayFiles($files));
$files_arr = reArrayFiles($files);
echo “<pre>”;
print_r($files_arr);
function reArrayFiles(&$file_post)
{
if (is_array($file_post['name'])) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
}else {
$file_ary[0] = $file_post;
}
return $file_ary;
}
?>

File Download using PHP Script

PHP File Download:

0){
$seek_start = intval($range[0]);
}
if($range[1] > 0){
$seek_end = intval($range[1]);
}

// Seek to the requested position in the file
fseek($fp, $seek_start);

// Set the range response headers
header(‘HTTP/1.1 206 Partial Content’);
header(‘Content-Length: ‘ . ($seek_end – $seek_start + 1));
header(sprintf(‘Content-Range: bytes %d-%d/%d’, $seek_start, $seek_end, $size));
}
else
{
// Set default response headers
header(‘Content-Length: ‘ . $size);
}

// Set up the size of each piece of data we send
$block_size = 1024;
if($rate > 0)
{
// Multiply by rate if specified
$block_size *= $rate;
}

// Prevent the script from timing out
set_time_limit(0);

// Start sending the file
while(!feof($fp))
{
// Output data
print(fread($fp, $block_size));
flush();

if($rate > 0)
{
// Wait one second before next block if rate is specified
sleep(1);
}
}

// Close the file
fclose($fp);
}
?>

Capcha code integration with php

Paste the code in php page and download the monofont.ttf font and paste in the same folder.

Php Code:

var $font = ‘./monofont.ttf’;

function generateCode($characters) {
/* list all possible characters, similar looking characters and vowels have been removed */
$possible = ’23456789bcdfghjkmnpqrstvwxyz’;
$code = ”;
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
return $code;
}

function Captcha($width=’120′,$height=’40′,$characters=’6′) {
$code = $this->generateCode($characters);
/* font size will be 75% of the image height */
$font_size = $height * 0.75;
$image = imagecreate($width, $height) or die(‘Cannot initialize new GD image stream’);

/* set the colours */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$noise_color = imagecolorallocate($image, 100, 120, 180);

/* generate random dots in background */
for( $i=0; $i<($width*$height)/3; $i++ ) {
imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
}
/* generate random lines in background */
for( $i=0; $i<($width*$height)/150; $i++ ) {
imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
}
/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die(‘Error in imagettfbbox function’);
$x = ($width – $textbox[4])/2;
$y = ($height – $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die(‘Error in imagettftext function’);
/* output captcha image to browser */
header(‘Content-Type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
$_SESSION['security_code'] = $code;
}

}

$width = isset($_GET['width']) && $_GET['width'] < 600 ? $_GET['width'] : ’100′;
$height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : ’30′;
$characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : ’6′;

$captcha = new Captcha($width,$height,$characters);
?>