Monthly Archives: February 2013

How to do a PHP MySQL Insert into a Database Table

In this tutorial, we'll learn how to do a simple MYSQL INSERT using PHP.

First prepare you variables:

$first = "Ian";
$last = "Lin";
$email = "linian11@yahoo.com";

Second, include your database connection string:

include 'DB_connection.php';

Do your query:

mysql_query("INSERT INTO your_table_name (first,last,email) VALUES('$first','$last','$email')") or die(mysql_error());

Last, close your connection:

mysql_close($con);

That really should be self-explanatory...

Flexy Template Engine Tutorial

Okay this is for anyone still interested in Flexy Templates. I know it's a little outdated, but there are still thousands of websites using it at least and chances are you will get a job that requires the modification of Flexy Templates sooner or later if you are a developer.

Installing Flexy

Stay away from the documentation on Flexy from the Pear site because it sucks! I had to figure this out on my own. But do go to http://pear.php.net/package/HTML_Template_Flexy/redirected and download the source code.

Do not use the installers because they install everything in the wrong damn directorys. Sorry I don't usually cuss in my blog, but this pissed me off because it took me hours to come to the conclusions on this page because they didn't document it well or install it correctly from their installers. It may have something to do with the fact that the Flexy Engine hasn't been update since 2009 though, so I hold no grudges.

Installing Flexy

Check that you have pear installed first by typing "pear" at the command prompt. If you have pear installed it will show a list of pear related packages or something like that. Use Putty to get a command prompt(Google "Putty download") if you don't have direct access to your server.

If you don't have pear installed install it with:

wget http://pear.php.net/go-pear.phar
php go-pear.phar

Download the Flexy Files from:

http://download.pear.php.net/package/HTML_Template_Flexy-1.3.12.tgz

You will need 7-zip or similar program to extract it into a tar and then into a folder. Download 7zip from:

http://downloads.sourceforge.net/sevenzip/7z920.exeYou will have to right click on the file and select  "7 zip/extract  files" and it will add a new folder which you then have to open and extract the file inside the same way to finally get the package completely unzipped.

Locate the main folder and rename it from HTML_Template_Flexy-1... to simply "Flexy" to make things easier.

Then upload the Flexy folder to your working web directory. Mine was var/www/html. That is what the installer doesn't do. It installs from the installer to a directory below the web root which I found to be useless, but I am a rookie at this right now, however, for all you other rookies, this is how to get going.

Now disregard all the tests in the test folder as I found them to be useless and deleted them. More aggravation! Try this simple hello world script to get going with Flexy:

Live Flexy Example

First make sure your directory structure is set up properly. You should have your web root folder which is usually named something like html or htdocs. Then inside that is where you should have uploaded your Flexy folder to. Okay good.

Open the Flexy folder and create a directory called templates and another called compiled.

Now open a text editor and enter the following into it which is going to be your hello_world.tmpl file:

<html>
  <head></head>
  <body>
    <h2>{intro}</h2>
    <h3>{testing}</h3>
  </body>
</html>

Now save the file as hello_world.tmpl. Upload the file to the Flexy/templates directory. Now open a new file we will call hello_world.php and insert the following text into it:

<?php
// change error reporting level
error_reporting(E_ALL & ~E_NOTICE);

// include class
require ('HTML/Template/Flexy.php');

// set class configuration
$options = array(
    'templateDir'   => './templates',
    'compileDir'    => './compile',
);

// initialize template engine
$flexy = new HTML_Template_Flexy($options);
 
// define object and properties
// corresponding to template variables
$flexy->setData('intro', 'Hello World!');
$flexy->setData('testing', 'This is just one thing Flexy can do...');

// compile template and interpolate object
// display result
$flexy->compile("hello_world.tmpl");
$flexy->output();
?>

Save this file right inside the Flexy directory, then go to your browser and enter something like your_site.com/Flexy/hello_world.php and you should see your script in action. However, if you didn't think to make the compile directory writable, you may get an error that looks like this:

can not write to 'compileDir', which is './compile'
Please give write and enter-rights to it

...in which case, simply use your FTP editor such as FileZilla to change the permissions of the compile directory you created earlier inside the main Flexy folder. Change to 777 for now but you may want to tighten up security later when in production use.

If it works, you should see the following text on your screen when you go to your-site.com/Flexy/hello_world.php:

Hello World!

This is just one thing Flexy can do...

Short and sweet the way a hello world example should be! However, I did add a little more detail later on at one of my readers request, so I hope this is enough to get you going now.  I couldn't find anything like this until I looked for two days online, so hopefully this helps someone. Please comment below if it does so I feel better:-)

 

 

 

 

Converting PostgreSQL Database to Mysql Database

I am writing this tutorial because I couldn't find out how to do this successfully on the internet by doing a Google search and had to figure it out on my own. Sometimes, when doing web development, we have to do that regardless of how much time and how many tries it takes. In the end here is the solution I found to convert my PostgreSQL database into a MySQL database. I am not saying this is the best or only solution in the world to do this, but it is the only one that worked for me. There was online converters that did not work in my case and there are complicated database management utilities you can download and user from the desktop, but they are nearly impossible to use if you don't have a doctorate in Computer science and about 20 years of experience behind your belt. Anyway, Here is how I did it:

 

  1. I used phppgadmin to export the tables one at a time in CSV format. To do so, simply open your phppgadmin, go to the table you want, click on "Export" then select "data only" and for "Format", select "CSV" from the drop-down. Then tick the download option near the bottom and click the "Export" button to download the CSV file to your local machine.
  2. Now open phpmyadmin in your browser and select a database to add the table to or create a new database and select it.
  3. with the database selected, click on the "Import" tab.
  4. Click "Browse" and select the dump file created in step one. If the dump file is larger than 2,000 KiB see the section below for special instructions for larger files.
  5. For "Format of imported file" select "CSV".
  6. For "Fields terminated by", enter a comma.
  7. Place a check in the box that says "column names in first row".
  8. Leave the rest of the options set to default and click the "Go" button.
  9. You will see it created a new table and named it something like Table1. Change the table name according to your needs and you are done. You may need to view the structure and make some changes, but it will work as-is for most situations.

Importing Large files bigger than 2,000 KiB

To import larger files, you have to break up the dump CSV file into sections. Here is how:

  1. Start from the bottom and copy the last 500-3000 lines to the clipboard, depending on how much data is in them. Try 2000 and if it is still over 2,000 KiB, do the math and try again.
  2. Paste the data into a new CSV file.
  3. From the original dump file, go to the first line and copy it and paste it to the first line of the new CSV file you have created.
  4. Save the file as somename.csv.
  5. Follow the above instructions to import the file into a table and repeat as many times as needed.

 

Install Pear from Linux Command Prompt

Here I will cover how to install Pear on a Linux box from the command line. I am using an Amazon Linux AMI in the EC2 environment, but the instructions are the same for any Linux, Ubuntu like webserver.

Check if Pear Already Exists

To make sure you don't already have Pear installed type the following at the command prompt:

pear

If it already exists, typing pear will produce a long list of text, otherwise it will tell you it doesn't exist...

Install Pear

From the command prompt, type:

wget http://pear.php.net/go-pear.phar

then type:

php go-pear.phar

To test that it works type:

pear

and you should get a list of Pear related info. If you didn't get anything or got an error, make sure you are in the user/bin directory or the directory where you installed pear. You can make it work globally by adding user/bin to your PATH.

 

Write newline to shell script with PHP without control M showing up

Okay, this was one of the most aggravating experiences I had today. I spent over two hours trying to get rid of the annoying Control characters followed by an M in the named.conf file that was writing to from a PHP script. Therefore I posted this post to help anyone else that has this issue. What's weird is the solution that worked I tried as one of my first attempts, but I must have uploaded the file with the change wrong because it didn't take, but anyway, this is the solution:

Example Problem:

I was writing a new line to the named.conf file and at the end of the line, I wanted a newline so next time I write to the file, it is on a new line. Here is something like what I had in my PHP file that writes to the config file:

$line = "zone: a zone file named here...

";

Then when I open my named.conf file in the VI editor I get this:

zone: a zone file named here...^M

Solution:

$line = "zone.......some text here n";

So, as you can see the solution is simply to include the n newline in Linux for PHP to write a newline to the end of the line in the file. I did this after trying just about everything else, so good luck with your project and upload everything twice if you are not sure because that's what ended up costing me two hours of coding time.

 

Parsing Data from textarea by newline or comma with PHP

I was presented with a job where I had to parse lines from a textarea with PHP today and here is what I found to be the best working solution:

<?php

//if submit is hit:
if(isset($_POST['sbmt'])){
$doms = trim($_POST['doms']);
$textAr = explode("\n", $doms);

    foreach($textAr as $line) {//for ea. dom in textarea:
    $curURL = trim($line);
    echo "$curURL<br />";
    }//end foreach domain.

}//end if submit was hit.
?>
<h1>Read Lines from Textarea with PHP</h1>
<form method="post" action="">
<textarea name="doms" rows="12" cols="60">
seers.com
homedebo.com
quizknows.com
amizon.com
</textarea><input type="submit" name="sbmt" value="Check for Misspellings" /><hr />
</form>

I have found the above method to be the most reliable, but if you need an alternate solution, read on...

 

 

Here is a very nice alternate solution I found on Stack Overflow for parsing string data from a form's textarea that has newlines and/or commas separating the values in the textarea. Normally this is a real pain to deal with, but a single line of PHP code makes it really easy as I discovered. Here is the one-line solution and a full example script follows:

Alternate Solution:

Note that this method doesn't work for all cases and the above one should, but should the above solution fail for any reason, try the following one:

$doms = preg_split("/[rn,]+/", $dom, -1, PREG_SPLIT_NO_EMPTY);

Working Example:

<form method="post" action="">
<br />
<strong>Domain Names: (enter each domain on a newline or separate them with commas)</strong><br />
<textarea id="dom" name="dom" rows="17" cols="33"></textarea><br /><br />
<input style="margin-left:360px;" type="submit" id="sbmt" name="sbmt" value="Parse" /><br />
</form>

<?php
//now to process above info from form and insert the data in config files:
if(isset($_POST['sbmt'])) {
//collect form data:
$dom = $_POST['dom'];//raw user input text into domain names textarea needs parsed!

//parse domains entered by user into dom textarea and put in doms array:
$doms = preg_split("/[rn,]+/", $dom, -1, PREG_SPLIT_NO_EMPTY);//array of domains

    foreach($doms as $dname){
    echo $dname."<br>";
    }//end foreach domain.

}//end if form submitted.

?>

What's so nice about this is that I have found it to be almost error proof and idiot proof because the user can either enter values separated by commas, newlines or even both, so it works all the time, regardless of the method used to enter the values into the form.

 

Centering Anchor Link Tags

Have you ever tried to center a link using text-align:center? If you have, you know it doesn't work. There are a few ways to center a link and some are more correct than others, but I wanted to offer an alternative solution. Most times, I think people just put the link in a containing div and set the text-align attribute there. What do you do if you don't want to add a new element to your HTML though? Here is one solution:

<a style="position:relative;left:50%;width:200px;margin-left:-100px" href="http://www.jafty.com/">Go to Jafty!</a>

One thing you have to pay attention to is the width and margin-left in the style attributes though. What I do is estimate or measure the actual length of the text between the opening and closing anchor tags and use that as the width. Then set the margin-left value to negative half of the width. So if your width was 200px, your margin-left would be -100px. If you get the width close, it will be reasonably well centered. Experiment with different values always keeping the left margin to negative half of the width and it will be easy as pie in July!

Write a PHP Script to List Domains in Bind Named DNS

The following PHP code can be used to list the domain names in a bind DNS nameserver. It gets the domains from the /var/named directory. If your DNS server has its host files in a different directory, you may have to edit the script to include that directory. You will also have to edit the nameserver host file name to keep it from showing up in the list of domains since you probably don't want to show that file as it isn't for external domains and is for the nameserver itself.

 

<?php
//List Domain names in BIND9 server
//script created by Ian L. of Jafty.com
//created on 2-23-2013
//Version: 1.00
//Last updated on: 2-23-2013 by Ian L.
//Description: Lists existing domain names in BIND DNS server according to the files in the /var/named directory

if ($handle = opendir('/var/named')) {
//start counter:
$cnt = 1;
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
        //see if it is a host file and list if so:
        //does the entry contain ".hosts"?
            if(strstr($entry,".hosts") && !strstr($entry,"nameserver_domain.com")){
            //strip ".hosts" from entry:
            $domname = str_replace(".hosts","",$entry);
            echo "$cnt - $domname<br />";
            //increment domain count:
            $cnt++;
            }//end if contains .hosts then list it.
        }
    }
    closedir($handle);
}
?>

Edit the file and save it to the HTML directory or web root of your DNS server. You will have to replace "namserver_domain" with your nameserver's domain name and may need to edit the path to your master zone files. You also may need to edit the file extension or naming format of the zone files themselves. This script assumes you use the default zone file naming convention of example.com.hosts, but if your DNS server uses something else, replace where it says hosts with whatever your server uses.

ADNUT Automatic Domain Name Update Tool

I have been building a lot of DNS applications lately and found a great need for a new  PHP simple dynamic DNS update application. My solution was ADNUT or the Automatic Domain Name Update Tool. ADNUT is mostly PHP with a simple layer coded in C to restart the named/Bind service in the background. I had to use a few lines of C to make it secure, but installation is simple if you follow the instructions. In fact it is much easier than any of the existing domain name update clients I have seen to date. Simplicity is the most essential element in coding in my opinion. If you start out simple, you can build something into anything you desire. This tool has that in mind. It started out as a Proof of Concept and later was developed into a fully functional PHP dynamic domain name update tool for Bind, Bind9 and/or Named.

Here is how to implement ADNUT on a Bind9 DNS server.

  1. Build and compile the named restart script by following the instructions at http://jafty.com/blog/?p=186 Just follow the part of the tutorial for writing and compiling the named_restart.c file and stop there.
  2. Start a new folder in your /var/www/html directory called adnut.
  3. Open your notepad application for coding and copy and paste the code in the next step and save the file as index.php in the adnut directory.
  4. <?php
    /* ############## ADNUT Automatic Domain Name Update Tool #######################
    * This script is for dynamic setup of Domain names within Bind9 DNS
    * Created By: Ian Lincicome of Jafty.com
    * ADNUT Website: http://jafty.com/blog/?p=190
    * WARNING! Use at your own risk, Ian L. assumes no responsibility for issues arising from use of this script on any computer.
    */
    //Configure the following variables according to your individual situation:
    $nameserver1 = "ns1.example.com";  //main nameserver subdomain
    $nameserver2 = "ns2.example.com";  //second nameserver subdomain
    //Dir and file info for config files(these defaults should work in most cases):
    $namedConf = "/etc/named.conf";          //path and name of named/bind configuration file
    $zoneDir = "/var/named/";                //Direcory to store zone files(often /var/named)
    ?>
    <h1>ADNUT</h1>
    <p style="font-weight:bold">Automatic Domain Name Update Tool</p>
    Instructions:<br />
    <ol>
    <li>Take a new domain name and point it to your nameservers in your domain name provider's control panel.</li>
    <li>Then simply enter the domain name below with the IP address of the web server you want to point it to and that web server's web root directory and wait a few min for the domain change to take effect. For more information visit <a href="http://jafty.com/blog/?p=190">The ADNUT Blog</a>
    </li>
    </ol>

    <form method="post" action="">
    <h2>Domain name info for zone and config files</h2>
    Domain name:
    <input type="text" id="dom" name="dom" value="" /><br />
    Time To Live(ttl):
    <input type="text" id="ttl" name="ttl" value="900" /><br />
    Web Server IP Address:
    <input type="text" id="ip" name="ip" value="" /><br />
    Admin Email Address:
    <input type="text" id="eml" name="eml" value="" /><br />

    <input type="submit" id="sbmt" name="sbmt" value="Create Records" /><br />
    Pushing the "Create Records" button will create a master zone file in var/named, edit the etc/named.conf file. Be careful using this tool, incorrect entries will crash your DNS server!<br />
    </form>

    <?php
    //now to process above info from form and insert the data in config files:
    if(isset($_POST['sbmt'])) {
    //collect form data:
    $dom = $_POST['dom'];
    $lifetime = $_POST['ttl'];
    $IP = $_POST['ip'];
    $eml = $_POST['eml'];
    //replace @ with . in email:
    $email = str_replace("@",".",$eml);

    //build the master zone file path and filename:
    $hostFile = $zoneDir.$dom.".hosts";

    echo "Setting up DNS entry for:<br />Domain name:$dom<br />TTL: $lifetime<br />Webserver: $IP<br />Webmaster Email: $eml<br />Nameserver 1: $nameserver1<br />Nameserver 2: $nameserver2<br />Master Zone File: $hostFile<br />named.conf File: $namedConf...<br />";

    //create the example.com.hosts file in var/named(or dir from $zoneDir)
    //create serial number incremented ea. min by PHP date function:
    $serial = date("ymdhi"); //year, month, day, hour, min like: 1302300659
    $fh = fopen($hostFile, 'w') or die("can't open file");
    //prepare the contents of the hosts file:
    $stringData = "$ttl $lifetime
    $dom.  IN      SOA     $nameserver1. $email. (
                            $serial
                            1800
                            1800
                            3600
                            3600 )
    $dom.  IN      NS      $nameserver1.
    $dom.  IN      NS      $nameserver2.
    $dom.  IN      A       $IP
    www.$dom.      IN      A       $IP";

    //write the contents to the host file in var/named:
    fwrite($fh, $stringData);
    fclose($fh);
    echo "<p>data written to $hostFile</p>";

    //Append zone entry to the etc/named.conf(or file named in $namedConf):
    $fh2= fopen($namedConf, 'a') or die("can't open file");
    //prepare the contents of the hosts file:
    $stringData = "zone "$dom" {type master;file "$hostFile";};";
    //Append the contents to the config file:
    fwrite($fh2, $stringData);
    fclose($fh2);
    echo "<p>data written to $namedConf</p>";

    echo "<h3>Host file content:</h3><span  style='color:blue; text-decoration:underline' onclick='document.getElementById("showHost").style.display="";'>Show Master Zone file content</span><br /><div id='showHost' style='display:none'><pre>";
    //print contents of host file to screen:
    $file_handle = fopen($hostFile, "r");
    while (!feof($file_handle)) {
       $line = fgets($file_handle);
       echo $line;
    }
    fclose($file_handle);
    echo "</pre></div><br /><br /><h3>named.conf Content</h3><span style='color:blue; text-decoration:underline' onclick='document.getElementById("showConf").style.display="";'>Show named.conf file content</span><div id='showConf' style='display:none'><pre>";
    //print contents of named.conf file to screen:
    $file_handle2 = fopen($namedConf, "r");
    while (!feof($file_handle2)) {
       $line2 = fgets($file_handle2);
       echo $line2;
    }
    fclose($file_handle2);
    echo "</pre></div><br /><br /><p>restarting named...</p>";
    //restart named using the named_restart script coded in C in the /var folder:
    exec('/var/named_restart');
    echo "<p>The DNS server has been restarted to finalize your domain configuration... Your domain name should resolve to $IP within a few minutes, but may take up to 72 hours.</p>";

    }//end if submit button was hit.
    ?>

  5. Now go to your browser and enter yourdomain.com/adnut and you should see the front end of ADNUT. Before you do anything with it read the next steps.
  6. From your command line window, check the status of the named service  by typeing: sudo service named status and note the number of zones because you will need to verify they increase later.
  7. Test the app by first setting up the domain name you want to use. To do this, you must change the nameservers for that domain to your nameservers that you are running ADNUT with and which you should have configured ADNUT with by replaceing ns1.example.com and ns2.example.com with your own nameserver URLs in the above script.
  8. After you have pointed your domain to your nameservers, enter that domain name into the form along with the IP of the server you want it to resolve to and the admin email you want in the zone records then click "Create Record".
  9. Now if all went well, it will have created a new master zone file in your zones directory(var/named usually) and it will have added a line to your named.conf file and restarted the named service(restarted Bind DNS server). To verify this, type sudo service named status again and compare the number of zones with what you got before and it should be one greater if it worked. If not, troubleshoot by following some of the tips below.

Troubleshooting:

First of all, if you are having problems, DNS is complex and not for beginners. If you would like to hire me to install this script and/or build one like it or even expand on it, I would be happy to do it for you at a very reasonable rate. My rates are far less than most developers with this type of knowledge in the USA, far, far less.

If the ADNUT script didn't work, try adjusting permissions. I think I had to temporarily change permissions of etc and var/named to get it to work. try that first, but be sure to tighten security before going live with your nameservers and ADNUT. If you have to give root permissions to the Apache or ec2-user to execute the named_restart script, then be sure to add a line to your sudoers file later and change permissions back to secure the server. Open them to get it working so you know what you need and close them later is what I normally do. Most likely if ADNUT is not working, it is due to permission errors so start there. Google "Running PHP script as root" for more help on permissions for this application.

 

How to Restart Named or Bind from PHP script

I struggled with this for hours so I am posting it so others don't have to. Here is how to restart your BIND DNS server or Named service from a PHP script.

Comple a C script to do the work

first change to su with:

sudo su

from the linux command line

Go to /var direcory and type vi named_restart.c to create a C file.

Then copy and paste the follwoing into the VI editor:

/***********************************************************
 * Script created by Ian L. of Jafty.com
 * Desc: restarts named DNS service
 ***********************************************************/

#include <stdio.h>
#include <stdlib.h>

int main() {
  if (!setuid(geteuid())) {
    system("/bin/echo '/sbin/service named restart > /dev/null 2>&1' | /usr/bin/at now");
  } else {
    printf("Couldn't set UID to effective UIDn");
    return 1;
  }
  return 0;
}

Next enter the following commands at command prmpt"
cc -o named_restart named_restart.c

or

gcc -o named_restart named_restart.c

If neither of the above work, type:

yum install gcc

then try the gcc command again.

then type this at command line:
chmod +s named_restart

To test to see if it's working, type:
service named status
and make note of the no. of zones
Add a new zone to the DNS system then type:
./named_restart
from within the /var directory
Then type:
service named status
and see if the no. of zones increased by one. If it did, the script worked from the command line and you are halfway home.

Write the PHP script

Now it's time for PHP to do it's magic. Open a php file and enter the following PHP code:

exec('/var/named_restart');

That's all there is to it. You may have to fool around with permissions to get it to work, but this is what I used.

 

Form Fields are not Populated after Pressing Back Button

On a recent project of mine, I had a registration form in a two step registration process. Sometimes a user might want to press the back button to make changes to the information they filled out in step one. Unfortunately, every time I filled in the step one form and submitted it to go to step two, I would press the back button and the form for step one would be empty. It's always something right? well, I did  a quick bare-bones style test case to see what was causing this and to see if I could recreate the issue and when I entered a basic form with one field, submitted it and went back, the data was there. Confusing to say the least, but in this post, I will solve the issue or die trying.

Below is a good example of old fashioned trial and error PHP and HTML debugging. I did find the problem and I won't make you read this entire post to get the answer, however I left the test cases for educational purposes. I think it serves as a good example of what us coders have to go through to solve seemingly small issues sometimes.

The Problem

The problem or cause of the form data being gone after the back button was hit was something to do with the PHP session_start function at the top of the script. When I commented it out, the form data worked as expected and was present after pressing the back button. Hopefully this post will save someone some debugging time by getting them right to the root of the problem, session_start. Read on to see how I fixed this.

The Solution

After a few long minutes searching Google, I did find a  way to fix this issue. Simple add the following line of PHP code directly before your session_start function and it all works fine. Here is the code you need to add just before session_start in PHP:

session_cache_limiter('public');

TEST ONE:

first I made two simple scripts, a HTML form and a processing script with the following contents:

HTML in formtest.html

<form method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>

PHP in process.php

<?php
//form back button population error debug testing script:

//get data from formtest.html
$n = $_POST['name'];
echo "<h3>Name entered into form was $n now hit backbutton to see if it is still populated in the name field of the form on prev. page.</h3>";
?>

This worked as expected, so I had to throw in more variables to attempt to find out what causes the form to not populate when going back via the browser back button. So, next I tried changing just the HTML page to this:

TEST TWO

<!DOCTYPE html>
<html>
<head>
<body>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" /
<form id="regform" name="regform" method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
</html>
</head>
</body>

So I added the HTML5 DOCTYPE declaration and basic HTML page tags as well as an id and name to my form to see if by chance any of these might be causing the issue however unlikely it seemed. But it still worked when I tried it, meaning the form field was still populated when I pressed the back button after submitting it. So where is the problem? Next I added more to the form as follows:

TEST THREE

<!DOCTYPE html>
<html>
<head>
<body>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<form id="regform" name="regform" method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
</html>
</head>
</body>

It still worked, so it wasn't the DOCTYPE, content type form id, name or basic HTML tags causing the issue. Next I tried making some additions to process.php, but I wont' post them because the problem wasn't there at all. After that, I changed formtest.html, the basic form testing HTML script to a PHP script since the form that was causing issues was a PHP script. I also added a dynamically included header so my new formtest.php script looks like this:

TEST FOUR

<?php
include 'header_partner.php';
?>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<form id="regform" name="regform" method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
</html>
</head>
</body>

Finally, I recreated the problem, but the only question that remains is was the problem due to using a PHP script to submit the form from or was it something in the included header.php file that I included at the top of the script, so time to narrow down the possible causes. I took out the php include and closing HTML tags at the end of the page, so now my formtest.php script looked like this:

TEST FIVE

<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<form id="regform" name="regform" method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
basically it was the same as test one above, but using a PHP file instead of an HTML file, so if the form data isn't present on going back this time, I know the problem lies with PHP. However, the problem was gone and the form data was there, so the problem isn't PHP itself, but it did let me know that the problem now lies in my include file or just having PHP tags themselves before the form, so first I added just PHP tags before my form so that formtest.php looked like:

TEST SIX

 

<?php
//this is s PHP comment....
?>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<form id="regform" name="regform" method="post" action="process.php">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
Well, that still didn't cause the issue again and the data was there on returning to the page after pressing the back button, so the problem has to be in header.php right? Here is header.php contents:

TEST SEVEN

<?php
//start session vars and get user email for every page header file is included in:
session_start();
//get email from session var set in login.php script:
if(isset($_SESSION['user_email'])){
$eml = $_SESSION['user_email'];
//get member's ID
include 'c.php';
$idq = mysql_query("SELECT * FROM members WHERE email='$eml'")or die(mysql_error());
    while($idr = mysql_fetch_array($idq)) {
    $mid = $idq['id'];
    }//end while
}
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<link rel="icon" type="image/png" href="images/lock.png" />
<link href="style.css" rel="stylesheet" type="text/css" />
<?php
//go to db to get 800 no. and head text from settings table:
include 'c.php';
$phquery = mysql_query("select * from settings where id='1'") or die(mysql_error());
while($r=mysql_fetch_array($phquery)){
$ph800 = $r['phone800'];
$headText = $r['header_text'];
}//end while.
?>
<title>
Caregivers | QR Code Emergency Medical Cards
</title>

<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>
<body>

<div id="main-wrapper"><a name="top"></a>
    <div id="header-wrapper">

        <div id="header">    
        
            <div>
            
                <span id="siteseal" style="position:absolute;top:3px;left:195px;"><script type="text/javascript" src="https://seal.starfieldtech.com/getSeal?sealID=vrLtyGqVemlr56J0BgCP0KqRHNTY0QUzZXEZkZk3fkHQz181UVL"></script></span>
            
            <div id="one800b"><?php echo $ph800; ?></div>
            <span id="logout" onclick="window.location='logout.php'">
                <?php
                if(isset($eml)){
                    if($eml != ""){echo "Log out";}
                }//end if eml var set.
                ?>
            </span>
            
                <div id="login-wrapper" onclick="window.location='login.php'">
                    <div id="login">member login</div>
                </div>
                
                <div id="top-login-form">
<p><a href="register.php">Sign Up</a></p>
                </div>                
                
                <img id="mainlogo" src="images/lifestat911new.png" onclick="window.location='index.php';" />

                
<?php
include 'top_nav_partner.php';
?>

<div id="headtxt">
<?php echo $headText; ?>
</div>

<?php //include 'user_status.php'; ?>

<div id="headbgimg">
<img src="images/heart2.gif" style="opacity:0.3;width:400px;height:99px;" />
</div>
            </div>    
        </div><!--######################## End header div #####################-->

So I pasted the above code to the top of formtest.php and tested to see if the form data would disappear after pressing the back button again and it sure enough the data was gone, so that tells us a couple other things, it wasn't due to the include statement and it is somewhere in the contents of the include file, but not the include process itself. so I starting taking away from the header code a few lines at a time to find which section of code was causing the issue. First I took out the opening PHP tag and everything down to the form so I took out this:

TEST EIGHT

<?php
//start session vars and get user email for every page header file is included in:
session_start();
//get email from session var set in login.php script:
if(isset($_SESSION['user_email'])){
$eml = $_SESSION['user_email'];
//get member's ID
include 'c.php';
$idq = mysql_query("SELECT * FROM members WHERE email='$eml'")or die(mysql_error());
    while($idr = mysql_fetch_array($idq)) {
    $mid = $idq['id'];
    }//end while
}
?>

Then I tested it and it worked! So pressing the back button didn't cause the form to be blank this time, therefore we now know the problem is in the above code. Time to dissect it further... Next, I replace the above code without the if statement. I removed the following:

TEST NINE

if(isset($_SESSION['user_email'])){
$eml = $_SESSION['user_email'];
//get member's ID
include 'c.php';
$idq = mysql_query("SELECT * FROM members WHERE email='$eml'")or die(mysql_error());
    while($idr = mysql_fetch_array($idq)) {
    $mid = $idq['id'];
    }//end while
}

Then tested again and after pressing the back button, the data was missing again, so the problem wasn't there apparently, which leaves only one thing it seems, the session start PHP functioin. so I took it out and it worked! Low and behold, the session_start PHP function was the culprit the whole time. Just to make certain, I commented out the session_start function in the site I originally had the trouble with and sure enough, it solved the problem. Unfortunately, it presents a whole new problem, how do I now start my session?

So as you can see, I did solve the problem at the top of the article by using:

session_cache_limiter('public');

session_start();

instead of just session start. Had I known this from the start, I would of titled the article:

PHP's session_start Function Causes Forms to Lose Data When Pressing Browser Back Button

Maybe a shorter article will follow with that title;-)

 

 

 

 

Install and Configure Bind DNS server for First Time

DNS is a heavy topic and not for newbies so much. I have been doing server admin for many years and It is still a challenge to work with Bind DNS sometimes. I have posted this guide here partly so I can replicate the process and partly so others can set up their own BIND DNS servers without so many headaches because none of the tutorials online I could find seemed to be complete, but here is the exact process that worked for me. I have installed and configured half a dozen of these by now, so have somewhat perfected the process.

This tutorial is for setting up a DNS server as an authoritative nameserver. That means that you will be able to use it as a DNS server to point domain names to outside web servers. An example would be if you had the domain name mydomain.com and a server with the IP 111.111.111.111. You could then use this nameserver setup to point that domain name to that IP address. I hope that is clear enough. This is not a caching only nameserver or a nameserver for internal use only, it is a fully functional authoritative name server meaning that it is a nameserver that can be used just like Godaddy's or any other large company's nameservers. Unless you have a need for this type of nameserver, I recommend using an existing service, otherwise read on!

Installing BIND DNS

  1. Login to your Server and get a command prompt. I did mine as an Amazon EC2 instance, so I logged into mine remotely using PUTTY.
  2. Become Super User by typing: sudo su at the command prompt.
  3. Install the Bind 9 package with:  yum install bind

Setting Up Nameserver Domain

There is a lot to setting up a nameserver's domain name, so bare with me here as I explain it all here. If you don't need this section having already done this, skip it and move on to the next heading.

  1. Go into your domain name provider's website and point the domain name you are using for your name server to the IP address of the DNS/Bind server using an address or "a" record. Next you have to set up two host records. See your domain name providers rules for this or if you are using Godaddy, scroll down on the domain information page to where it says "hosts" and click on "add" and fill in the two IPs you have for your nameservers. You can either set two IPs to your one DNS server or do what I did and clone off your DNS server giving the second one the second required IP. Yes, you have to have two IP addresses for a DNS system to work.
  2. Go into your Bind server via command prompt again and set up a master zone record for the nameserver itself. If your DNS server's domain name were example.com, the name of the file would need to be example.com.hosts  This would be what your zone file would look like and it goes in the var/named directory:
  3. $ttl 900
    example.com.      IN      SOA     example.com. admin.example.com. (
    1360462393
    1800
    1800
    3600
    900 )
    example.com.      IN      A       23.20.141.125
    www.example.com.  IN      A       23.20.141.125
    ns1.example.com.  IN      A       23.20.141.125
    ns2.example.com.  IN      A       23.20.141.125
    example.com.      IN      NS      ns1.example.com.
    example.com.      IN      NS      ns2.example.com.
  4. Now you have to edit your named.conf file in the /etc/ directory so it looks like the following example for example.com. Remember this is the domain name for your DNS server, the one that you will use as ns1.example.com and ns2.example.com. Here is the file contents for etc/named.conf: //example.com nameserver setup
    //where example.com is the domain name to the nameserver itself
    // named.conf
    // See /usr/share/doc/bind*/sample/ for example named configuration files.
    options {
    listen-on port 53 { 0.0.0.0; };
    listen-on-v6 port 53 { 0::0:0:0:0/0; };
    directory "/var/named";
    dump-file "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    allow-query {
    any;
    };
    recursion yes;dnssec-enable yes;
    dnssec-validation yes;
    dnssec-lookaside auto;

    /* Path to ISC DLV key */
    bindkeys-file "/etc/named.iscdlv.key";

    managed-keys-directory "/var/named/dynamic";
    };

    logging {
    channel default_debug {
    file "data/named.run";
    severity dynamic;
    };
    };

    zone "." IN {
    type hint;
    file "named.ca";
    };

    include "/etc/named.rfc1912.zones";
    include "/etc/named.root.key";
    //this is the zone for the DNS server itself
    zone "example.com" {
    type master;
    file "/var/named/example.com.hosts";
    };
    //all other outside domains pointed to this DNS server below here:

  5. Okay now you should have a file named something like example.com.hosts from step 2 & 3 in your var/named directory and a file named named.conf in your /etc directory. Just to be clear. The next thing you need to do is: from the DNS server command prompt, type: ifconfig and press enter. This is to get the listen-on IP and V6 listen on IP. From the information you got with the ifconfig command look for the IP address after where it says "inet addr:" that's what you replace "0.0.0.0" with in the named.conf file above where it says listen-on-port. Now look in the ifconfig readout for where it says inet6 addr:" and use that longer number for the listen-on v6 port replacing where I currently have 0::0:0:0:0/0. save the file to your etc directory.

Point an external Domain Name with Bind DNS

Now it is time to see your new DNS server in action. the following instructions are for taking a domain name you own and pointing it using your DNS server. Here is what you will need:

  • The two nameserver domains such as ns1.example.com and ns2.example.com, the same ones you used in the above steps to set up your nameservers zone files and the ones you used with your nameserver domain name configuration at your domain name provider to point example.com to the DNS server itself.
  • A server with an IP address to point the outside domain name to. I set up a free micro instance in Amazon EC2 to use as a test server for this, but you can use whatever server you want.
  • You will need your domain name settings from the domain name provider set up. To do this, go into the nameserver settings and use the ns1.example.com and ns2.example subdomains you set up for your DNS server and the two IPs that point to the DNS server or to two separate DNS servers if that is how you set it up. You should have two, but one will work I think if you have two IPs for it.

Okay after you have the above all done, follow the following instructions to set up the BIND DNS configuration for the new domain name which you want to point to a server to have your own DNS server point that domain so others can see it on the internet.

  1. First, you need to edit the same /ect/named.conf file once more to add a zone for the new external domain name. At the end of the named.conf file, add the following:
  2. zone "buildmycareer.com" {
    type master;
    file "/var/named/buildmycareer.com.hosts";
    };
  3. Then save the etc/named.conf file and go to the var/named dir and start a zone file for that domain and save it in var/named as mydomain.com.hosts. It needs to have the following bare min. content. the content here is just to point the domain and excludes mx records, cname records etc. this is a barebones set up for simplicity's sake and only has the address record needed to actually point the domain name to resolve it to your web site on the server for which you should already have an IP address for:
  4. $ttl 900
    mydomain.com.  IN      SOA     ns1.example.com. admin.example.com. (
    1360465998
    1800
    1800
    3600
    3600 )
    mydomain.com.  IN      NS      ns1.example.com.
    mydomain.com.  IN      NS      ns2.example.com.
    mydomain.com.  IN      A       0.0.0.0
    www.mydomain.com.      IN      A       0.0.0.0
  5. Change mydomain to your domain name, change example.com to your DNS domain name, change 0.0.0.0 to your IP and save the above contents in a file at var/named.mydomain.com.hosts replacing mydomain with the actual domain name you are pointing.
  6. Now set up a virtual host on the same DNS server so it has information on the domain name. All it needs is the IP adress and root folder on the web server for which you are supplying the IP for. The next step has the contents that you have to add to the etc/httpd/conf/httpd.conf file:
  7. <VirtualHost 54.242.44.14>
    DocumentRoot "/var/www/html"
    <Directory "/var/www/html">
    allow from all
    Options +Indexes
    </Directory>
    </VirtualHost>
  8. Save the httpd.conf file and fire up your server now that everything should be in place. You can start your server with: sudo service named start or restart with sudo service named restart if it is already running.

That is about it. I hope it works for you. I remember it took me days to set up my first authoritative DNS server, but if you follow this process well enough it should make it easier for you. If you don't see any errors when starting your DNS server, then you should be good.

Testing

To test your server, wait for at least thirty min and then try to resolve your domain name that you pointed with the new DNS server. It it resolves to the correct web server and you see the site you posted there, then you are doing great. If not, track down any typos in the config files and try, try again. Here are some links to help you test DNS issues:

http://pingability.com/

 http://www.dnssy.com/

 

 

How to Add Spell Checker to Notepad++

I have been using Notepad++ as my coding text editor of choice for several years now. One of the main things I use it for is to create web pages in PHP and/or HTML. Over those years, I can't count the number of times I have been chastised for my somewhat poor spelling and numerous typos the end up in the final product or website that I turn over to my clients. Well, it's time I did something about it, don't you think? Well, my clients think it is and several have mentioned it, so here I am years after starting to use Notepad++, finally installing a spell checking plugin. Here we go!

Also, I recently added a bug fix to this tutorial that describes how to fix it so that you can use the learn button and otherwise save changes to the dictionary files. When I installed Aspell, none of this worked and it was aggravating, so I learned how to fix it and will share at the bottom of this article, so if you are here to learn how to fix the bugs in Aspell, skip down to the bottom of this post. If you get an error something like the following one, then the bottom section is for you:

Ensure that the security settings of the "C:/Program Files (x86)/Aspell" folder for the current user allow for modifying and writing

Aspell

Usage example with replace by text same as misspelled text

Steps to installing Spell Check for Notepad++

Before you start, you should close any open applications, or at least close Notepad++ so it can get the updates needed if any while you install the plugin.

  1. Go to http://aspell.net/win32/ and download the "Full Installer" to your desktop or downloads folder and double click on it when it's downloaded fully to set it up on your machine. I selected the defaults mostly, but did check the boxes to allow a desktop icon and a right click menu option so I could take advantage of the drag and drop document feature and quick spell check options.
  2. During the installation process, after clicking through the terms of service and a couple other routine clicks, you will come to the "information" dialog. It will say: "Please download and install at least one dictionary from http://aspell.net/win32/dicts" So, naturally, I clicked on the link and came to find that it was a dead link and that the spell check plugin hasn't been kept up for the past ten plus years. So, determined, I went to back to the same webpage above, , where I downloaded Aspell from, and found the dictionary list I was seeking. Lucky me! Then I scrolled down and found the one for English entitled "aspell-en-0.50-2-3.exe" (Click to download) and clicked on it to download the English dictionary I needed. You can click on the link I just provided to download it without having to go back to the webpage however. If you need other languages, then go to the webpage you downloaded Aspell from to get them.
  3. After your Aspell installation is finished, double click on the dictionary file you downloaded in the last step to install it as well. Install it with all defaults as long as you did the same with the install directories for Aspell as well. Click, click, click and it's installed!

Notes: When you are done with the three simple installation steps, open Notepad++, click on plugins in the top menu and select "spell checker" from the drop-down menu. I was impressed with the easy installation even though it was missing a link and there wasn't much documentation. It took less than five minutes to do, so this is an easy thing to do that will save you tons of headaches in the future.

I do have one complaint with the functionality and did find one apparent bug right off the bat. The issue that stuck out to me the most was that it didn't automatically suggest the most likely correct spelling of the misspelled words. It did provide a list of most likely alternatives, but there is a field that is supposed to have the most likely correct spelling and that field is always populated with the misspelled word instead of the correct spelling. Then I noticed there was a button that read "learn", so I figured it had to be taught this and there is where I found the apparent bug. When I pressed the Learn button, it gave me an error and didn't do anything constructive. This is new to me, so perhaps I will report back later on this blog when I find a solution to the bug and/or functionality issue. Even with this minor bug and issue, it still performs well and gets the job done, so overall, I am happy to have a spell checker for Notepad++ now!

As promised, I am back to solve the issues with Aspell mentioned in this tutorial. Here is how to fix the error:

Ensure that the security settings of the "C:/Program Files (x86)/Aspell" folder for the current user allow for modifying and writing

Locate your Aspell directory by the error itself. Mine was in "C:/Program Files (x86)/Aspell" as the error indicates. From the Aspell directory do the following fixes:

  1. Right Click on the Aspell directory and select "Properties". Then select the "Security" tab and click on the "Edit" button to alter permissions.
  2. Click on the username that you use Notepad++ with then click the Allow column for "Full Control" for that user in the permissions box. Hit apply then okay twice.
  3. Now enter the Aspell/dictionary directory and give any files with .pws or extension in the dictionary folder write permissions for your username. Using the same technique as in the first couple steps above.
  4. Next open up Notepad++ or notepad and create a new text file then copy and paste the following into it and save it as en.pws: personal_ws-1.1 en 2
    µÄ
  5. Click the encoding option in the top toolbar of notepad and make sure that ANSI is the coding type and save the document to c:/Program Files(x86)/Aspell or wherever your Aspell was installed.
  6. Now go back to notepad or Notepad++ and create yet another text file and paste the following green text into the first line and save it as an ANSI encoded file into the same Aspell directory, but name this file en.prepl: personal_repl-1.1 en 0 
  7. close and restart Notepad++ and try out the program with the Aspell plugin again and you will find it should be all working now!

 

 

Setting up Domain Names on Autoratative Nameserver with Bind and Webmin

This is an advanced level DNS server administration tutorial. If you don't know what DNS means, get out while you can, this is complex stuff and you got to have some background information first. Start reading up on nameservers first, you will need some education behind you before attempting this tutorial, trust me. It took me weeks to learn to set one up with no background education in computer science, but I did it and here is how. First you may also want to read my previous article on how to set up the domain name for the webserver itself. This tutorial is for setting up domain names on an already configured nameserver that already has a domain name and at least two sub-domains such as ns1.domain.com and ns2.domain.com.

 

Inserting new domains in Bind and Webmin

 

How Setup domain name Zone Records:

This is a tutorial on how to set up domain name Zone records on our name servers using Webmin and Bind. This is necessary in the process of pointing a domain to our nameserver and being able to control them from our domain name rotation system.

  1. Login to Webmin - and click on "Servers" then on "Bind DNS Server"
  2. Create a Master Zone - by scrolling down to "Existing DNS Zones" and clicking on "Create master zone". Then fill out the form as follows:
    • In the first field, type in the domain name you are setting up. For example, "buildmycareer.com" without quotes.
    • Then skip down to the "" field and enter "ns1.imonetizepark.com" without quotes.
    • If you have Global Server Options/Default Zones set up, enter the relative IP address in the "IP address for template records" field and check yes in front of it, otherwise skip this and check no in front of it.
    • For "Refresh time" enter 30 min. for testing or longer for permanent records.
    • For "Transfer retry time" enter 30 min. for testing or longer for permanent records.
    • For "Expiry time" enter 60 min. for testing or longer for permanent records.
    • For "Negative cache time" enter 60 min. for testing or longer for permanent records.
  3. Click the "Create" button to save the master zone.
  4. Click on the "Address" icon and enter the following information in the resulting pop up window:
    • Leave the "Name" field blank and enter the IP address to the server that holds the website for the domain name you are configuring in the "Address" field.
    • Press the Create button and a new address record form will appear. This time, type "www" without quotes in the "Name" field and enter the same IP in the "Address" field and click Create again.
  5. Click on "Return to record types" at the bottom of the form and click on the "Nameserver" icon from the main menu. Enter the domain name in the first field and enter the nameserver in the second. If you look below the form, the first nameserver, ns1, should already be entered, so just enter the second one here, buildmycareer.com. It is important to enter a trailing period after both the domain name and the nameserver domain name in this form. When you have both nameserver records entered, click create and "return to record type".
  6. Finally, click on "Apply zone" in the top right corner of the page and you should be done. If it doesn't take, restart the Bind server, but you shouldn't have to.
  7. Duplicate process on nameserver two - When you are done with all of the above steps for nameserver one, do the exact same thing on nameserver two.
  8. Create Virtual Host - After the all the zone records are done, follow the instructions below to create a virtual host for the same domain name you just set up on both nameservers. you will be creating the virtual host on both as well.
  9. TEST - When you are done, the settings can take up to 72 hours to work, but normally work within a half hour, so as soon as you are done, you can test by typing your domain name into a browser window to see if it resolves. If it doesn't wait an hour and try again. If it still doesn't work after 72 hours you likely have a problem, so go over everything and make sure it's set correctly. You can use online tools such as those found at
  10. TIPS Trouble shooting - If you still need help or more information since this is a very basic, bare bones set up I have described, go to docfre.webmin.com for more complete instructions or go to wallpaperama.com for similar simple instructions or finally also at linuxjunkies. There are also tools available to check DNS settings available at pingability.com and dnsstuff.com. GOOD LUCK! (you may need it)

How Setup domain name Virtual Hosts:

This is a tutorial on how to set up domains on our web server using Webmin. This is also necessary in the process of pointing a domain to our nameserver and being able to control them from our domain name rotation system.

  1. Login to Webmin - Click on Servers/Apache Webserver
  2. Create Virtual Host - by clicking on the "Create Virtual Host" tab.
  3. Enter IP Address - in the first field and select the "Specific address .. " option just above it.
  4. Enter the document Root - in the "Document Root" field.
  5. Save - by clicking the "Create Now" button under the form.
  6. Copy settings - on webserver two just like you did here for webserver one.
  7. Apply Changes - by clicking on the "Apply changes" link in the upper right hand corner of the webpage in Webmin.
  8. Test - by entering the domain name into a web browser and seeing if it resolves to the correct webserver. If it doesn't wait an hour or so and try again. If it doesn't work after 72 hours, something is definitely wrong. Use the tools mentioned above in the section on setting up the nameserver section.

Prevent Doubles in MySQL Query

If you work with MySQL enough, I am sure you have run into a table with double records or at least partial double records. Say you have a table with several rows for each name with the rows containing different data but the same name and you just want a list of unique names. This is what you can do to just get a list of names without repeating the names in your list. There are a couple approaches. You can use the DISTINCT keyword or the GROUP BY syntax. Either will work but with often different results. Here is an example of each:

SELECT DISTINCT name FROM table;

SELECT name FROM table GROUP BY name;

 

Importing Large Database with MySQL

Many of you probably know that you can not upload larger databases or tables using the standard PHPMyAdmin interface. PHPMyAdmin will normally crash when you try to import a table or database that exceeds 4,000kb. That is why I am posting these instructions on how to import larger databases or tables into MySQL.

Instructions:

The below is assuming you already know how to loginto a shell prompt with putty or from the server directly. If you don't check with your hosting provider or Google it.

How to import a large database from the MySQL command prompt:

First get the MySQL command prompt with:

mysql

Then from the mysql prompt type

use database_name

In the above command, replace database_name with the name of the database you are trying to import into. If you have not created the database yet, you can do that easily from PHPMyAdmin. Next type:

source /var/www/html/file.sql

In the above command replace /var/www/html/file.sql with the path and filename of the .sql file you are importing.

Tips:

If you get a permission error, go to phpmyadmin and grant privedeges for the database for the user you are logged into the command prompt window as.

If the above method gives you trouble, although it is the one that worked for me, it may not for your situation, depending on certain variables, you can try BigDump which is free to downloat at:

http://www.ozerov.de/bigdump/

 

...or try the alternate solution below:

If you don't already have the .sql file ti import, you have to take a dump of the database first,

mysqldump /var/lib/mysql/databasename > /home/username/database.sql

This will create a mysqldup file called database.sql.

Copy this .sql file and in order to restore use the following from the command prompt:

mysql /var/lib/mysql/databasename < /home/username/database.sql

If you don't have shell access you can use the cpanel backup utility to make a copy of that in your home directory and upload into the new location using FTP.

Installing Webmin on Amazon Linux AMI in EC2

Here is how I installed Webmin on my Linux AMI from Amazon EC2:

first switch to root user so you don't have to type sudo in front of every command:

sudo su

install the package:

wget http://www.webmin.com/download/rpm/webmin-current.rpm

Unpack Webmin. Use the following command, but update the version number if it has changed:

sudo rpm -U webmin-1.620-1.noarch.rpm

your putty session should look like this after it is done. It will take a few min to finish and when you see the screen that looks like the below image, it is done:

Snap 2013-02-09 at 12.50.03

Make change to firewall

check that firewall is running with:

service iptables status

Stop the firewall with:

service iptables stop

Add port 1000 for Webmin with this command:

iptables -A INPUT -p tcp --dport 10000 -j ACCEPT

then save the rule:

/sbin/service iptables save

restart:

service iptables restart

flush the firewal rules:

iptables -F

restart and check status:

service iptables restart

service iptables status

you should see your port added as in the image below:

Snap 2013-02-09 at 12.58.37

Notice the tcp dpt:1000 on the right of the screen If you don't see it, redo the firewall steps again until you do!

Reboot by typing this at command line:

wait a couple minutes and log back in with butty as you will be kicked out during reboot process.

If you didn't have an elastic IP which you should, you will have to update the IP address of the instance.

Now you have to set a root password since ec2-user won't work with web admin and amazon Linux AMIs don't come with a root password, so use the following command:

/usr/libexec/webmin/changepass.pl /etc/webmin root PASSWORD

replace PASSWORD with your own root password of course.

restart Webmin again with

service webmin restart

Now you should be all set so login with your favorite web browser using the following URL but replace the IP with the elastic IP you set for your instance:

https://53.215.141.71:10000/

INSTALLING BIND with WEBMIN

Bind didn't show up under servers in the left navigation panel for Webmin, so this is what you do:

in the search box in left nav, type bind and click to search. IN the search results, I clicked on the first one that said "BIND DNS server" and it prompted me to install it if wanted, I clicked to install.

after successful install, refresh page and Webmin should have bind dns listed under servers now in the left navigation menu.

click on Bind DNS server and you will see the admin for bind.

 

 

 

 

 

 

 

 

 

Amazon Web Server 5 Minute Install

This tutorial will show you how to set up an Amazon cloud server n just over five minutes! It assumes you already have an Amazon account created. If you have to create an account, see my more detailed article on creating an Amazon cloud web server HERE

Here are the high end steps to create a web server from Amazon's EC2 tab:

  1. From the EC2 tab, click "Launch Instance" near the top of the page and then click on "continue" with the default "classic wizard" selected.
  2. In the next dialog you will see, click the very first "select" button to select the basic Amazon Linux AMI.
  3. In the next dialog, you'll be asked to select a zone. If you already have a security group created for another instance that you want to use, select the same availability zone, otherwise just click "Continue" with the default selected.
  4. The next dialog is for advanced options, just click continue to accept the defaults. Then in the next window, click continue again to accept the default root volume which will work fine.
  5. The next dialog window is for Key Value Pairs, Enter a friendly name for your server in the first value input and click "continue".
  6. The next step allows you to choose an existing key pair or create a new one. Do so and click "continue". Then choose a security group from a previous instance or choose the one with "default" in the name if you haven't created one in the past. If you have custom needs, create a custom security group. Click "Continue". Then click "Launch" and "Close" in the next two windows and your instnace has been created. It may take a minute or two to set up in the background.
  7. Loginto your instnace using the puglic IP address which you can get by checking the instance in your amazon console and making a note of the IP address. it will look something like: http://ec2-54-242-44-14.compute-1.amazonaws.com/, but you can shorten it by taking the number after the ec2 part so that the above would shorten to 54.242.44.14 which is the IP address only. Notice I replaced the dashes with periods.
  8. Open Putty and enter your server's IP address form the last step into the host field. Click on "SSH" from options on left of Putty window then click on the "Auth" subcategory and use the browse button to allow Putty access to your key file which you should have downloaded to your desktop when creating it for the first time. If you have not done this yet, look in Amazon's help section for instructions on downloading your key file. After selecting the key file, click on open to open it, then open again to open a terminal window and finally click yes to add a security exception and you will be connected to your instance. Enter "ec2-user" into the terminal window when it asks for a user name and hit enter.
  9. Now it's time to install some stuff. FIrst update your server's software by typing "sudo yum update" then when that is done, type the following series of command line commands to install PHP, MySQL and PHPmyAdmin:

sudo yum install php-mysql php php-xml php-mcrypt php-mbstring php-cli mysql httpd

sudo yum install mysql-server

sudo /etc/init.d/mysqld start

mysqladmin -u root password UrPassWord

mysql -u root –p

If you get a MySQL prompt, you are good so far. Type q to exit MySQL and continue from the command prompt as follows:

sudo vim /var/www/html/index.php

Now enter some test text for your first test webpage.

Save the page and start your new server with

sudo service httpd start

Type the IP address in a web browser and if you see your test text from above, you are done! otherwise, go back and find your error. Good Luck! If you need a more detailed set of instructions, see my first post on setting up a cloud server at http://jafty.com/blog/?p=142

.

 

 

How to Install a Web Server on Amazon EC2

This is a step by step tutorial on how to install a web server on an Amazon Linux AMI in EC2. I, Ian L. of Jafty.com, have personally used this method to set up well over a dozen web servers for myself and my clients. I have perfected this method and edited the directions according to what I have found works the best. Take note where I noted that you do not need to make database tables if you don't want to and you plan to install PHPmyAdmin as instructed towards the end of the tutorial. Have fun!

Starting a Free Amazon Web Server:

Sign up for an Amazon Web Services account:

The first step to migrating your website to the cloud is to sign up for AWS using the link below.

Go to http://aws.amazon.com/ and sign up.

Next, you need to set up your account before you can launch a server into the cloud. Start by going to https://console.aws.amazon.com/console/home and following these few steps to set up your account for the cloud:

  1. Click the “EC2” tab.
  2. On the left column of the page, under the “Network & Security” heading, click on “Security Groups”.
  3. In the right column click on the “Create Security Group” button. Enter a name and description in the pop up window then hit the “yes create” button.
  4. Just under the “Create Security Group” button is a list of existing groups. Your new group should be here. Make sure it is the only one checked.
  5. Further down in the right column click on the “inbound”  tab and set up your server’s ports. Here is another tutorial I wrote on how to set this up that you should take a look at because it is a little complex and very important to get correct the first time: http://jafty.com/blog/amazon-cloud-server-security-rules/(link opens in new window or tab). This has changed a little and now you don't have to do this here if you don't want to...or if you do it wrong, you can have another chance when you are setting up your instance. If you do it when you set up your instance, refer to the same link just mentioned as well and you'll be okay.

 

  1. Make sure you click on the button that reads “Apply Rule Changes” once you have the ports set up like we do in the above image.
  2. Now go back to the left navigation column of the page and click on the "key pairs" link.
  3. Click “Create Key” in the right column.
  4. Give the key pair a name that relates to your server like “iansserver” and save it to your local machine. Save it to the desktop or somewhere you can find it easily because you will need it soon.

Creating a server instance in the cloud

Now comes the fun part! We are going to create a virtual private server or VPS in the cloud on amazons network of servers for little or no cost at all! Currently as of March 2012, Amazon allows new users to receive a year of free services. Be careful though, there are limitations, so monitor your account to make sure you only use services on the free tier and that you don’t exceed any set limitations. Read online support for more information on charges that could apply. Follow the following steps to set up a free micro instance of a Linux web server complete with web server, PHP, database server and PHPMyAdmin. Those are the minimal things you should definitely have to create dynamic web sites.

  1. Picking up on the same page we left off on above, click on “instances” in the left navigation column of the amazon webpage.
  2. Click “Launch Instance” to make the instance wizard appear. Make sure “Classic Wizard” is selected in the pop up and click on “Continue”.
  3. On the “Choose an AMI” pop up, select the AMI that reads “Basic 64-bit Amazon Linux AMI ” it will have a notice by it indicating it is in the free usage tier. Check the box to select this AMI and click "Next...".
  4. In the “instance details” and the step after it, just accept the defaults by clicking on “Next...” two times.
  5. You should now be at the point where there is a key and value column. Leave “name” in the key column and enter a name that describes your server in the value column like “64bit_linux”. Click Continue.
  6. Now you should be on the “create key pair” pop up. Select the key pair name you saved earlier in step 9 above and click continue.
  7. Now in the “configure firewall” pop up, select the preexisting security group you named earlier and click continue.
  8. Review your settings and click “Launch”. Click on “View your instances on the Instances page” and watch your new cloud server appear under “My Instances”.
  9. Check the instance name and make sure no others are checked.
  10. Look down below and find where it gives details for the checked instance. Start a notes page in notebook to record important info and copy and paste the public DNS address for safe keeping you will need it soon.
  11. Open PuttyGen and click on file/load private key and load in the file you saved to your desktop earlier that has a .pem extension. When it’s loaded, click save private key to save the .pem file as a .ppk file
  12. Open Putty and enter the public DNS where it says “Host name”.
  13. Under “Category” in the left column of the Putty window, click to expand “SSH” then click on “Auth” then click browse and select the .ppk file you saved earlier. Click open.
  14. Now a terminal window should appear asking for a username. First a pop up may appear saying the server’s host key…. Just click yes then Enter “ec2-user” for username in the terminal window and hit enter. If it says “…AMAZON LINUX AMI…” you did good! If not backtrack and find out where you messed up.

Okay congrats, you have successfully launched your bare bones server! There is currently no software on it though, so the next several steps are going to involve installing PHP, a database and required libraries to support them and the web server.

Installing server software on your Amazon EC2 AMI instance

  1. First install PHP and the web server software. Type the following at your command prompt then hit “y” whenever prompted:

sudo yum install php-mysql php php-xml php-mcrypt php-mbstring php-cli mysql httpd

  1. Next install MySQL software. Type the following command and hit “y” when prompted:
sudo yum install mysql-server

 

  1. Start the mysql server by typing:
     sudo /etc/init.d/mysqld start
4.  Set the root password and record it in your notebook page you started earlier for safe keeping. Type:
mysqladmin -u root password UrPassWord
where UrPassWOrd is a unique secure character combo.

NOTE: THE NEXT FEW STEPS ARE OPTIONAL DEPENDING WHAT YOU ARE ATTEMPTING TO DO. YOU DON'T HAVE TO CREATE THE DATABASE TABLES HERE THOUGH, YOU CAN WAIT AND DO SO LATER, AS NEEDED FROM PHPMYADMIN. I included the next three steps to demonstrate how to work with mysql from the command line though as it is a good learning exercise, so you should do it anyway just for the sake of learning.
5.Log into mysql by typing:
mysql -u root –p
then enter the password from step 4.
6.  Type the following commands, hitting enter after each semicolon:
CREATE DATABASE [DataBase NAME];
CREATE USER '[DataBase NAME]_admin'@'localhost' IDENTIFIED BY '[ADMIN PASSWORD]';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER ON [DataBase NAME].* TO '[DataBase NAME]_admin'@'localhost';
CREATE USER '[DataBase NAME]_user'@'localhost' IDENTIFIED BY '[USER PASSWORD]';
GRANT SELECT, INSERT, UPDATE, DELETE ON [DataBase NAME].* TO '[DataBase NAME]_user'@'localhost';
7.  Be sure to make a note of both users you created in your notes with the usernames and passwords you used above. Type “exit” then type “sudo chown ec2-user /var/www/html” hit enter to change the owner of the html dir to the ec2-user user.
8.  Type “sudo vim /var/www/html/index.php” and hit enter to start a test .php file as the home page of your new live site on your new cloud VPS.
9.  Hit “I” to put the text editor in insert mode and type some basic HTML to test php and the server. Something like this will do:
<h1>Hello World!</h1>
10.   Hit “ESC” and type “:wq” to save and quit the vim editor. Then start your server with: "sudo service httpd start".
11.   Goto your notepad and get the public DNS address you recorded in your notes earlier. Copy and paste that address to your browswer’s address bar. If it works you should see the bold text: hello world! If it didn’t work and you receive an error with 13 in it, type “sudo chown ec2-user /var/www/html/index.php” and that should fix it.

Okay you now have a working web server! You just need to do some final steps to get the database PHPMYADMIN up and working.

 

Installing PHPMyAdmin

Now let’s install PHPMyAdmin to complete our web server:
Here is how:
1.  Navigate to the html folder:
cd /var/www/html
2.  Type: wget http://www.sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/3.4.1/phpMyAdmin-3.4.1-all-languages.tar.bz2
3.  Unzip by typing: tar -jxf phpMyAdmin-3.4.1-all-languages.tar.bz2 -C /var/www/html
4.  Rename the directory by typing: mv phpMyAdmin-3.4.1-all-languages phpmyadmin
5.  Make a config directory in the phpmyadmin main folder:
cd /var/www/html/phpmyadmin
mkdir config
cp /var/www/html/phpmyadmin/config.sample.inc.php /var/www/html/phpmyadmin/config/config.inc.php
6.  Open config.inc.php in VIM text editor by typing:
sudo vim /var/www/html/phpmyadmin/config/config.inc.php
7.  Find the line that reads “$cfg['blowfish_secret'] = '';” and change it so it reads:
$cfg['blowfish_secret'] = 'yoursecretcode';
You can enter anything you want for your secret code above as long as it’s not over approximately 60 characters.
8.  Find the line that reads “$cfg['Servers'][$i]['AllowNoPassword'] = false;” and change false to true only if you don’t have a root password set or if you are not sure. You can always come back and change this to false again later when you tighten up your server’s security as you will want to do before too long.
9.  Hit “Esc” to get out of insert mode in your text editor. Then type:
:wq 
Type it just like that, including the semicolon, to save and exit the file.
10.   Go to http://your_public_DNS/phpmyadmin/ and enter you mysql admin username and password. You should have recorded these in your notes when setting up the database above in step 7 of the previous section(not this one).

You should now be logged into your new phpMyAdmin section of your VPS server. If so, you have successfully created a cloud VPS server with all of the most essential components to develop a live dynamic PHP website! Once you are done or if you do not intend to use this instance, terminate it so you don’t get billed for it later on after your free year expires. If you intend to use it, do not terminate it or you will lose all of your work!

To learn more about how to connect to an instance go to http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/ConnectToInstanceLinux.html and learnn to connect to your instance.

To become root user in putty type:

sudo su

Starting server from putty

Open putty

Enter the public DNS of the server instance which can be found in your AWS dashboard and looks like ec2-50-16-87-242.compute-1.amazonaws.com into the host name field in putty. UPDATE: now Amazon IPs are simply like 45.23.34.22.

In the left column under “category” expand “ssh” and click on Auth

Click browse and select your security key file you created while creating your server instance, it will be a file like: adamskey.ppk you should of saved it on your desktop for convenience.

Click open and your terminal window should come up.

At the login prompt, enter ec2-user and hit enter.

You should see several lines of text with “Amazon Linux AMI” in the middle then a command prompt at the end.

You are now in your server. If you need root access, type sudo su

Reference:

The best tutorial I found on how to get a linux micro instance up and running with a web server  was at:

http://www.alexkorn.com/blog/2011/03/getting-php-mysql-running-amazon-ec2/

Tip: find public data at:

http://aws.amazon.com/publicdatasets/

 

To find out how to use Filzilla with your instance:

http://www.latentexistence.me.uk/how-to-set-up-a-free-linux-server-on-amazon-ec2/

 

 

 

 

 

 

 

Here is how I didn command line server installation second time because above didn’t work:

 

Yum install httpd

Yum install php

Yum install mysql-server mysql

Service httpd start

Service mysqld start

Linux Cron Job Tutorial

Here I will demonstrate how to add cron job to various Linux web servers to automate your daily, hourly or weekly tasks.

How to Set Up a Cron Job on Hostgator  and other shared Servers with Cpanel

Here is a screenshot of the cpanel page you use to add cron jobs in cpanel when using a Hostgator or similar server:

crons

So, yes, all you do is fill in the form and click the Add button, but you have to understand the settings, so you may need to read on. If you're lucky, below the above box in cpanel, there are current existing cron jobs listed. You should be able to figure out how to fill in the form properly by following the examples if there are any. If not, you should be able to do it after readying this tutorial, so no worries.

Entering the cron command:

The cron command will consist of two parts:

  1. The location of the PHP installation on your server
  2. The path and filename of the script the cron job is to run

Simply combine those two objects with one or more spaces in between them to make up the cron command for the command field in the form you see in the image above. For example, here is what I used for the command field in the cron form:

/usr/bin/php /home1/gold2013/public_html/amazing-agents.com/crontest.php

Then in the first drop-down in the form, the one called "Common Settings", select to run every 15 min. for testing or if you are confident and don't want to test, set it for exactly how you want your cron job to be ran.

Test Cron Script

The following script is a great way to test cron jobs. All it does is creates a file called cronresults.txt or appends to it if it's already been created. It writes a simple message with the time of the cron job to that file and that's it. Nice and simple, the way I like it!

Copy and paste the following code into notepad and save it as crontest.php

<?php
$ctime = date('l jS \of F Y h:i:s A');
$myFile = "cronresults.txt";
$fh2 = fopen($myFile, 'a') or die("can't open file to append");
$stringData = "appended text from cron job ran at $ctime....\n";
fwrite($fh2, $stringData);
fclose($fh2);
?>

Upload crontest.php to an active web directory using your favorite FTP client.  Make sure the path in your cron job matches the directory you upload to and you will be good.

Now wait 15 minutes or however long you set your cron job to run and check to see if the file named cronresults.txt was created in the same directory that you put crontest.php. Download cronresults.txt and you should see a list of the times that your test cron job has ran. If it didn't work, try changing the permissions of crontest.php to 777 while testing and tighten up security asap.

Cron eMail Notices

One nice thing about cron is that it sends you an email every time it runs. Make sure the email in Cpanel, just above the cron form, is set to the correct email where you can receive emails. If there is an error in the cron job, that email message is the easiest place to read the error information. Yes, errors are emailed to you! You can suppress the emails once your cron job is set up and error-free however.

How to set up a cron job from Amazon ec2 cloud server

We used the basic Linux 64bit AMI but these directions should work for any Linux web server. Here are the simple steps to creating a cron job on a Linux server:

First, open a command prompt using Putty or a command window from your desktop if you have access that way.

From the command prompt, type:

which php
returns:/usr/bin/php

using the response from which php command above, add the proper shebang to your PHP script like so:

#!/usr/bin/php -q

the  -q parameter makes it so you don't get an email every time cron job runs.

Continuing from the command prompt, type:

crontab -e

Then use VI editor to add the following line to crontab which will run  your PHP script every minute:

* * * * * /usr/bin/php /home/ec2-user/crontest.php

or every hour:

0 * * * * ...

The five cron positions are as follows:

minute         0-59
hour           0-23
day of month   0-31
month          1-12
day of week    0-7 (sun = 0 or 7)

Start a PHP file named crontest.php and enter the following contents:

----------------------code----------------------------
#!/usr/bin/php -q
<?php
//script to test cron on adam's cloud server:
$message = "If ur reading this then the cron job worked!!!!nn";

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

fwrite($fh, $message);
$stringData = "Coming to you from cloud cron! the script that sent this was in home/ec2-user/crontest.phpn";
fwrite($fh, $stringData);
fclose($fh);
?>
--------------------------------------------------------

Start another PHP file named testFile.php. It will just be a blank .txt file with no content at all.

Then upload crontest.php and testFile.php to /home/ec2-user and change permissions of both to 755 or 777 if 755 doesn't work but 777 can cause a security issue.

Important note: it seems that if you change the regular crontab using crontab -e call that the files have to be in the user's directory that you are in when making the call which in this case is user ec2-user.

To switch user use:

su ec2-user

Then do your crontab -e command again and it will work.

Cron Job Examples:

To run a cron job once a day, the syntax would be:

minute hour * * * command

so just replace minute with a number from 0 to 59 and the hour with a number from 1 to 24 as in the following working example:

30 9 * * * /usr/bin/php /home/ec2-user/crontest.php

The above example would run the crontest.php script once a day at 9:30am.

Running a cron job every 15 minutes

 0,15,30,45 * * * * /path/to/command

or

*/15 * * * * /path/to/command