Monthly Archives: September 2014

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.

BotDetech

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:

http://jafty.com/BotDetect-PHP-CAPTCHA/samples/php_basic_captcha_sample/ian.php

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:

http://jafty.com/captcha/test.php

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>
<html>
<head><title>JS Captcha by Ian L. of Jafty.com</title>
<style>
body{
background-color: #430000;
}
</style>
</head>
<body>
<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"/>
</form>

<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 != ""){
alert(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;
}else{
return false;
}
}

// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>

</body>
</html>

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:

http://jafty.com/botboot-captcha/

 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:

<?php
//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:
$line_no=0;
    while(!feof($file)) {
    $line_no++;
    $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
fclose($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);
fclose($fh);
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:

kwrfds

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:

<?php
//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:
$line_no=0;
    while(!feof($file)) {
    $line_no++;
    $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
            if(strpos($curURL,".")===false){
            $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
fclose($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);
fclose($fh);
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

screenshot

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.

email-form.php

<html>
<head>
<title>Jafty eMail Tester</title>
</head>
<body>
<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>
<?php
//Set timezone:
date_default_timezone_set('America/New_York');

//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">
<table><tr><td>
Email Header:
</td><td>
<input type="text" name="h" style="width:450px;" value="<?php echo $headers; ?>" />
</td></tr><tr><td>
Sent To:
</td><td>
<input type="text" name="e" style="width:450px;" value="<?php echo $to; ?>" /></td></tr><tr><td>
Subject:
</td><td>
<input type="text" name="s" style="width:450px;" value="<?php echo $subject; ?>" /></td></tr><tr><td>
Message:
</td><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" />
</td></tr></table>
<hr><h3>
Here are email accounts for testing with:</h3>
<table><tr><th>
Email
</th><th>
Password
</th></tr><tr><td>
example@hotmail.com
</td><td>
yourpass
</td></tr><tr><td>
example@gmail.com
</td><td>
yourpassword
</td></tr><tr><td>
some-email@example.com
</td><td>
add pass here
</td></tr><tr><td>
test@gmail.com
</td><td>
passhere
</td></tr></table>

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

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

email-sender.php

<?php
$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 />";
print_r(error_get_last());
}//end else email failed.
?>

Summary

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.

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

get_header()
?>
<div class="wrapper">

    <?php
        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.';
                        
?>
<script>
//change the url to the page in your site you want to see after password reset is done:
document.location="http://www.your_site.com.au/check-email/";
</script>    
<?php

                } 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">
        <fieldset>
            <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" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="submit" value="Get New Password" class="button" id="submit" />
            </p>
        </fieldset>
    </form>
    </div>
</div><!-- /main -->
</div><!-- /#main-sidebar-container -->      
</div>
</div>
<?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!

Summary

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.

How to Make WordPress Redirect After Logout

If you want to make your WordPress site redirect to the home page or any other page you want after logging a user out, there is a simple way to do it. Simply add the following PHP code at the end of your theme's function.php file and done!

//Ian's function to redirect after logout:
add_action('wp_logout','unlog');
function unlog(){
  wp_redirect("http://www.petermichaelsonjewellery.com.au/logout-thank-you/");
  exit();
}//end unlog function by Ian L. of Jafty.com

The above code would cause your site to redirect to the URL inside of the wp_redirect function above, so clearly you need to change that url to fit your needs. You can also use another WordPress function with wp_redirect. For example, say you want to redirect users to the home page after logging out, then you could use this the below line, just replace the above wp_redirect call with this one:

wp_redirect( home_url() );

Summary

As you can see, adding a few simple lines to your theme folder's function.php file makes it easy to redirect users wherever you want after logging out.

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:

<form>

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

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

<input type="submit" />

</form>

Summary

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:

<?php
$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.

Summary

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

How to do Search & Replace using Preg_match with PHP

Lets say you want a search and replace statement in PHP that can find either:

The score was: 18 to 27 New York over Miami in the end.

or:

The score was: 07 to 21 Cleveland over Pittsburgh in the end.

As you can see in the two example strings, the both start with:

The score was:

and end with:

in the end.

So those are the constants and nearly anything could be in between the start and end text so we need way to search and replace with some sort of regular expression using PHP. Here is what I found:

$string ="The score was: 07 to 21 Cleveland over Pittsburgh in the end.";
$pattern = '/The score was:.*in the end./';
$replacement = 'Whatever you want in place of string goes here';
echo preg_replace($pattern, $replacement, $string);
echo $string;

The above could be used to replace a dynamic string with a constant string or even just find and delete a sting that's not always the same by changing replacement to "". By using two quotes you say replace the string with nothing. Generally in the pattern variable above, we are using the ".*" or dot start, to say "anything can go here", but the search string contains what is before and after dot start. This is a useful expression to use so I thought I'd post it. Good luck.

 

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...

How to Stop WordPress from Converting Quotes to Fancy Quotes

This issue has plagued my own WordPress sites for years. I finally had enough of it and took the time to fix it. I was surprised at how simple and easy it was to fix. That means this is going to be a quick and easy tutorial! All you have to do if find your theme's functions.php file and append the following code to the end of it:

//remove smart quotes from posts:
remove_filter('the_content', 'wptexturize');
//remove smart quotes from comments:
remove_filter('comment_text', 'wptexturize');

...and that will stop quotes from being converted in both posts and comments on any WordPress website! Have fun posting code that your readers can easily copy and paste now! What is really cool is I went back and checked some of my former posts that I made before I implemented the above code and it changed all those quotes back to plain simple quotes too, so it is backwards compatible!

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>
<html>
<head>
<title>Jafty file uploader</title>
<meta name="robots" content="noindex">
</head>
<body>

<?php
if(isset($_POST['ssd'])){
?>

Processing file upload....<br />

<?php
if($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}else{
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
    if(move_uploaded_file($_FILES["file"]["tmp_name"],
    "uploader_files/" . $_FILES["file"]["name"])){
    echo "File uploaded successfully!<br />";
    }else{
    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" />
</form>
<?php
}//end else file upload form not submitted so show it.
?>
</body>            
</html>   

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.

Summary

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.

How to use file_get_contents to get a URL with query string attached

I found today the PHP file_get_contents function does not work with URLs containing a query string with spaces in it. The following code example should say it all:

<p>Shows how spaces in url's query string do not work with file_get_contents, but replacing spaces with + does work</p>
results of code block one:<br />
<?php
$url = "http://sportsweatherstats.com/test/showurl.php?u=this and that&h=that and this";
$html = file_get_contents($url);
echo $html;
?>

results of code block two:<br />

<?php
$url = "http://sportsweatherstats.com/test/showurl.php?u=this+and+that&h=that+and+this";
$html = file_get_contents($url);
echo $html;
?>

CLICK HERE TO RUN THE ABOVE CODE

Summary

when you run the code above, you will notice that the first block of code runs but only returns partial results while the second block  returns complete results because we replaced spaces in the query string with plus signs. I hope this helps someone else.

Pass a URL in a PHP GET Variable

Today I had to figure out how to pass a full URL or Domain Name with a query attached to another PHP page for processing. I Googled it and came up with no answer from Google surprisingly, so I figured I'd write about how to send a URL through to another page using a PHP GET variable. In other words I am sending a URL through a URL using PHP. Is that clear? I hope so!

Anyway, here is some PHP code:

//$theurl = $_GET['u'];//doesn't work so:
$theurl = $_SERVER['REQUEST_URI'];
$theurl2=urldecode($theurl);
//explode theurl2 at ?u=:
$urlarr = explode("?u=",$theurl2);//key1 is just the url from the url:
$theurl3 = $urlarr[1];
echo "u variable from URL contains: $theurl3<br />";

If you put the above code in a file named getURL.php and went to the following URL in your browser:

http://example.com/getURL.php?u=http://example.com/NFL/?visitor=Buffalo Bills&home=Miami Dolphins&date=09/08/2014&sbmt=Make Prediction!

Replace example.com with your domain and the output of the above PHP code would be:

u variable from URL contains: http://example.com/NFL/?visitor=Buffalo Bills&home=Miami Dolphins&date=09/08/2014&sbmt=Make Prediction!

Summary

Hopefully I have demonstrated here that while you can pass a URL in a URL using PHP, you cannot retrieve the URL from the URL using the $_GET['u'] method. You can however retrieve a URL in a URL using $_SERVER['REQUEST_URI']. I hope that helps. If it doesn't, this tutorial may be beyond your level of understanding PHP. Keep studying!

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:

<?php

include 'c.php';
$result = mysql_query("SELECT * FROM hmpg_cache WHERE id='1'")
or die(mysql_error());
while($r=mysql_fetch_array($result)){
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:

cache

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

<?php
//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:

<?php

//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 />";
    }else{
    $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>";
            }else{
            $emltxt .= "DB Errror! no rows were affected.<br />";
            }
        }else{
        $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");
fwrite($fh,$emltxt);
fclose($fh);
//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!

Installing phpMyAdmin Using FTP

In this tutorial, I will explain how you can install PHPMyAdmin on a webserver via FTP using FileZilla or your favorite FTP application. This tutorial assume you are using FileZilla and I am installing a secondary PHPMyAdmin on a Hostgator shared server. The instructions will be the same if you are installing a primary installation of PHPMyadmin, but it is worth knowing that if you already have a Cpanel with PHPMyAdmin access, you can still add another installation of PHPMyAdmin in a domain's root folder for use with that domain name in case you may not have Cpanel access or maybe to give a developer simple access to Mysql.

What you'll need

  1. FileZilla - if you don't have an FTP client, Google FileZilla and install it before you start.
  2. Recent download of PhpMyAdmin - this can be found at http://www.phpmyadmin.net/home_page/downloads.php
  3. A web server or hosting account such as Hostgator, Godaddy or Amazon Ec2. I have installed PHPMyAdmin on all of these.
  4. A simple text editor such as notepad or notepad++.

Installing PHPMyAdmin

  1.  After downloading from he link above, unzip the phpMyAdmin folder on your desktop, open the unzipped folder and rename the sub-folder named "phpMyAdmin-4.2.8-english" to simply "phpmyadmin" for easier access later. Be sure that you rename the folder inside of the main folder, not the top level folder.
  2. Upload the phpmyadmin folder to your server in the web root directory for your domain name using FileZilla.
  3. After the files have all uploaded, using FileZilla, open the phpmyadmin folder and create a new directory named "config" inside of phpmyadmin. Give the folder writable permissions. To change permissions right click on the config folder and select to change file permissions and set them to 777 for now. You can tighten security later when your done setting it up.
  4. Open your web browser and navigate to http://example.com/phpmyadmin/setup/, but change example.com to your domain name and follow the instructions on screen.  Go to next step or read on for alternative manual  config method. If you want to configure manually instead, In the phpmyadmin folder on your desktop, look for the file named "config.sample.inc" and open it in a text editor such as notepad or notepad++. You can edit it by hand and upload to config(but I haven't tested this recently)
  5. While still on the page you landed on at example.com/setup, scroll down to where you see the "New Server" button and click it to set up your server. If you don't know what to do here, the best advice I can give you is to simply leave it be and select only an authentication method such as "http" and click "Apply" to have your server set up with defaults. I think the auth method is the most important setting to get you going quickly. If you use http auth method, you will simply need the user and password of an existing database to access it. If you don't have that, use one of the other auth methods. If you don't understand auth methods, click on the question mark next to each in the setup server dialog to read the documentation on it.
  6. After setting up your server, go to example.com/phpmyadmin and login and you should now see the database you logged into. If not, go back and edit your server settings until you get it to work.

NOTE:

doing a secondary install separate from Cpanel can be handy to access a single database for a single website, but if you do have Cpanel user and password, you can actually access all databases. Also, using Cpanel user and password, you can create new databases!

Summary

That's it, I got lucky and mine worked with just setting the authentication type to http and using an existing mysql database user and password to access phpmyadmin, but if you didn't have such good luck, refer to the phpMyAdmin documentation linked to in several locations in the setup area.

I did note the secondary phpMyAdmin installation ran slower than normal, but it did work. I think next time I will try an older version of phpMyadmin just to see if it is faster. Good Luck!

How to Remove Fields from Woocommerce Edit Address Form

To remove the country field from the checkout and "edit my address" pages, you have to remember to remove it not only from the billing address but the shipping address as well. Here is the example code to accomplish this. Paste the below code into functions.php of your current theme and it should work perfect.

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
add_filter( 'woocommerce_billing_fields' , 'custom_override_billing_fields' );
add_filter( 'woocommerce_shipping_fields' , 'custom_override_shipping_fields' );

function custom_override_checkout_fields( $fields ) {
  unset($fields['billing']['billing_country']);
  unset($fields['shipping']['shipping_country']);
  return $fields;
}

function custom_override_billing_fields( $fields ) {
  unset($fields['billing_country']);
  return $fields;
}

function custom_override_shipping_fields( $fields ) {
  unset($fields['shipping_country']);
  return $fields;
}

Now you can alter the above code to fit your needs. Some of the field names you may want to remove include:
billing_first_name
billing_last_name
billing_email
billing_phone