CSS Opacity Settings

Here we’ll show you how to alter the opacity of an HTML element using the CSS3 opacity property.

Example HTML & CSS Code:

<!DOCTYPE html>
<title>320px by 480px</title>
width: 320px;
height: 480px;
border:2px solid #333;
background-color: #444;

#iPhoneBox img{
opacity: 0.5;
<div id=”iPhoneBox”>
<img src=”football.jpg” width=”320px” alt=”NFL 2015″ />

If you take note of the style section on the head part of the above HTML code, you can see that I have made the image have a solid background color. You can experiment with the color used here to give the opaque image different effects. Also experiment with the opacity setting of the image which can be anything between 0 and 1.

How to Use PHP in an External JavaScript File

This is a simple lesson on making your external JavaScript files more dynamic using PHP. PHP is perfectly capable of generating JavaScript code in-line, but have you thought about using it in an external JavaScript file? Well, you can and here’s how:

1 – Convert your JavaScript file to a PHP file

Let’s say you already have an existing JavaScript file. You’ll have to convert it to a PHP file to be able to enjoy all of the goodness of PHP in your JavaScript. All you have to do is change the .js extension to a .php extension so javascript.js becomes javascript.php.

2 – Edit HTML to Include your External JavaScript/PHP File

The next thing you’ll do is edit the script tag in your HTML that calls your external JavaScript. It will end up looking like:

<script type=”text/javascript” src=”javascript.php?c=<?php echo $config_file; ?>”></script>

Notice that two things are changed from how it would look before converting to PHP. First, we added a variable to the file name and second we added a PHP tag to echo the file name of a third file used to hold PHP variables that need to be available to the JavaScript file since the script tag doesn’t allow for variables in the including script to be passed to the external JavaScript/PHP file automatically as it would if it were included using a PHP include function. NOTE: the passing of the config script is optional, so if you don’t need to pass any PHP variables or functions along in your script tag, all you’d have to do is replace javascript.js with javascript.php and you’d be done. You’ll find the method for passing PHP variables and functions will come in handy for many of you tough.

Back to work. Hope this helps.

How to Create a CSS Stylesheet with PHP

Variables can be very useful in CSS. Unfortunately CSS isn’t particularly variable-friendly. In comes PHP. It is very easy to dynamically create portions of your CSS style sheet using PHP. You can also generate the entire style sheet using PHP if you wish, but I find it usually more practical to only generate needed sections of my CSS with PHP. Either way, here is how it is done:

Convert Existing CSS Style Sheet to PHP

Lets start with an existing webpage with the below  index.html and style.css files.

Content of index.html:

<!DOCTYPE html>
<head><title>CSS & PHP Example</title>
<link rel=”stylesheet” type=”text/css” href=”style.php”>
<div id=”box”>
<h1>H1 Header</h1>
<p>This is text inside a p tag which is inside of the box div…</p>

Edit index.html

In index.html, the only required change to convert to a PHP enhanced CSS style sheet is to edit the link tag’s href attribute. In our above example HTML code’s link tag, we  changed “style.css” to “style.php”. For example:

<link rel=”stylesheet” type=”text/css” href=”style.css”>


<link rel=”stylesheet” type=”text/css” href=”style.php”>

That’s all for index.html. The rest of the changes will be done in the style sheet.

Content of  style.css

Our original style.css file looks like this:

background-color: #FFFFFF;

position: absolute;
background-color: #0000FF;
border-radius: 15px;
top: 100px;
width: 400px;
height: 300px;
left: 60px;
line-height: 18px;
padding-left: 15px;
padding-right: 12px;

Edit style.css File

We will only be making a few minor changes to the above style.css file to make it work with dynamic PHP variables. Here’s the simple process:

  • Save style.css as style.php – all we are doing in this step is changing the .css extension to .php.
  • Add some PHP code to the top of the style.php file that changes the content type back to CSS. The php code needed is: <?php header(“Content-type: text/css; charset: UTF-8”); ?>
  • Build a couple of variables for various CSS attribute values such as color, padding, height, width etc. You can set any values you wish using PHP by following our example. We are keeping it simple for learning purposes and only changing the background colors in our example webpage by setting a variable for the body’s background color and for the box’s background color with: <?php $body_bg = “red”; $box_bg = “blue”; ?>
  • Save style.php and upload your two new files, index.html and style.php to your server for testing. Unlike using just HTML and CSS, when you use PHP and HTML files, you can no longer test the webpage from your desktop unless you have an active web server which most people don’t. But it will work fine if you upload it to your website and navigate to the index.html page.

Final HTML and PHP Code

I won’t list the HTML code again here because it is still the same as it was above, so simply use that if you are following along with this tutorial. The style.php file however has more changes so I am adding the final PHP code for style.php below:

Final PHP/CSS Style Sheet Code

header(“Content-type: text/css; charset: UTF-8”);
$body_bg = “red”;//”#DBF5F3″;
$box_bg = “blue”;//”#DBF5F3″;

background-color: <?php echo $body_bg; ?>;

position: absolute;
background-color: <?php echo $box_bg; ?>;
border-radius: 15px;
top: 100px;
width: 400px;
height: 300px;
left: 60px;
line-height: 18px;
padding-left: 15px;
padding-right: 12px;

The final solution is no more than a blue div with some simple text inside a red body and you can see my working version of it here: http://jafty.com/CSSnPHP/

Converting index.html to index.php

An optional idea which is often more convenient, is to convert your index.html file into a PHP file. All you have to do is change the .html extension to .php and that is done. One good reason why you might want to convert your HTML file to a PHP file is to be able to declare styles in your index.php file too using PHP. You may also want to set your main styles at the top of your index.php script to make them easy to find and edit. The only reason I used an HTML file in my example was to show you the simplest way to use PHP with CSS styles, in the real world, if you’re using PHP in your style sheet, you are probably going to want to use it in your index file as well. While it is not a requirement, it does make good sense in many situations.

The one caveat to using PHP variables in both your index.php and you style.php file is that when you use the link tag to include your PHP style sheet as in the above HTML example, the variables do not carry over from one page to the other. One possible fix to this is to create a new file just for configuration settings, I use this to set basic color variables and the like and call it config.php. Then other developers working with your code can very easily change colors, sizes and other styles all in one place without having to pour over all the css code.

Another possible solution to overcoming the passing of variables between index and style scripts is to eliminate the use of the link tag to include the style sheet. You could use a regular PHP include function instead, but you’d have to restructure your style sheet to read like an inline style sheet included in the head section of your index.php page. Basically you would not use the content declaration in PHP and wrap the CSS in <style> and </style> tags instead.


If this solution didn’t work for you. There’s a few possible causes.

If you’re on an Apache server and using WordPress with the above solution. You may need leave the file named style.css, and use .htaccess to parse it as PHP. Add the following code to the .htaccess file at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.

<FilesMatch “^.*?style.*?$”>
SetHandler php5-script

Another possible WordPress solution involves using PHP code such as:

 $absolute_path = explode(‘wp-content’, $_SERVER[‘SCRIPT_FILENAME’]);
 $wp_load = $absolute_path[0] . ‘wp-load.php’;

  Do whatever here…

  header(‘Content-type: text/css’);
  header(‘Cache-control: must-revalidate’);

If your PHP variables are not working as expected. Read above last two paragraphs under the heading “Converting index.html to index.php”. There I explain how to overcome this possible issue related to using the HTML link tag.


There you have it! Easy as pie. Of course, in the real world, you will be developing much more complex solutions than this, but the easy example code here should be just enough to get you started using PHP to generate CSS style sheets. If you have troubles when using WordPress with this solution, the troubleshooting tips should help.



How to use Twitter Boostrap without the Overhead

I went over to the Twitter Bootstrap website today to download the latest Bootstrap version for a new project I am starting and was happy to notice that the Bootstrap files are now available as remotely included files! That means you do not have to download the files and put them on your server. They include the two main files, the CSS and the JavaScript files, for Twitter Bootstrap.

How to use remote file includes for Bootstrap

MaxCDN has provide CDN support for Bootstrap’s CSS and JavaScript files. Simply replace old links to CSS and JavaScript files with these Bootstrap CDN links:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>



How to Use Firefox for Mobile and Responsive Web Design

Today I found a nice trick that I wish I would of realized years ago. I figured I’d post it here in case anyone else is missing out on this great Firefox feature for mobile developers and responsive web design. Firefox as a mobile screen display which you can get by using the shortcut:


It’s that easy.

To use this feature of Firefox, simply open the browser, hit the key combo, control+shift+m and type in any web address in the address bar like normal. Here’s what it looks like:

Snap 2014-11-20 at 21.39.23…and what’s really nice is that you can use developer tools while at this size and be able to read them easily with little scrolling. I used to try to use the tools while the browser window was very small and I couldn’t read more than a line at a time but now it is easy. Here’s a picture of the same website as above with developer tools opened:

Snap 2014-11-20 at 21.39.45Nice huh? By the way, there is an icon in the top right corner of the tools window that allows you to reposition the toolbox in the side of the window instead of at the bottom as it is by default.

WordPress Plugin Development – Part 2 Admin Menu

Here we will cover how to add menu items and admin pages to the WordPress admin area or the wp-admin dashboard.  This will be the first lesson in the crash course on WordPress development series where you will actually be creating a full working WordPress plugin!


I explain a plugin’s file structure and how to start your first plugin file in PHP in the primer for this series. Click the following link to read the primer for this tutorial:

Crash Course on WordPress Plugin Development

Other requirements are the same for the entire series of WordPress plugin tutorials and include:

  • Knowledge of PHP
  • Experience in HTML and HTML5
  • Knowledge of JavaScript
  • CSS experience
  • WordPress experience
  • Knowledge of MySQL database

Create a Plugin that adds an Admin Menu to the WordPress Dashboard

Starting with the PHP file template we made in our primer the plugin file that creates an admin menu and page for your WordPress dashboard will look like:

 * Plugin Name: Jafty Part Two
 * Plugin URI: http://jafty.com/blog/crash-course-on-wordpress-plugin-development/
 * Description: A Plugin that adds a menu item and admin page to the wp-admin dashboard.
 * Version: 1.0
 * Author: Ian L. of Jafty.com
 * Author URI: http://jafty.com
 * License: GPL2

//part two, add admin menu:

function add_notes_menu(){
add_menu_page(‘Admin Notes’, ‘Admin Notes’, ‘manage_options’, ‘admin_notes’, ‘create_notes_pg’,”,3);
//add_submenu_page(‘admin_notes’,’Credits’, ‘Credits’,’manage_options’, ‘manage_notes_slug’, ‘create_credits_pg’);
}//end add_notes_menu function.

function create_notes_pg(){
include “../wp-content/plugins/jafty-plugin/inc/admin_notes.php”;
}//end create_notes_pg function

Admin Page PHP File

Next we need to create the admin page. To accomplish this I like to create a new folder inside my plugin folder named “inc”. Then create a file appropriately named after the admin page in question such as admin_notes.php. For demonstration purposes, the below HTML will be the temporary contents of your inc/admin_notes.php file. You can add your own PHP, CSS and/or JavaScript code as needed.

<h1>Add/Edit/Delete Admin Notes</h1>

You can put whatever HTML, CSS, JavaScript and PHP code you desire here by editing the jafty-plugni/inc/admin_notes.php file….

Code Explained

Okay, some of the above code(not the HTML we hope) is a little confusing if you are not familiar with the WordPress function used, especially the add_menu_page and add_submenu_page function. They do what they suggest. add_menu_page adds an admin page and a top level menu item to the admin dashboard’s main left navigation menu. The add_submenu_page function, that we currently have commented out, would be used to add a submenu item to the admin navigation menu as well as another admin page. The submenu would appear under the main menu item set in the function’s parameters. I’ll go on to explain the add_menu_page function in detail below to help you better understand both.

WordPress add_menu_page Function

add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );

As demonstrated above, the add_menu_page function takes up to 7 parameters:

  • page_title – this is what will show up inside the title HTML tag of the page and therefore shows up on the browser tab when the page is opened.
  • menu_title – this is the menu text that shows up in the main admin dashboard’s navigation menu.
  • capability – is the user capability a user must have in order to view the admin page you are adding.(no longer use user levels here as this has been depreciated)
  • menu_slug – is the text that shows up in the URL when viewing your new admin page. (optionally you can use the PHP file name of the menu page here and not use the next function parameter to create the page. We do not use this method here though)
  • function – is where you name the PHP function that creates the admin page.(technically this is optional, but this is a much needed option for the method we use for creating admin pages and menus. If you do not include this, you do not use a function to create the page, but include the file name of the menu page in the previous menu_slug parameter instead)
  • icon_url – is an optional parameter that can be used to name an image file for the icon used in the navigation menu for this item. In our example above, we left this blank, but if you want to use the next parameter, as we have, you must put at least an empty quotation here to mark it’s place. When not used, the standard gear icon is used as the icon for the menu item.
  • position – is an optional parameter used to define the position in the admin menu that you want your new menu item to appear. We used 3 here because that is the magic number that allows the menu item to appear directly after the “dashboard” menu item which is where I like to include more important menu items so they are easy to find. you can use a higher number here to make the menu item appear further down in the navigation menu.

Put it all together:

To put this all together into a working plugin, you could follow these simple steps:

  1. create a folder on your desktop named “Jafty_plugin_two”, the name of this plugin.
  2. name your main plugin PHP file(the first one we made above) “jafty-plugin-2.php” and place it insde of the Jafty_plugin_two folder.
  3. Create a folder named “inc” inside of the main plugin folder, Jafty_plugin_two.
  4. Name the last file we created, that has only the HTML for the new admin page, “admin_notes.php” and place it inside of the “inc” folder.
  5. Finally upload the Jafty_plugin_two folder to your plugins directory and go to your dashboard’s plugin tab and activate the “Jafty Part Two” plugin and you will see your admin menu item appear. Click on it and you should see something like the main image at the top of this article.


We demonstrated the code to create a functional plugin that adds a custom admin page and corresponding navigation menu item to the WordPress admin dashboard. Then we went on to explain the main function used to accomplish this. We also added the means in the plugin to expand it to include submenu items under the main menu item we added. We commented out this submenu code until it is needed. If you want to add a submenu item, simply remove the uncomment the line and make the first parameter the same as the fourth parameter in the corresponding add_menu_page function which is the menu slug parameter.

Best Captcha Scripts

Tonight I decided to evaluate a few different captcha options. I did this mainly for the same reason I do most things on this blog, I have a client that needs a captcha. My situation, as usual, is unique because I have to add a captcha to a PHP page, but that PHP page submits a form to a cgi script. As you may have heard, I am mostly a PHP programmer, so I don’t care much for cgi and asp type scripts. I had to find a captcha that would work with both PHP and cgi, which wasn’t easy as it turns out.

Here are some of the captcha solutions I tried. If you want my best reccomendation, skip to the last one, Jafty Captcha. It is a custom simple captcha I made from what I learned examining the others.


Botdetct is a captcha solution that offers solution in PHP, ASP, cakePHP, Ajax and others, so I thought it might work for my unique situation. Turns out it wasn’t the best for my situation, but it would of been great for pure PHP or HTML web pages that need captcha. I did make a working example which you can see at:


That is a link to the test I ran with it. The only problem with this is that is does the captcha after the form is submitted and I needed a script that can do the captcha check before form is submitted due to the fact that my client’s page submits to a cgi script and I’d rather not mess with the cgi script at all to keep things simple. Back to the drawing board for me, but if you have a PHP only form submission, it would work great for you!

Simple PHP Captcha

Simple PHP Captcha was the next service I evaluated. I like this one better than BotTech for sure, but again, it was a PHP only solution basically offering no JavaScript alternative and the code to check the captcha would have to be on the page you are submitting the form to. This is a good PHP only solution, but if you are not submitting your form to a PHP script, this isn’t ideal, so I kept searching. Here is the example I made for this captcha script though:


Simple JavaScript Captcha You Can Add to Any Form

I found my next Captcha to test at http://www.tothemoon.com/2013/01/simple-javascript-captcha-you-can-add-to-any-form/ and you can see from the URL, it is supposed to be a very simple JavaScript captcha. So I decided to give it a go. I actually took this script and made some adjustments to it and came out with a decent captcha script which I will post the code for anyone else interested here.

Demo: http://jafty.com/simple-js-captcha/JS-captcha.html

HTML & JavaScript code:

<!DOCTYPE html>
<head><title>JS Captcha by Ian L. of Jafty.com</title>
background-color: #430000;
<form name=”review” ACTION=”newpg.html” METHOD=”POST” onsubmit=”return checkform(this);”>
<font color=”#DD0000″>Enter Code ></font> <span id=”txtCaptchaDiv” style=”background-color:#A51D22;color:#FFF;padding:5px”></span>
<input type=”hidden” id=”txtCaptcha” />
<input type=”text” name=”txtInput” id=”txtInput” size=”15″ />
<input type=”submit” value=”Submit”/>

<script type=”text/javascript”>
function checkform(theform){
var why = “”;

if(theform.txtInput.value == “”){
why += “- Security code should not be empty.\n”;
if(theform.txtInput.value != “”){
if(ValidCaptcha(theform.txtInput.value) == false){
why += “- Security code did not match.\n”;
if(why != “”){
return false;

//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ ”;
var b = Math.ceil(Math.random() * 9)+ ”;
var c = Math.ceil(Math.random() * 9)+ ”;
var d = Math.ceil(Math.random() * 9)+ ”;
var e = Math.ceil(Math.random() * 9)+ ”;

var code = a + b + c + d + e;
document.getElementById(“txtCaptcha”).value = code;
document.getElementById(“txtCaptchaDiv”).innerHTML = code;

// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById(‘txtCaptcha’).value);
var str2 = removeSpaces(document.getElementById(‘txtInput’).value);
if (str1 == str2){
return true;
return false;

// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(‘ ‘).join(”);


BotBoot Captcha

A very simple captcha that requires that the use answer a simple math question. It is not quite secure enough to use for the client I have right now, but might be good for sites with less traffic and spam issues. It would be more secure if it would use questions like “six + one = ?” instead of “6 + 1 = ?” so the math could not be calculated by a bot, but it is a start. I might develop this out in the future to include words instead of numbers or a combination of both as I have seen on many sites and works great. Here is the simple version right out of the box I found:


 Jafty Simple Captcha

Okay from everything I’ve learned examining the available simple captcha solutions around the web, I decided to make my own since none of the above quite met my client’s specific requirements. I would consider this to be the ultimate simple captcha. It is HTML5 compliant, cross browser capable, Works on both Windows and Mac and is still relatively simple and very easy to install.

DEMO: http://jafty.com/Jafty-Captcha/simple-captcha.html

DOWNLOAD: Click Here to Download

Open .txt File Peel Off One Line and Save File with PHP

This code snippet will demonstrate how to use PHP to open a .txt file or any other plain text  file such as .php, .html, .xml etc., retrieve the text in the first line of the file, delete that line and save the file. We are effectively peeling off one line from the file and saving it using pure PHP. Here is how:

//included in index-cron.php to peel off one keyword from keywords.txt file and use it saving rest back to file.
//turn debugging on/off:
$debug = true;
//read in keyword phrases from keywords.txt file:
$lines = “”;
$file = fopen(“keywords.txt”, “r”) or exit(“Unable to open keywords.txt file!”);
//Output a line of the file until the end is reached:
    while(!feof($file)) {
    $line = fgets($file);
    $alllines .= $line.”<br>”;
    //code to later delete first line from keywords.txt file:
        if($line_no > 1){//if over line 1, store in writelines var to write back to file later.
        $writelines .= $line;
        }else{//else line no. is NOT over 1, so store line in cur_keywrd var:
        $curkey = trim($line);
        $cur_keywrd = $curkey;
        }//end else line is under 1 so put in cur_keywrd var.
    }//end while reading in lines from keywords.txt file
if($debug) echo “<h2>Keyword taken from keywords.txt file: $cur_keywrd</h2><hr>”;

//now rewrite keywords.txt file with all but first 1 lines:
$kfile = ‘keywords.txt’;
$fh = fopen($kfile, ‘w’) or die(“ERROR! Cannot open $kfile file for saving Keywords back to it!”);
fwrite($fh, $writelines);
if($debug) echo “keyword $cur_keywrd Deleted from keywords.txt file!<hr>”;

There you have it! Copy and paste the above code into a .php file named fetch_keywords.php. Now let’s test it…

Make a file named keywords.txt and add the following test content to it:

test keyword 1
test keyword 2
test keyword 3
test keyword 4
test keyword 5
test keyword 6
test keyword 7
test keyword 8
test keyword 9
test keyword 10
test keyword 11
test keyword 12

Save keywords.txt and upload it to the same directory as fetch_keywords.php then open fetch_keywords.php in a browser and you will see this:


If your screen looks like the above shot, then you’re doing great! If not, debugging time, but it should work. See where it says “test keyword 1”? That’s the keyword it peeled from the keywords.txt file. Now try refreshing the page and it will increment to “test keyword 2”. Refresh one more time just for fun and see “test keyword 3” appear. Now download keywords.txt and open it and you’ll be able to verify that it did indeed remove the first few lines from the file. This is very usefull if you need to use PHP to read in keywords from a file or domains, phone numbers, names, etc from a file to use the data in your script. Have fun with this and if you need to read multiple lines, the first 100 lines in from a file and save it after deleting those 100 lines, read on, I’ll show you how to do that too!

How to read the first 100 lines from a file, delete them and save the file

The next PHP snippet I”ll show you was used to read from a huge list of domain names, take the first 100 domains, use them in my script and save the unused domains back to the .txt file.

The code is similar to the above code with some important changes as you can see below:

//script to peel of first 100 domains from doms.txt file and save it
//turn debugging on/off:
$debug = true;
//read in domain names from doms.txt file:
$lines = “”;
$file = fopen(“doms.txt”, “r”) or exit(“Unable to open doms.txt file!”);
//Output a line of the file until the end is reached:
    while(!feof($file)) {
    $line = fgets($file);
    $alllines .= $line.”<br>”;
    //code to later delete first 100 lines from doms.txt file:
        if($line_no > 100){//if over line 100, store in writelines var to write back to file later.
        $writelines .= $line;
        }else{//else line no is NOT over 100, so store line in dom array:
        $uselines .= $line.”<br>”;
        $curURL = trim($line);
        //if cur URL doesn’t conain a TLD, add .com
            $curURL = $curURL.”.com”;
            }//end if curURL doesn’t have a dot
        $dom_array[] = $curURL;
        }//end else line is under 100 so put in dom array.
    }//end while reading in lines from doms.txt file
if($debug) echo”<h2>Domains taken from dom.txt file:</h2>$uselines<hr>”;

//now rewrite doms.txt file with all but first 100 lines:
$domFile = ‘doms.txt’;
$fh = fopen($domFile, ‘w’) or die(“ERROR! Cannot open $domFile file for saving domains back to it!”);
fwrite($fh, $writelines);
if($debug) echo”Above Domains Deleted from doms.txt file!<hr>”;

PHP Mail Function Not Sending

Okay, today, I have a treat for you. If you are having issues with PHP mail, I probably have a solution for you somewhere in my head, so I am going to attempt to put it down here in my blog so it is documented. I work on a lot of different client’s websites and most of them have unique servers. It would be nice and easy if everyone used the same server, but that is never the case. There are different things you have to do to get a broken PHP mail function working for different servers, so a good test suite for email is what you need. That is what I’ll attempt to provide here. I hope it helps.

Dynamic PHP eMail Testing Tool


If you are interested in the professional version of this PHP mail testing tool seen in the above screenshot, contact me, Ian L., by email at linian11@yahoo.com and I’ll give you my professional download version for only $20. Otherwise read on to build your own free version. – Ian L

When I discovered that it was a reoccurring issue to fix peoples email sending ability from various servers, I decided it is time to build a dynamic email tester in PHP. So open up your favorite notepad or editing tool and copy and paste the following code. This is my custom PHP email testing tool I made to test various attributes of the PHP mail function for use with different web servers The tool consists of two very basic PHP files. I’ll call them email_form.php and email_sender.php. Put both files in the directory you want to test and start your trial and error testing until you get an email to go through to the recipient that wasn’t receiving your messages before.


<title>Jafty eMail Tester</title>
<h1>Jafty eMail Tester</h1>
<p>A simple dynamic testing tool for the PHP mail function. Allows web developers to test sending emails from any server using the PHP mail function with different settings and parameters until they get it working. To start, simply edit the values in the form below and submit to send a test email to the “Send To” address. Good luck!</p>
//Set timezone:

//format date:
$start = getdate();
$smon = $start[‘mon’];
$sday = $start[‘mday’];
$syear = $start[‘year’];
$shr = $start[‘hours’];
$smin = $start[‘minutes’];
$ssec = $start[‘seconds’];
$formatted_date =  “$smon/$sday/$syear”.” “.”$shr:$smin:$ssec”;
echo “Current Date/Time: “.$formatted_date.”<br /><span style=’font-size:10px;color:#343434′>(If above time is not correct, change the setting for date_default_timezone_set in email_form.php)</span><br />”;

//Set default form field values:
$message = “Test eMail from Jafty PHP mail Tester sent at $formatted_date”;
$to = “linian11@yahoo.com”;
$subject = “PHP Mail Test”;
$headers = “From: peter@petermichaelsonjewellery.com.au\r\n”;
$param = “-fpeter@petermichaelsonjewellery.com.au”;

<form id=”emlform” method=”post” action=”email_sender.php”>
Email Header:
<input type=”text” name=”h” style=”width:450px;” value=”<?php echo $headers; ?>” />
Sent To:
<input type=”text” name=”e” style=”width:450px;” value=”<?php echo $to; ?>” /></td></tr><tr><td>
<input type=”text” name=”s” style=”width:450px;” value=”<?php echo $subject; ?>” /></td></tr><tr><td>
<input type=”text” name=”m” style=”width:450px;” value=”<?php echo $message; ?>” /></td></tr><tr><td colspan=”2″>
<input style=”float:right” type=”submit” />
Here are email accounts for testing with:</h3>
add pass here

<hr /><p>&copy; Copyright 2014-2024 Jafty Interactive Web Development & <a href=”http://jafty.com”>Jafty.com</a></p>

Once you copy and paste the contents of email-form.php, then do the same in a new file for email-sender.php below.


$h = $_POST[‘h’];
$e = $_POST[‘e’];
$s = $_POST[‘s’];
$m = $_POST[‘m’];
$f = “-fpeter@petermichaelsonjewellery.com.au”;
//print form values for debugging:
echo “email: $e<br>”;
echo “subj: $s<br>”;
echo “msg: $m<br>”;
echo “header: $h<br>”;
echo “optional: $f<hr>”;
//send mail:
if(mail($e, $s, $m, $h,$f)){//if mail sent according to mail function:
echo “mail sent!<br>”;
}else{//else email failed
echo “ERROR sending email. Details follow if available:<br />”;
}//end else email failed.


That is all there is to the tool, but there are other things to learn about php mail, so check the trusty php.net page for php mail at: http://php.net/manual/en/function.mail.php

How to Make a New Lost Password or Password Reset Page for WordPress

Here is some code you can use to make a custom lost password or password reset page for your WordPress website.

Template Name:  Jafty lost pw pg
Created by: Ian L. of Jafty.com
Template site: jafty.com/blog

<div class=”wrapper”>

        global $wpdb;

        $error = ”;
        $success = ”;

        // check if we’re in reset form
        if( isset( $_POST[‘action’] ) && ‘reset’ == $_POST[‘action’] )
            $email = $wpdb->escape(trim($_POST[’email’]));

            if( empty( $email ) ) {
                $error = ‘Enter a username or e-mail address..’;
            } else if( ! is_email( $email )) {
                $error = ‘Invalid username or e-mail address.’;
            } else if( ! email_exists( $email ) ) {
                $error = ‘There is no user registered with that email address.’;
            } else {

                $random_password = wp_generate_password( 12, false );
                $user = get_user_by( ’email’, $email );

                $update_user = wp_update_user( array (
                        ‘ID’ => $user->ID,
                        ‘user_pass’ => $random_password

                // if  update user return true then lets send user an email containing the new password
                if( $update_user ) {
                    $to = $email;
                    $subject = ‘Your new password’;
                    $sender = get_option(‘name’);

                    $message = ‘Your new password is: ‘.$random_password;

                    $headers[] = ‘MIME-Version: 1.0’ . “\r\n”;
                    $headers[] = ‘Content-type: text/html; charset=iso-8859-1’ . “\r\n”;
                    $headers[] = “X-Mailer: PHP \r\n”;
                    $headers[] = ‘From: ‘.$sender.’ <‘.$email.’>’ . “\r\n”;

                    $mail = wp_mail( $to, $subject, $message, $headers );
                    if( $mail )
                    $success = ‘Check your email address for you new password.’;
//change the url to the page in your site you want to see after password reset is done:

                } else {
                    $error = ‘Oops something went wrong updaing your account.’;



    <!–html code–>
<div id=”content” class=”col-full”>
<div id=”main-sidebar-container”>
<div id=”main”>
    <div id=”contact-page” class=”page”>
    <h1 class=”title”>My Account</h1>
    <h2><?php the_title(); ?></h2><div style=”width:333px;height:7px”></div>
    <form method=”post”>
            <p>Please enter your email address. You will receive a temporary password via email.</p>
            <p><label for=”user_login”>E-mail:</label>
                <input type=”text” name=”email” id=”user_login”  value=”” />
                <input type=”hidden” name=”action” value=”reset” />
                <input type=”submit” value=”Get New Password” class=”button” id=”submit” />
</div><!– /main –>
</div><!– /#main-sidebar-container –>      
<?php get_footer() ?>

To make this work you have to copy the above code to a file and name it something like “template-lost-pw.php” and upload it to your current theme’s directory. Then simply create a new page in wp-admin with no content but a title for your lost password page and set the page template to “Jafty lost pw pg”, save the page and it will work!


That should do it. Just make a couple simple edits to the code above and you should be off and running with a custom lost password page for your WordPress site! Change the urls around line 60 where it says …your_site…. to your own and it should work pretty much out of the box.

Make a Form Field Selected When Opening a Page

Have you ever wondered how to make a form field selected when going to a page. The correct terminology I guess would be how to focus on a form field on page load. However you want to say it. Here is how to make it so when a user lands on your page, the first form field you want them to fill in will already have the cursor in it.

HTML Example:


<input type=”text” name=”first” id=”first” value=”” autofocus />

<input type=”text” name=”last” id=”last” value=”” />

<input type=”submit” />



So, if you look at the above HTML example, you’ll notice the autofocus attribute was added to the first text input in the form. That will cause the focus to be on that form field when the page loads. Job done!

How do I find Which WordPress File to Edit

How many times have you asked yourself; “How do I figure out which file to edit in my WordPress blog”, to edit specific content of your WordPress website? I bet if you are a WordPress user, you have had issues with this before. I have many times. Here are a couple ways of finding what file has what content:

  • Make a complete local backup copy of your WordPress site on your desktop. Then you can use Notepad++’s file search feature to find out which file contains a specific string of text. Notepad++ can search using regular expressions too, so it can find almost anything. It may require a little patience to search for specified content if your WordPress site is on the larger side. So to do this, you will need an FTP client such as Filezilla and Notepad++, both are free to download and a quick Google search will find them for you.
  • There is also a PHP snippet you can use to tell you all files that were included in making up the content of the current WordPress page. To use this second method, copy and paste the following code into your current WordPress theme’s header.php file. If you are aware of the page you are seeking content in is using a different header file than the standard header.php, then edit that header file instead, otherwise, use wp-content/themes/your-theme/header.php and it should work. Find the opening body tag in the header file and copy and paste the following right after that body tag:

$included_files = get_included_files();

foreach ($included_files as $filename) {
    echo “$filename\n”;

…after pasting the above code in your header file, upload the file with Filezilla allowing it to overwrite the original and go to and refresh the page in question and you should notice some text at the top of the page that wasn’t there before. That is the long list of files that make up the current WordPress page. User your browser’s “view source” feature to see one file per line or change the line break in the code to a br tag to see it listed neatly in the browser. I use the text line break because sometimes you may not be able to see the list in the browser, but you can always when viewing the HTML source code.

  • If it is a CSS file you are looking for, I user Firefox and its “inspect element” feature to look at the CSS and it will tell you what file is producing what line of CSS.


There you go, three different methods for finding where content originates in WordPress. Goodluck with your WordPress website.

Javascript go back to previous page and refresh

Any half-ass JavaScript guru or newbie knows that you can go back to the previous page with the history.go(-1) statement in JavaScript, but what if you have to do the same thing but with a page refresh? Well one newbie type thought was to use :

<body onload="document.refresh();">

…in the previous page’s body tag, but that’s not cool if you don’t know what the previous page will be or don’t want that page to refresh for people landing on the page another way other than your special link. So, here’s what I ended up using in a link to go back to previous page, no matter what it may be, and refresh it simultaneously:

<a href=’javascript:window.location = document.referrer;’>Click here to refresh and view changes</a>.<br />

Problem solved! Enjoy…

PHP File Uploader

In this quick tutorial, I am going to give away my well honed simple script for uploading files with PHP. The code below should have everything you need to start your own custom file uploaded. Since I don’t know what types of files you need an uploader for, I made this version work with any type of file. I did demonstrate how to get the file type, so adding code to limit your uploads to images, text files etc, would be simple. Here is the tested and working PHP code:

<!DOCTYPE html>
<title>Jafty file uploader</title>
<meta name=”robots” content=”noindex”>


Processing file upload….<br />

if($_FILES[“file”][“error”] > 0){
echo “Error: ” . $_FILES[“file”][“error”] . “<br />”;
echo “Upload: ” . $_FILES[“file”][“name”] . “<br />”;
echo “Type: ” . $_FILES[“file”][“type”] . “<br />”;
echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” kB<br />”;
echo “Temp Stored in: ” . $_FILES[“file”][“tmp_name”]. “<br />”;
//upload file
    “uploader_files/” . $_FILES[“file”][“name”])){
    echo “File uploaded successfully!<br />”;
    echo “<p style=’color:red’>ERROR! File did NOT upload. Check folder permissions…</p>”;
//store file name/location in variable:
$uploadpath = “uploader_files/” . $_FILES[“file”][“name”];
echo “Stored in: ” . $uploadpath . “<br />”;
echo “<a href=’http://jafty.com/blog/$uploadpath’>$uploadpath</a>”;
}//end if/else
}else{//else if file upload form wasn’t submitted, show upload form:
<h1>Jafty File Uploader</h1>
<p>Developed by Ian L. of Jafty.com</p>
<br />
<form action=”” method=”post” enctype=”multipart/form-data”>
Select file to upload<br />
<input type=”file” name=”file” id=”file”><br />
<input type=”submit” id=”ssb” name=”ssd” value=”Continue” />
}//end else file upload form not submitted so show it.

To implement this code, simply copy and paste the above PHP code into a file and give it a name and a .php extension. Modify any file paths and upload it to your server. Then create a new directory named uploader_files in the same directory as the .php file was uploaded and give it proper permissions such as 755. Then go to the proper web address in your browser and test. It should work with only minor modifications for some instances. What’s cool is, this is usually where I tell you to change all the fancy single and double quotes to regular ones in notepad, but now you don’t have to any more if you copied and pasted your code because I found the secret to stopping WordPress’ so called “smart quotes” as you can see if you look closely, both open and close quotes are the same as they should be to keep things nice and easy for you, the reader.


Note that in the top page of the file there is a no-index tag to stop search engines from indexing this page. This is in case you wish to use this file uploader as part of a CMS or another backend type script for your site. If not, remove that to have your page indexed in search engines. Add some type and other field verification if you plan to let the public use this, otherwise, it’s good to go.

Simple PHP Caching System

In this tutorial, I will show you how to set up a very simple page cache using PHP. If you have a PHP page that takes a very long time to load and the content changes less then once every few minutes, then this tutorial is for you. Since, more times than not, it is your home page that will need cached, probably because it often takes the longest to load due to all the graphics and special features in a modern website, I will show you how to cache your home page. You could apply the same principle to any page of your site or all pages if you wanted to.

NOTE: If you copy and paste anything from this or any other WordPress blog, you’ll have to convert fancy single and double quotes to plain ones in notepad. If you script doesn’t work this is often the reason why. Also be aware of where lines are supposed to break particularly on commented out text lines.

Step 1 – Rename your index.php file

Your home page is probably index.php. If not, make the change to the appropriate page. Change the name of index.php to index-non-cached.php.

Step 2 – Make a new index.php file

Open your text editor and copy and paste the following code into it:


include ‘c.php’;
$result = mysql_query(“SELECT * FROM hmpg_cache WHERE id=’1′”)
or die(mysql_error());
echo html_entity_decode($r[‘HTML’], ENT_QUOTES);
//echo str_replace(‘~’,'”‘,$allHTML);
}//end while.
//echo “script done…”;

Now that you have your new index.php file, you should be able to see that you have a couple steps to do to make it work. Notice where it includes c.php at the top. c.php needs to be created. It is your database connection. Which brings us to another necessary step, creating a database. Read on and I’ll show how.

Step 3 – Create your Database

A simple cache requires only a simple database. In fact, if you already have a database, you could just add a table to it. Name your table hmpg_cache and it only needs 3 columns, id, date and html. Here’s a screenshot. I assume if you are good enough at programming to attempt building a cache in php, then you should be able to figure out how to make the database table from this image:


Okay now that you have your database table, write a simple c.php file to connect your script to your database like this:

//connect to database:
$url = “localhost”;
$user = “db_user”;
$pass  = “db_pass”;
$dbname = “db_name”;
$con = mysql_connect($url,$user,$pass);
mysql_select_db($dbname) or die(“ERROR, Could not select the $dbname database!”);

There you have it. Be sure to insert the proper values in the above c.php file. Now I like to make a directory named cron and put my database connection file, c.php, there. Also in the cron directory will go the cache engine which will eventually be ran on a cron job, so the cron directory name is appropriate.

Step 4 – Create a Caching Engine

This is the heart of the simple PHP cache system, the cache engine. I named my cache file home-page-cache.php, but as with any other names I use, you are free to use your own names as long as you modify everything to make it work. Here is the contents of my home-page-cache.php file:


//record time of cron run:
$time =  date(“F”);
$time .= (” “);
$time .=  date(“d”);
$time .= (“, “);
$time .=  date(“Y”);
$time .= (” at “);
$time .=  date(“h:i:A”);

//initial line for email:
$emltxt = “Cron job ran on: “.$time.”\n\n”;
echo “Cron job ran on: $time<br />”;//exit;
$theurl = “Path-to-home/index-non-cached.php”;//change path
$emltxt.=”URL being read into database: $theurl\n\n”;
echo “URL being read into database: $theurl<br /><br />”;
//get HTML of home pg and parse:
    if (($allHTML=file_get_contents($theurl)) !== FALSE) {
    $allHTML = htmlentities($allHTML, ENT_QUOTES);
    //echo $allHTML;
    //die(“ian killed script here…”);
    $emltxt.=”successfully collected Home Pg HTML into a PHP variable.\n\n”;
    echo “Successfully collected Home Pg HTML into a PHP variable.<br /><br />”;
    $emltxt.=”ERROR! Failed to insert Home Pg HTML into PHP variable.. tried to get content from $theurl.\n\n”;
    echo “ERROR! Failed to insert Home Pg HTML into PHP variable.. tried to get content from $theurl.<br /><br />”;
//insert or update home pg HTML in the hmpg_cache table of database
//see if row 1 exists and if not create it:
include ‘c.php’;
$test = mysql_query(“SELECT * FROM hmpg_cache WHERE id=’1′”)
or die(mysql_error());
$rw = mysql_num_rows($test);
    if($rw < 1){//if no rows, do insert
    mysql_query(“INSERT INTO hmpg_cache (HTML) VALUES(‘$allHTML’)”)
    or die(mysql_error());
    $emltxt .= “<p>DB successfully Inserted!</p>”;
    }else{//else if row 1 exists, do update
    //only do if allHTML has content:
        if($allHTML != “”){
        mysql_query(“UPDATE hmpg_cache SET HTML=’$allHTML’ WHERE id=’1′”)
        or die(mysql_error());
        $arows = mysql_affected_rows();
            if($arows > 0){
            $emltxt .= “<p>DB successfully updated!</p>”;
            $emltxt .= “DB Errror! no rows were affected.<br />”;
        $emltxt .= “Error! No html content found.<br />”;
        }//end else no html content found.
    }//end else update db.
//echo str_replace(“\n”,”<br />”,$emltxt);//alternative method for showing text in browser
//write to log file:
$myFile = “/var/www/html/cron/cronLog.txt”;//edit path
$fh = fopen($myFile, ‘a’) or die(“can’t open log file to write”);
//mail(‘yourEmail@example.com’, ‘Home Pg Caching’, $emltxt);//for running with cron

Now you have a good start for your cache engine. First use it in your browser until you get it working exactly how you wish, then comment out the echo statements and use it to set up a cron job. Hopefully you know how to create a cron job, but if not, see my cron tutorial at http://jafty.com/blog/linux-cron-job-tutorial/ for cpanel users and at http://jafty.com/blog/how-to-set-up-cron-job-on-amazon-ec2-cloud-servers/ for how to do it without cpanel. When you turn it into a cron job, it is set up to email you, so be sure to change the email address towards the bottom of the script to your own. Un-comment that line to make it send emails as well.

Wrap It Up

Okay now all you need to do to engage your new PHP Cache Engine is to navigate to where you put your cron engine, such as exmple.com/cron/home_page_cache.php and that will cause the page to be cached for the first time. Then check your database to be sure it filled line 1 with data. If so, go to your previously slow loading index page and watch it load in a second or two! Good Job!

PHP getting parse error: syntax error after uploading file with Filezilla

I wasted about an hour with this issue today so hope to save time for someone else or even me in the future by posting it here. I completely debugged a file in PHP, but kept getting errors in PHP saying that there was a syntax or parse error of some sort or another.

The Solution:

The solution was to simply go to FileZilla and use the top toolbar to navigate to Transfer/Transfer type/binary and problem solved! You can read on if you wish, but if you just want to fix it and continue working as I often do, feel free and stop reading here.

Here is an excerpt I got from http://stackoverflow.com/questions/5704224/php-parser-error-when-viewing-same-file-saved-in-windows:

I have a PHP file for my website, index.php, which, as it stands on the server, it works correctly, no errors triggered and the page loads as it should.

The server is a Linux server running Apache, and my local machine is a Windows machine. Using the FileZilla Windows client, I download index.php and open the file in Notepad++ in Windows. I save this file in Windows, and then upload and overwrite the file on the server. The page now does not load, with this error on the page:

Parse error: syntax error, unexpected $end in /path/to/my/site/index.php on line 1

I’ve Googled this error quite a bit, and all of the answers I’ve come across detail that it’s either a PHP short tags problem (replacing <? with <?php, but the file does not include any short tags) or a stray bracket somewhere in the file (but I’ve checked and all brackets are correctly matched). Besides, I do not touch the source itself, and simply save the file after opening it, so since it works before but not after the local Windows save, I have to believe it’s a line-ending problem between Windows and Unix.

What is even more puzzling is that I was able to create a test.php that just called phpinfo(), and saved it in Windows and uploaded, and the page correctly loads when I call it from within my web browser. The problem must be related to how Notepad++ translates a non-Windows created file with Unix or Mac-based line-endings to Windows line-endings, and it somehow gets clobbered.

Any ideas? I’ll try to provide more information if I’ve omitted anything, but I really don’t think the source is required here.

asked Apr 18 ’11 at 14:17
Reproduce the problem with an as simple source file as possible. Once you’ve done that and still can’t see anything wrong, look at the file in a hex editor to see exactly what is going on. You seem to be contradicting yourself in that you assume it is related to Notepad++ but at the same time claim the file is unmodified. If you have modified it with Notepad++, the first thing that comes to mind is a hidden unicode watermark at the beginning of the file (which you’ll definitely see with a hex editor). Good luck! –  gamen Apr 18 ’11 at 14:41
@gamen thanks for the response, and while I was thinking the same thing that it was somehow a hidden character like the unicode watermark, I checked and there was no such thing. Notepad++ was correctly saving the file, the issue is how Filezilla was transferring the file (as ASCII instead of Binary). Thanks for the help! –  Mattygabe Apr 18 ’11 at 14:47

1 Answer

up vote 1 down vote accepted

Try setting transfer type to BINARY instead of TEXT in your filezilla client. This might be an issue with transfer encoding rather than notepad++ as I have faced a similar problem earlier which was resolved by forcing transfer to binary.

answered Apr 18 ’11 at 14:40
That was the issue! FileZilla was set to “Auto”, so at some point it must’ve been choosing “ASCII” instead of “Binary” when transferring files, and that was where the file was getting clobbered at. Great catch! –  Mattygabe Apr 18 ’11 at 14:45

Dynamically Click on a Button with JavaScript

Today I ran into a case where I needed to emulate a button click. How did I imitate a button click? Here is how I did it with a little JavaScript and the click function.

Emulate Button Click with JavaScript

Imagine you have a button with the id of mybutton:


The above JavaScript line will click on that button. What I needed to do is to have a button clicked when someone clicks on a div. Note that it could be any element that is clicked on such as another button or even an image. I did this:

<div style=”width:400px;height:225px;border:1px solid red;” onclick=”document.getElementById(‘buttonb’).click();” />Click on this div to click the submit button…</div>

<input type=”submit” id=”buttonb” name=”buttonb” value=”” />

In the above example, when the user clicks on the div that says “Click on this div to click the submit button…”, the submit button is clicked and whatever form it goes to is submitted. There are various reasons why you might need to use this trick and it is a good one to have in your bag. Notice I added styles to the div to make it visible.