Matthew Steven Kelly

Just another WordPress weblog

Generating an image from text

March23

This is an image displaying text from the input box

Text to display:

How did I do that?

Generating an image from text can be easy with PHP and GD. This requires GD 1.8 or higher.

Check out www.php.net for an exact description of the php functions used in this code. They are all pretty much built in GD functions.

Now the part that make this code great is that there is no temporary files saved on the server, it is all done in memory.

Save this code as generate_image.php

<?php
function trimLength($data,$len)
{
if(strlen($data)>$len)
{
$data = substr($data,0,$len);
}
return $data;
}

function filterText($data)
{
return preg_replace("/[^A-Za-z0-9.,\s\s+]/","",$data);
}

$text = filterText($_GET['text']); // remove all illegal characters
$text = trimLength($text, 60); // trim to sixty characters
if($text == "") { $text = "Text"; }

$font = 4;
$width = ImageFontWidth($font) * strlen($text);
$height = ImageFontHeight($font);

header("Content-type: image/gif;");
$im = @imagecreatetruecolor($width, $height)
or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 0, 0, 0);
$COULEUR_BLANC=imagecolorallocate($im,255,255,255) ;
imagefilledrectangle($im,0,0,$width,$height,$COULEUR_BLANC) ;
imagestring($im, $font, 0, 0, $text, $text_color);
imagegif($im);
imagedestroy($im);
?>

And then on the page you want the image created add this code

<img src="generate_image.php?text=The security code is 9999" alt="" />
posted under Random | No Comments »

Task Schedule Web Script From Windows

February9

If your website hosting is of the Linux variety, you know you can schedule scripts to automatically run using cron jobs. But what if your servers are all of the Windows variety? Not a problem, Windows provides the Windows Task Scheduler.

Lets say you have a php script that sends out emails to a newsletter list, but because you do not want to flood your email servers, you would like to have the server send out (20) emails every 30 minutes to keep your daily total under 1000 emails/day. You could generate a script that every time it was executed grabbed the next 20 emails from a database list and send them a predefined email.

Or if you have a database that has a large amount of volume, so to conserve space you only want to keep data that is less than 30 days old. You could create a script that executes a query to delete any content older than 30 days. With the task scheduler, you could have this script run every night.

Or if you have a production database and need to email a report out every hour, you could create a script to do so and task schedule it.

Or any other task you wish to have repeated on a scheduled basis and can easily script the task. This is a great tool for developers who are only familiar with scripting languages like PHP, ASP, etc and can complete advanced tasks in them that would otherwise be done by coding a C++ or C# server application.

Lets go with scheduling the email script example above for a walk through on setting up the Windows Task Scheduler.

On the Windows server (note this does not have to be the web server – it can be any Windows machine that will be running 24/7 to be able to execute the script when scheduled) go to “Start | Control Panel | Scheduled Tasks”.

  1. Click the Add Scheduled Task button
  2. Click Next
  3. Select Internet explorer from the list and click Next
  4. Select Perform this task Daily (we’ll change it later) and click Next
  5. Click Next on the task start time
  6. Enter your username and password of the computer
  7. Check the open advanced properties checkbox and click Finish

In advanced properties

  1. Add “www.mywebsite.com/mail.php” after “C:\PROGRA~1\INTERN~1\iexplore.exe” in the “Run” Section. The field will look like this: “C:\PROGRA~1\INTERN~1\iexplore.exe www.mywebsite.com/mail.php
  2. Click on the schedule tab and click advanced
  3. Check “Repeat Task” and say every 30 minutes for 24 hours.
  4. Click OK
  5. Click OK
  6. Enter the Windows user name and password again

Internet explorer will pop up and execute the script every 30 minutes now.

Need the script to have a few layers of security? Here are a few things you can add:

  • Utilize SSL encryption and setup the task scheduler to access the page via https:// instead of http:// this ensures any data transmitted between the web server and computer running the task scheduler is encrypted.
  • Have the web page look for a specific cookie on the computer making the request to execute the script. Then add a method to the script to allow for the one time creation of the cookie, such as mail.php?generatecookie=1. Now on any computer you need to run the task scheduler, first generate the cookie on the computer, then run the scheduler.
  • Have the script check the IP address of where the request is coming from and only allow it to execute if it is the IP address of the server running task scheduler. With PHP you can detect the IP address of where the web request is coming from using “$_SERVER['REMOTE_ADDR']” (note: only works if you have a static IP address and keep in mind IP addresses can be spoofed).
posted under Random | 1 Comment »

PHP Input Validation

February4

Any time time a user inputs data to your site the input should be validated to ensure it cannot cause any harm to the system. The obvious characters that cause problems are double and single quotes which are used in injection attacks to trick the server into executing malicious code. However, there are many other special characters and situations that can cause problems. This is especially important with taking input data and storing it a database, or emailing it off, etc.

PHP has built in functions to handle these tasks including preg_replace and substr. I created some functions below that I use for field validation:

They can be called like this:

<?php
echo trimLength(“This is a long string that needs to be cut down to ten characters”,10);
echo “<br>”;
echo filterText(“This @is$ t%ex&t w*ith $bad character*()@’s that need filtered”);
echo “<br>”;
echo filterNumeric(“1234ABCD”);
echo “<br>”;
echo filterEmail(“fake’s_email@^liar.com”);
echo “<br>”;
?>

substr is used to trim the length of text like below. This is especially useful when inputting data into a database fields such as varchar that have limited character lengths.

function trimLength($data,$len)
{
if(strlen($data)>$len)
{
$data = substr($data,0,$len);
}
return $data;
}

For the rest of my filtering, I always use regular expressions to filter out bad characters. I do this because regular expressions allow you to filter characters by specifying what characters you allow – not what characters you want to reject. This is an important distinction because there are so many different character sets and special characters that if you only filter by character replacement, instead of character exclusion, you open yourself up to faulty characters entering the system. If you are currently using str_replace to remove apostrophe’s and quote’s consider upgrading to regular expressions.

This text filtering allows for periods, comma’s and spaces to be used in the text:

function filterText($data)
{
return preg_replace(“/[^A-Za-z0-9.,\s\s+]/”,”",$data);
}

Only numbers are returned with this function:

function filterNumeric($data)
{
return preg_replace("/[^0-9]/","",$data);
}

When you need to filter a URL, different special characters such as ?, % and / are to be allowed

function filterURL($data)
{
return preg_replace("/[^A-Za-z0-9:_\%\-.\/\?,+]/","",$data);
}

This email filtering function doesn’t just filter the characters in email address it also validates it is in username@domain.domaintype format:

function filterEmail($data)
{
list($username, $domain) = explode("@", $data, 2);
$username = preg_replace("/[^a-z0-9._-]+/i", "", $username);
$domain = preg_replace("/[^a-z0-9._-]+/i", "", $domain);
if ( $username == "" || $domain == "" || !strpos($domain,"."))
{
return "";
}
else
{
return $username."@".$domain;
}
}

PHP Master

December2
Matthew Steven Kelly
Master 50,000 Expert Points
PHP Scripting Language

Click here: View Profile to view my Experts Exchange profile.

Click here: View Certificate to view my PHP certificate.

And more information about Experts-Exchange and me:
http://www.matthewstevenkelly.com/blog/technology/experts-exchange.html

posted under My Career | No Comments »

phpBB forum

November27

A while ago I evaluated many PHP based discussion forums for integration into a project a work. phpBB (PHP Bulletin Board) was found to be the best of the bunch. We were able to completely skin it into our application so that it appeared to be a seamless integration between our application page and the discussion forum.

I set up a sample of phpBB (with the default theme) on my site as a demonstration:
https://www.matthewstevenkelly.com/forum/

PHP Email

April5

Are you going to be sending email in PHP? Don’t use the mail() function, unless your site’s email needs are very basic and you are running on a Linux/Unix machine. It is light on features and not built into the Windows version.

The best approach is to use a 3rd party mail program. In the past I have used PHPMailer as it is has all features I have needed. This script is the fix to many SMTP email problems in PHP!

http://sourceforge.net/projects/phpmailer

Below is the PHP code to use it. Place class.phpmailer.php into your php includes directory.

Replace text in << >> with your server information:
http://www.emailaddressmanager.com/tips/mail-settings.html

<?php

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // send via SMTP
$mail->Host = "<<smtpserver>>:<<stmpport>>"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "<<uname>>"; // SMTP username
$mail->Password = "<<pword>>"; // SMTP password
$mail->From = "<<email address from>>";
$mail->FromName = "<<email name from>>";
$mail->AddAddress("<<email address to>>");
$mail->AddReplyTo("<<email address from>>","<<email name from>>");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Subject";
$mail->Body = "Body text";
$mail->AltBody = $mail->Body;

$mail->Send();

?>

posted under Random | No Comments »