Wednesday, August 29, 2012

Client side data storage

Lots of ways to do it, but I am favoring HTML 5's sessionStorage. Its clean and does not stick around on peoples machines. I hate it when stuff sticks to my machine so I try not to let it stick on others. sessionStorage will expire when the browser closes. Here are a few ways to set it in javascript.

sessionStorage.someKey = 'someValue';

 or if you prefer...

 sessionStorage.setItem('someKey', 'someValue');

 And to retrieve it.

sessionStorage.getItem('someKey')
 or
sessionStorage.someKey

You can display the info with the Document Object Model like so...

document.getElementById("myvalue").innerHTML = sessionStorage.someKey;

You should get this in your HTML

<div id="myvalue">someValue</div>

Monday, August 27, 2012

Linux

I have decided that I am favoring CentOS over Ubuntu. I used Ubuntu for a long while as a desktop, and it was great for that. I use CentOS at work on our servers. When I installed the server addition of Ubuntu I found that in order to be able to SSH to the server to update files I had to jump threw a lot of hoops, like moving the web directory to a home folder and then pointing Apache to the folder to let it write to it. Yes its more secure that way. But what I really want right now is ease of use. Perhaps I will use Ubuntu if I decide to store Credit Cards, when I finally get my game up and running, but beyond that I think its a bit overkill and cumbersome for my personal sites.

Wednesday, August 22, 2012

PHP Email crazyness

Today I built a simple email class to send out emails.


/**
 * Description of Email Class
 *
 * @author Joseph Tveter
 */
class Email
{
    public function __construct()
    {}
   
    public function Email($to, $subject, $message, $from = 'admin@yoursite.com', $cc = '', $bcc = '', $MIME = 'MIME-Version: 1.0', $Content = 'Content-type: text/html; charset=iso-8859-1', $Reply = "")
    {
            $headers  = $MIME . "\r\n";
            $headers .= $Content . "\r\n";
            $headers .= 'From: '. $from . "\r\n";
            if($cc != "")
            {
                $headers .= 'Cc: '. $cc . "\r\n";
            }
            if($bcc != "")
            {
                $headers .= 'Bcc: '. $bcc . "\r\n";
            }
            if($Reply != "")
            {
                $headers .= 'Reply-To: '. $Reply . "\r\n";
            }
           
        if (mail($to, $subject, $message, $headers) == false)
        {
            //send email on fail
            $s = "Email Failed to ".$to;
            $m = $s.":"."\r\n".$message;
            $h  = $MIME . "\r\n";
            $h .= $Content . "\r\n";
            $h .= 'From:'. '$from' . "\r\n";
            mail('you@yoursite.com', $s, $m, $h);
        }
    }
}

Tuesday, August 21, 2012

Multiple CSS Classes in HTML Tag

This was a major help for me.  If your a  control freak like me you want to keep your CSS from getting out of control. I found its good to keep the layout and text formatting CSS seperate.  Lots of ways to do it. Here is a few.

You can separate out the layout and formatting by putting some info in the id, and some in the Class.

#mytag
{
    position:absolute;
    width:15px;
    top:0px;
    left:30px;
    padding-top: 6px;
    padding-left:3px;
}

.MyDiv
{


    color: #000000;
    text-decoration: underline;
    font-weight: bold;


}

<div id="mytag" class="MyDiv">Bla Bla Bla</div>


But whats really cool is that you can put multiple classes in one tag to keep your CSS more reusable.

<div id="mytag" class=" Bold Underline BlackText">Bla Bla Bla</div>

.Bold
{
    font-weight: bold;
}

.Underline
{
    text-decoration: underline;
}

.BlackText
{
     color: #000000;
}

Monday, August 20, 2012

PHP Quotes and HTML

For those who don't know, I was one of you till about a month ago, you can have PHP write double quotes into your html.  You just need a slash in front of each " to keep it part of the string.

$mydiv = "<div class=\"myclass\"></div>";
echo $mydiv;
//<div class="myclass"></div>

This is really handy if you need to pass stuff to a javascript function.

$PassThis = "Passed";
$btn = "<button class='btn' onclick=\"MyFun('$PassThis')\">My Button</button>";

Friday, August 17, 2012

To all database developers

To all database developers:

Please when your building your database please make sure that your structures makes some sort of sense.  Please assign primary keys.  And make sure that they mean something.  Remember that one to many relationships are the goal.  And Please Please Please do not make stupid tables that you have to query 3 fields to get any meaningful data out of it. If for no other reason to preserve the sanity of the developers that come after you.

Thursday, August 16, 2012

Cleaning phone number data from database

I have been working with a database where the phone number data is very dirty.  People have been imputing numbers any old way so I wrote this to clean the data as it comes into the form. It strips out anything that is not a number and removes the '1' at the beginning of the number.
<?php

    private function CleanPhone($ph)
    {
        //break the string into an array
        $phSplit = str_split($ph);
        //Initialize the return value
        $nph = "";
        //Check each item in the array
        foreach($phSplit as $k => $n)
        {
            //if its numeric add it to the return value
            if(is_numeric ($n))
            {
                //if the first number is not a 1 add it to the retun value
                if($k == '0')
                {
                    if($n != '1')
                    {
                        $nph = $nph.$n;
                    }
                }
                else
                {
                    $nph = $nph.$n;
                }
            }
        }
        return $nph;
    }


$nph = CleanPhone($phoneFromDatabase)


$ph1code = substr($nph,0,3);
$ph1pre = substr($nph,3,3);
$ph1suf = substr($nph,6,4);
                   
$ph = "
<div>
          <div>Phone Number</div>
          (<input id='ph1code' name='ph1code' size='3' maxlength='3' type='text' value='$ph1code' form=' Form' />)
           <input id='ph1pre' name='ph1pre' size='3' maxlength='3' type='text' value='$ph1pre' form=' Form' /> -
            <input id='ph1suf' name='ph1suf' size='4' maxlength='4' type='text' value='$ph1suf' form='Form' />
             </div>
                    ";
?>

And here's how it fits on the site.

<html>
<body>

<?php echo $ph; ?>
<form name='Form' action='index.php' method='post'></form>
</body>
</html>

Thursday, August 9, 2012

Website

I configured apache and the web server last night. So I now have a functional dedicated web server for Fractured Nations.  Fractured Nations will be the company name I will publish any games I build under.  The first I am working on will be called Star Fighter.  Which will be a simple multiplayer space game where you control a ship and shoot your friends.  The site is under construction, I have done little more then lay out the basic css. The buttons do nothing, but the foundation is in place and we will see how fast it goes on an hour every evening.

http://www.fracturednations.com

Tuesday, August 7, 2012

Javascript Ajax POST to a html id function


I found and modified this a few months back so I could POST information into a page's div id's.
////////////////////////////////////
///////////AJAX/////////////
/////////////////////////////////////
//url is the target page
//tar is the div target the post is going to
//val is the array being sent. It must be in this format val = "key='value'&key2='value2'";
function PostToDiv(url, tar, val)
{
    var xmlhttp;
    var c = 0;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   
    xmlhttp.open("POST", url, true);
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
           
            document.getElementById(tar).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(val);
}

Return value of Javascript cookies

If you want to read the cookie you wrote.


//returns the value of a cookie by cookie name

function ReadCookie(name)
{
    var c = {};
    var val = "";
    var cookies = document.cookie.split(";");

    //unpack the cookies
    for(var key in cookies)
    {
        //split to array parts
        var s = cookies[key].split("=");
       
        var k = s[0];
        var v = s[1];
       
        c[k] = v;
    }
   
    if(c[name] != 'undefined')
    {
        val = c[name];
    }
    return val;
}

Javascript Cookies

I ran across this a while back.  If you want to hold info in cookies here is a good javascript function to do so.

function setCookie(c_name,value)
{
    var ex=new Date();
    ex.setHours(ex.getHours()+14);
    var c_value=escape(value) + ((ex==null) ? "" : "; expires="+ex.toUTCString());
    document.cookie=c_name + "=" + c_value;
}


Sunday, August 5, 2012

Send POST or GET data to a page from javascript

I found and modified this. It is a javascript function that dynamically creates a form and sends the data via POST or GET to the page.  Enjoy.

The params variable needs you to send data in a key value array object. 

pass = { postThis: 'Posted', andThis: 'as well' };
post_to_url('index.php', pass, 'post');


function post_to_url(path, params, method)
            {
                method = method || "post";

                var form = document.createElement("form");

                form.setAttribute("method", method);
                form.setAttribute("action", path);

                for(var key in params) {
                    var hiddenField = document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("id", key);
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", params[key]);

                    form.appendChild(hiddenField);
                }
                document.body.appendChild(form);
                form.submit();
            }


<?php
echo $_POST['postThis'];  //Posted
echo $_POST['andThis'];  //as well
?>

Saturday, August 4, 2012

Its Saturday so I get to work on my game a bit.  Its crazy how many programs I have open.  It took me forever to figure out all the software needed to build and run a game so I will provide a list of software needed to do so, to save another poor soul from searching forever.

Server Software to run a game
- Web Server ( I run Apache since its free httpd.apache.org/)
- Database Software (I run MYSQL because it is also free www.mysql.com/)
- PHP or ASP for client server communication on the web page(I have been favoring PHP lately)
- Game Server Daemon (I have been trying out Electroserver 5 for its Actionscript interface and the Unity Support in case I go that way.)


Development Software (you don't need all this but I have gotten comfortable with these tools)
- Flash (for Image Object development)
- Flex Builder (for client scripting, layout and publication)
- Netbeans (for server scripting for PHP and Java)
 
- Unity or another game engine can take the place of Flash and Flex and I have thought of using it if I ever go 3d.  
 


 



Friday, August 3, 2012

I thought its about time I started a blog.  The main reason is I need somewhere to keep track of my code notes, and typing it out helps me remember better.  If you do happen by,  feel free to use any code you find.

I have been scripting a lot of PHP and HTML lately and have been wanting the Object Oriented Functions within PHP to be available for the HTML I have been writing so I came up with this.


<?php

/**
 * Description of HTML
 *  -- OO-HTML --
 * @author Joseph Tveter
 *
 * Class to allow HTML to be eaisly written in native php
 * It will also work for building xml
 *
 * The $cmd string is the tag command such as a,div,html
 *
 * The $vals array holds a list of value commands for the html tag
 *
 * The $children array holds a list of children of the tag.  They will be placed in decending order, so a tag at [1] will come before a tag at [2]
 *
 * To print the string call HTML();
 * example:
 *
 * $mydiv = new HTML('div');
 * $mydiv->addValue('name', 'mydiv');
 * $mydiv->addChild('Hello World', '1');
 * echo $mydiv->HTML();
 *
 * <div name='mydiv'>
 * Hello World
 * </div>
 *
 *
 * I added some functions to make it a bit more like actionscript but you can also manipulate the tag arrays directly.
 *
 */
class HTML
{  
    public $cmd = "";
    public $vals = array();
    public $children = array();
   
    public function __construct($cmd)
    {
        $this->cmd = $cmd;
    }
   
    public function HTML()
    {
        $r = "";
       
        //values
        $val = "";
        foreach($this->vals as $k => $v)
        {
            $val = $val." ".$k."=\"$v\"";
        }
       
        //Children
        $child = "";
        foreach($this->children as $v)
        {
            $child = $child.$v."\n";
        }
       
        //Build and return the HTML string
        $r = "<".$this->cmd.$val.">\n$child</".$this->cmd.">";
        return $r;
    }
   
    public function addChild($child, $num)
    {
        $this->children[$num] = $child;
    }
   
    public function removeChild($num)
    {
        unset($this->children[$num]);
    }
   
    public function addValue($cmd, $val)
    {
        $this->vals[$cmd] = $val;
    }
   
    public function removeValue($cmd)
    {
        unset($this->vals[$cmd]);
    }
}

?>