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

Wednesday, July 24, 2019

Dynamic Image Dimension based on Font size in PHP


Working with images and text, we need to set image size based on font size is very useful for dynamic image processing. like CAPTCHA and text images. if you looking for PHP script to set image size based on font size here is the solution for you.

<?php


if($_GET['fontsize']!="" and is_numeric($_GET['fontsize']))
$size=$_GET['fontsize'];
else
$size=20;


define("F_SIZE", $size);
define("F_ANGLE", 0);
define("F_FONT", "verdana.ttf");


$text = "W3 Lessons";

$Leading=0;
$W=0;
$H=0;
$X=0;
$Y=0;

$_bx = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$s = preg_split("/\n]+/", $text);  // Array of lines
$nL = count($s);  // Number of lines

$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
$H = ($H==0)?abs($_bx[5]-$_bx[3])+2+($nL>1?($nL*$Leading):0):$H;

$W*=1.05;
$H*=1.5;

$img = @imagecreate($W+8, $H) or die("Cannot Initialize new GD image stream");

$white = imagecolorallocate($img, 255,255,255);
$txtColor = imagecolorallocate($img, 29,56,131);

// Adjust padding right:
$W+=8;
$bgwhite = imagecolorallocatealpha($img,238,238,238,0);
imagefilledrectangle($img, 0, 0,$W,$H, $bgwhite);

$alpha = "".range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);

// Use the string to determine the height of a line
$_b = imageTTFBbox(F_SIZE, F_ANGLE, F_FONT, $alpha);
$_H = abs($_b[5]-$_b[3]);
$__H = 0;

// Use the string to determine the width of a line
$_b = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$_W = abs($_b[2]-$_b[0]);

// Final width and height
$_X = abs($W/2)-abs($_W/2);
$__H += $_H;

imagettftext($img, F_SIZE, F_ANGLE, $_X, $__H, $txtColor, F_FONT, $text);

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
// END EMAIL IMAGE  
exit();
?>

Saturday, October 20, 2012

Get Yahoo contacts from address book


Mr. Antony request me how to list all email ids from user's yahoo email account. here is the simple solution to get all Emails from user contact list in yahoo address book.

In order to work with Yahoo Address book we need to create oauth Project on yahoo developer network. let us create it first.

Step: 1


Select My Projects on Top Right below the search box. (You are ask to Login with existing yahoo account)

Step: 2

 Click New Project Button

Step 3:


Select Application Type "Standard"

Step 4: ( Fill your Application as per the form below with your own values)

Step 5: (Get your Project Keys)

Application ID: below the Project Name
Consumer Key and Consumer Secret Inside the Box

Step 6: (Verify your Domain)

 

Step: 7 (Download Yahoo PHP SDK -  Included in Demo Download)



index.php ( Show the Button labled "Get Yahoo Contacts")
<p align="center"><br />

<a href="getContact.php" style="background:#939; color:#FFF; 
padding:10px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; 
text-decoration:none; font-size:14px; font-style:italic; margin-top:50px; 
text-align:center;">Get Yahoo Contacts</a></p>

getContacts.php

Get List of contacts using YQL after user access
http://developer.yahoo.com/social/rest_api_guide/contacts_table.html


<?php session_start();

error_reporting(0);

// Replace your Own KEYS 

require("lib/Yahoo.inc");
// Your Consumer Key (API Key) goes here.
define('OAUTH_CONSUMER_KEY', "j0yJmk9M1Zzc0F3YURkV3AwJmQ9WVdrOU5tMVRhSFJETjJNbWNHbzlNVEUxTXpRek9UUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMg--");
// Your Consumer Secret goes here.
define('OAUTH_CONSUMER_SECRET', "febded04011a8e6e2f1227b9e24688f2252587a");
// Your application ID goes here.
define('OAUTH_APP_ID', "mShtC7c");
// Call back URL
define('CALL_BACK_URL','http://demos.w3lessons.com/yahoo-contact/getContact.php');

/*
    Consumer Key:
    Consumer Secret:
    Application URL:
    App Domain:

   dj0yJmk9M1Zzc0F3YURkV3AwJmQ9WVdrOU5tMVRhSFJETjJNbWNHbzlNVEUxTXpRek9UUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMg--
    afebded04011a8e6e2f1227b9e24688f2252587a
    http://demos.w3lessons.com/yahoo-contact/index.php
    demos.w3lessons.com
 
*/ 

$session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);   

$user = $session->getOwner();

$query = sprintf("select * from social.contacts where guid=me;");  
$response = $session->query($query); 



if(isset($response)){

   foreach($response->query->results->contact as $id){

       foreach($id->fields as $subid){

               if( $subid->type == 'email' )
               $emails[] = $subid->value;
       }
   }
}

$session->clearSession();

echo "<pre>";
print_r($emails);
?>
<br />
<br />
<a href="index.php">Back</a>

Download This Script     Live Demo     Download Script

Thursday, October 11, 2012

Protect email address in web content.


While building web content we may need to include email address. In this case spam bots are may access our web page and collect email address inside our web content. based on this email address extracting script.

The only way to protect Email address inside the content is convert all email address into image.

Here is the solution to convert email address into dynamic text images


email-to-image.php

<?php

define("F_SIZE", 10);
define("F_ANGLE", 0);
define("F_FONT", "verdana.ttf");

$text = base64_decode(base64_decode($_GET['id']));

$Leading=0;
$W=0;
$H=0;
$X=0;
$Y=0;
$_bx = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$s = preg_split("/\n]+/", $text);  // Array of lines
$nL = count($s);  // Number of lines

$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
$H = ($H==0)?abs($_bx[5]-$_bx[3])+2+($nL>1?($nL*$Leading):0):$H;

$img = @imagecreate($W+8, $H) or die("Cannot Initialize new GD image stream");

$white = imagecolorallocate($img, 255,255,255);
$txtColor = imagecolorallocate($img, 255,50,0);

// Adjust padding right:
$W+=8;
$bgwhite = imagecolorallocatealpha($img,238,238,238,0);
imagefilledrectangle($img, 0, 0,$W,$H, $bgwhite);

$alpha = "".range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);

// Use the string to determine the height of a line
$_b = imageTTFBbox(F_SIZE, F_ANGLE, F_FONT, $alpha);
$_H = abs($_b[5]-$_b[3]);
$__H = 0;

// Use the string to determine the width of a line
$_b = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$_W = abs($_b[2]-$_b[0]);

// Final width and height
$_X = abs($W/2)-abs($_W/2);
$__H += $_H;

imagettftext($img, F_SIZE, F_ANGLE, $_X, $__H, $txtColor, F_FONT, $text);

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
// END EMAIL IMAGE  
exit();
?>

index.php

<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
// Keep line breaks inside textarea
$content=preg_replace("/[\n]/", '<br />', $content);
// Find All email ids inside content
preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$content,$emails);

// Replace as image every email address
foreach($emails[0] as $email)
$content=str_replace($email,'<img src="email-to-image.php?id='.base64_encode(base64_encode($email)).'">',$content);
}
?>
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 12px;
 color: #000;
}
body {
 margin-left: 5px;
 margin-top: 5px;
 margin-right: 5px;
 margin-bottom: 5px;
 margin:0 auto;
 width:750px;
}

textarea { width:750px; font-size:15px; font-family:Verdana, Geneva, sans-serif;}

#content
{
 font-size:13px;
 padding:10px;
 background:#EEE;
 border:1px solid #CCC; 
}

#content img
{

 position:relative;
 margin-bottom:-3px;
}

</style>
</head>
<body>

<br>
<br>
<h1>Protect Email Address inside web content</h1>
<form action="" method="post">
<textarea cols="70" rows="10" name="content">
content mixed with any email address. that email address text will be converted into as image. for example we have info@example.com mail in this text area it will be return as image after the compilation. any no of occurrence will automatically replaced as image 

For Example:
Contact
admin@example.com

Technical
tech@example.com
</textarea>
<br /><br />

<input type="submit" value="Compile" name="submit" /><br />
<br />

</form>

<div id="content">
<?php echo @$content; ?>
</div>
</body>
</html>


Download This Script     Live Demo     Download Script

Wednesday, October 10, 2012

Extract Email ID from Content PHP


In many, CMS development, We may often to check whether any email was found inside the content in this case. Here is the best solution to extract email ids from content using the power of regular expression.

Regular Expression to extract Email IDs from Content.

'/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/'

PHP function to extract All Regular Expression Matches

preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$content,$output);

Sample Content.txt with email id mixed html

<p>example for extracting email id <b>example@gmail.com</b> 
from entire content it mean how many <b>email@example.com</b> 
<b>admin.connnect@example.com</b></p
<?php

//Extract Email ID from content.txt

$whois = file_get_contents("content.txt");
preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$whois,$emails);


echo "<pre>";
print_r($emails[0]);

?>

Output

// OUTPUT


Array
(
    [0] => example@gmail.com
    [1] => email@example.com
    [2] => admin.connnect@example.com
)



Thursday, June 21, 2012

Create a Zip Archive File Using PHP


Today we are going to program, How to build a Zip Archive from the Entire Directory or Create Zip file from selected file from server. Here is the solution to Create Zip file with PHP

Following PHP Program you can build Zip file
1 . Zip Entire Directory
2.  Zip Selected Files







<?php

include_once("CreateZipFile.inc.php");
$createZipFile=new CreateZipFile;

$directoryToZip="./";
$outputDir="/";
$zipName="CreateZipFileWithPHP.zip";

define("ZIP_DIR",1); // Make it 0 to Archive selected file(s)

if(ZIP_DIR)
{
//Code toZip a directory and all its files/subdirectories
$createZipFile->zipDirectory($directoryToZip,$outputDir);
}else
{
 $fileToZip1="files/File1.txt";
 $fileToZip2="files/File2.txt";
 $createZipFile->addFile(file_get_contents($fileToZip1),$fileToZip1);
 $createZipFile->addFile(file_get_contents($fileToZip2),$fileToZip2);
 $createZipFile->addFile(file_get_contents($fileToZip3),$fileToZip3);
}

$fd=fopen($zipName, "wb");
$out=fwrite($fd,$createZipFile->getZippedfile());
fclose($fd);
$createZipFile->forceDownload($zipName);
@unlink($zipName);
?>


Download This Script     Download Script    

Wednesday, February 22, 2012

Directory Model URL Rewriting with htaccess and map content with php

Creating a dynamic content for web application, we need to consider the Search Engine Optimized web URL structure to main the quality of our web development says "SEO Friendly", Search Engines are clearly identified our web content if we have Directory Model URL structure in our websites. As a developer SEO Friendly URL is very important to any project. Let me explain How to create Directory Model URL Rewriting with htaccess and how to map your content with php.

.htaccess directory structure url rewriting



directory structure:

/index.php
/.htaccess
/include/home.php
/include/about_us.php
/include/contact_us.php

Wednesday, February 8, 2012

Prevent Browser cache PHP

Working with PHP in some times we need to avoid browser cache, Browser cache will cases you to prevent page updates when ever we work on Self Data POST in PHP,

Here I give the solution to prevent the Browser cache when reloading current page. and re-download the actual page with dynamic content.
header( "Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
header( "Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" ); // HTTP/1.1
header( "Cache-Control: post-check=0, pre-check=0", FALSE );
header( "Pragma: no-cache" ); // HTTP/1.0

Wednesday, January 18, 2012

PHP Sort array by key values based on another array

When you are working with array and data field sets, sorting array by key value is very usefull to reorder data set based on your requirement.

Here is a PHP function to Sort array by key values based on another array

Thursday, October 20, 2011

Introduction to Website Login with Google, Yahoo

When we are working with Website Account Registration / Account Login Page, We have to present a Signup form based on our website requirement. In case we are provide a simple signup form with Email, password, Confirm password. In this case we can use External website Login from OAuth Providers among most familiar  services among web. Such this think , Google, Yahoo, Facebook, Twitter all major services are provide OAuth to accept web developer/Website owners are use their credential to accept users on their websites.

Let us create a Login Page for our website to accept the visitors those who already have a account with Google or yahoo.



Let us Create Website login with Google account or Yahoo Account

Website Login with Google Account, Yahoo Account with Oauth

Website registration and Login forms have important aspect of our development process. Currently visitors were not interested to fill large forms in any website. In this case visitors are not willing to join by signup on our website. In this aspect, technology will a solution. that is open social login from other major services. By this way, we can be use Login from google, yahoo, facebook, twitter.


First, Let us create a open login for our website login or registration form with Google Account and Yahoo Mail. upcoming days we will see other services. Now we can create website Login with OpenID OAuth Login with Google Accounts and Yahoo Accounts.

let us create How to make people login into your website with their Google account and Yahoo
Google and Yahoo provides Federated Login for Account Users with OAuth.

Step: 1
Download LightOpenID Class from
https://nodeload.github.com/brice/LightOpenId/zipball/master


Step: 2: Write a Following Code and design a Form to Handle Login

<?php session_start();
# Logging in with Google accounts requires setting special identity, so this example shows how to do it.
require 'require/openid.php';

try {
    # Change 'localhost' to your domain name.
    $openid = new LightOpenID('demos.w3lessons.com');
 
  $openid->required = array(
  'namePerson',
  'namePerson/first',
  'namePerson/last',
  'contact/email',
  );

    if(!$openid->mode) {
  
 if(@$_GET['auth']=="google")
    {
  $_SESSION['auth']="Google";
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        header('Location: ' . $openid->authUrl());
 }elseif(@$_GET['auth']=="yahoo")
 {
  $_SESSION['auth']="Yahoo";
  $openid->identity ='yahoo.com';
  header("Location:".$openid->authUrl());
 }

    } elseif($openid->mode == 'cancel') {
        echo 'User has canceled authentication!';
    } else {
   $external_login=$openid->getAttributes();
   $_SESSION['name']=$external_login['namePerson/first']." ".$external_login['namePerson/last'];
   $_SESSION['email']=$external_login['contact/email'];
   header("Location:account-home.php");
   exit();
   
    }
} catch(ErrorException $e) {
    echo $e->getMessage();
}
?>


Download This Script     Live Demo     Download Script

Tuesday, September 27, 2011

PHP Google PageRank Script

Finding Google PageRank for multiple URLs is difficult process,  Here is the my solution to find Google PageRank for multiple URLs at the same time, PR Finder PHP Script here is the best solution for Finding PR for any web url. hope this very usefull for your projects.


PHP Google PageRank finder Script 

Wednesday, September 14, 2011

Get yesterday date PHP

Here is the different way of Getting yesterday date with PHP
using strtotime() and mktime()  we can find the previous date in easy way.

# Using strtotime() function
// from Current Date
echo date("d-m-Y",strtotime("yesterday"));

# Using mktime() function
// from Specific date  eg: Oct-01-2011
echo date("d-m-Y",mktime(0,0,0,10,1,2011)-1);


Output:
13-09-2011
30-09-2011



Get First and Last date of the Month from given date with php

When working with date ranges we need to find out the month starting and end dates from the given date. here is the PHP function to Get First and Last date of the Month from given date with php

functions used:
list(), split(), date(), mktime(), array()




<?php

# Desc: Funcion to get First and Last date of the Month from Given Date
# Parm: $anyDate ( as YYYY-MM-DD format), $return Format (eg: d-m-Y );
# Return: Array with Two Values of First and Last Date

function first_last_date_of_month($anyDate,$returnFormat)
{
 // separate year, month and date
 list($yr,$mn,$dt)    =    split('-',$anyDate);    
 //Create time stamp of the first day from the give date.
 $timeStamp            =    mktime(0,0,0,$mn,1,$yr);
 //get first day of the given month
 $firstDay            =     date($returnFormat,$timeStamp);    
 //Find the last date of the month and separating it
 list($y,$m,$t)        =     split('-',date('Y-m-t',$timeStamp)); 
 //create time stamp of the last date of the give month
 $lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);
 // Find last day of the month
 $lastDay            =    date($returnFormat,$lastDayTimeStamp);
 // return the result in an array format.
 $arrDay                =    array("$firstDay","$lastDay"); 
 return $arrDay;
}

//Usage
$month_range=array();
$month_range=first_last_date_of_month('2011-09-10','d-m-Y');
print $month_range[0];
echo "<br>";
print $month_range[1];

?>


Monday, September 12, 2011

Change/Update Photo with Ajax Image Uploader


A Member request us, How to create a Google Profile Like: Ajax Image Photo Uploader to Change/Update Photo with Ajax Image Uploader using PHP and jQuery. Here is the solution for the Image Uploader like Google Profile Style Ajax Image Uploader



In this example I have use HTML Input file object replacer "prettyfile plugin".
here you can download the jQuery prettyFile Plugin and Use the following code to replace a file input like a "Update Photo" link. and Turn your interface look like a Google Profile Photo update page with PHP Ajax Uploader without refreshing the page. Change/Update Photo with Ajax Image Uploader

Place the PHP Server Side Process on Page Top:

<?php session_start();

if(isset($_SESSION['updated_image']))
$existing_image=$_SESSION['updated_image'];
else
$existing_image='unknown.jpeg';


if(isset($_POST['image_process']))
{
 echo "<pre>";
 $filename=$_FILES['profile_photo']['name'];
 // Check whether the Uploaded file is Image file
 if(preg_match("/^[a-zA-Z0-9-_\.]+\.(jpg|gif|png|jpeg)$/",$filename))
 {
  // Check the Uploaded Image size is Less than or equal to 100 KB ( 1 KB == 1024 Bytes)
  if($_FILES['profile_photo']['size']<=102400)
  {
   $file_ext=end(explode(".",$filename));
   $filename="profile-".time().".$file_ext";
   if(move_uploaded_file($_FILES['profile_photo']['tmp_name'],"images/$filename"))   
   {
    $_SESSION['updated_image']=$filename;
   // Push Javascript Message on top Window  
   ?>
   <script type="text/javascript">
   window.top.window.top.UploadStatus(0,'<?=$filename?>');
   </script>
   <?php     
   }else
   {
   // Push Javascript Message on top Window  
   ?>
   <script type="text/javascript">
   window.top.window.top.UploadStatus(3);
   </script>
   <?php    
   }
   
  }else
  {
   // Push Javascript Message on top Window
  ?>
        <script type="text/javascript">
  window.top.window.top.UploadStatus(2);
  </script>
        <?php   
  }
 }else
 {
   // Push Javascript Message on top Window  
  ?>
        <script type="text/javascript">
  window.top.window.top.UploadStatus(1);
  </script>
        <?php
 }
 exit();
}


?>


Friday, September 2, 2011

Select Country Drop Down based on country location with flag with PHP

Selecting country name from country drop down based on the visitors country location will increase visitors user friendliness for your web forms, Let us create How to create Auto Select Country Name based on visitors location based on Country Geo location and  IP Address. When Loading a page detect country name and locate a country flag based on country location.




Create a Free Account for IP to Location API from http://ipinfodb.com/ip_location_api.php  to get a API Key for IP to Location. and get the Country Flag from ip2Location database.
using the URL: http://www.ip2location.com/images/country/{ COUNTRY SHORT CODE} .gif

and Process the code as per the following:

Thursday, September 1, 2011

Google profile style Image Uploader Script with PHP and jQuery

A Member request us, How to create a Google profile photo update style Image uploader using PHP and jQuery. Here is the solution for the Image Uploader like Google Profiles Change Photo Style


In this example I have use HTML Input file object replacer "prettyfile plugin".
here you can download the jQuery prettyFile Plugin and Use the following code to replace a file input like a "Update Photo" link. and Turn your interface look like a Google Profile Photo update page with PHP Ajax Uploader without refreshing the page.

Place the PHP Server Side Process on Page Top:

<?php session_start();

if(isset($_SESSION['updated_image']))
$existing_image=$_SESSION['updated_image'];
else
$existing_image='unknown.jpeg';


if(isset($_POST['image_process']))
{
	echo "<pre>";
	$filename=$_FILES['profile_photo']['name'];
	// Check whether the Uploaded file is Image file
	if(preg_match("/^[a-zA-Z0-9-_\.]+\.(jpg|gif|png|jpeg)$/",$filename))
	{
		// Check the Uploaded Image size is Less than or equal to 100 KB ( 1 KB == 1024 Bytes)
		if($_FILES['profile_photo']['size']<=102400)
		{
			$file_ext=end(explode(".",$filename));
			$filename="profile-".time().".$file_ext";
			if(move_uploaded_file($_FILES['profile_photo']['tmp_name'],"images/$filename"))			
			{
				$_SESSION['updated_image']=$filename;
			// Push Javascript Message on top Window		
			?>
			<script type="text/javascript">
			window.top.window.top.UploadStatus(0,'<?=$filename?>');
			</script>
			<?php					
			}else
			{
			// Push Javascript Message on top Window		
			?>
			<script type="text/javascript">
			window.top.window.top.UploadStatus(3);
			</script>
			<?php				
			}
			
		}else
		{
			// Push Javascript Message on top Window
		?>
        <script type="text/javascript">
		window.top.window.top.UploadStatus(2);
		</script>
        <?php			
		}
	}else
	{
			// Push Javascript Message on top Window		
		?>
        <script type="text/javascript">
		window.top.window.top.UploadStatus(1);
		</script>
        <?php
	}
	exit();
}


?>


Sunday, August 28, 2011

Function to Convert CSV to Array using PHP

Processing CSV file for web projects is very usefull to show CSV Upload list, Upload data to database table, processing bulk posting etc., Here is the function to process CSV file, using this function we can convert our CSV file to PHP Mufti dimensional Array

 

PHP function to check valid email address and TLD

Validating email is mandatory process to maintain quality email database of website visitors. But cetertain situation we need to accept simple validating for E-mail Address using @ and . or validating using Regular expression may accept unknown domain TLDs, Here is my solution to avoid E-mail address certain range of TLDs.

Friday, August 26, 2011

Newsletter Script with Simple Captcha using PHP

In previous Post We seen how to create a Simple capcha. Now we look how to integrate that simple Captcha with HTML Form. Now I am going to show you a Newsletter Subscriber with our Simple Captcha.

Kindly view  How to Create a Simple Captcha in PHP before the Newsletter Integration of this Capcha

Let me create a HTML form look like this
 

Develop a Simple Anti spam Captcha in PHP with Custom Font


When working with web forms on web development.  Preventing spam is important process. But most of the developers are feel Captcha is very big process, nothing like that.
Here is the very simple Captcha developed in PHP with custom font rendering option. You can change the look and feel based on your project need.

Let us see how to create this Capcha in PHP:


Now I am going to generate a 4 Digit Random number and than store into session variable using ($_SESSION). Based on the 4 Digit Random number I will generate a simple capcha with the custom font feedbackbb.ttf.