• How To Make A Simple Python Keylogger


    Python is a really easy programming language for beginners. What better way to showcase it’s range of abilities than making a simple keylogger.

  • Make A Chrome App in 5 minutes


    Making a Chrome App and an Extension is actually a fairly simple task. All you have to know is a few required fields and the JSON syntax.

     

    Download the examples used in the video here:

     

    http://www.tinkernut.com/demos/347_chrome.zip

     

    Further Learning:

    http://www.json.org/

    http://developer.chrome.com/dev/extensions/getstarted.html

    https://developers.google.com/apps-script/publishing_chrome_web_store

    https://developers.google.com/apps-script/execution_web_apps

    http://www.labnol.org/software/create-chrome-apps-extensions/27958/

  • How To Make A Web App In 7 Minutes


    Writing a web app is actually pretty simple when using the free tools that Google provides.

     

    http://script.google.com

     

    http://www.w3schools.com/jsref/jsref_obj_math.asp

  • HTML5 Photo Booth


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=2sXkl3rR-yc” browser_url=”https://www.youtube.com/watch?v=2sXkl3rR-yc”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-9294925e-bc34″][vc_column_text]

    HTML5 is ramping up to become a more and more robust markup language. So flex your code monkey muscles and lets make an HTML5 photo booth application.

    [/vc_column_text][vc_button title=”View Demo” target=”_self” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/343_photobooth/photobooth.html”][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-9294925e-bc34″][vc_button title=”Download Code” target=”_blank” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/343_photobooth/343_photobooth.zip”][vc_column_text]

    What you should already know

    Before starting this tutorial, it is assumed that you already know the basics of web development. This includes, HTML, CSS, Javascript, and HTML5. Without a basic understanding of these languages, it will be very difficult to understand the logic used to make this program work. So, as a prerequisite, it is recommended that you view these tutorials on the basics of web development before continuing.

    1. HTML Basics
    2. CSS Basics
    3. Javascript Basics
    4. HTML5 Basics

    Needed Tools

    Programming with web languages requires very little extra software. You only need three things:

    1. A text editor (I recommend Notepad ++)
    2. A compiler (Any web browser that supports HTML5 will do)
    3. A web server (A good free web server service is 000webhost)

    Demo and Download

    The code

    photobooth.html

    This is the full code that should be saved as photobooth.html and uploaded to your web server.

    <html>
         <head>
              <title>My Photo Booth</title>
         <head>
         <body>
              <center>
              <video id="webcam" width="200" height="200"></video>
              <br>
              <input type="button" id="snapPicture" value="Snap A Picture!" />
              <p> 
              <canvas id="capture" style="display:none;"></canvas>
              <img id="canvasImg" alt="right click to save">
              <script src = "script_photo.js"></script>
              </center>          
         </body>
    </html>
    
    

     

    script_photo.js

    This is the code for script_photo.js. This should be uploaded to your web server in the same direcotry as photobooth.html

    var photoButton = document.getElementById('snapPicture');
    photoButton.addEventListener('click', picCapture, false);
    
    navigator.getUserMedia ||
         (navigator.getUserMedia = navigator.mozGetUserMedia ||
         navigator.webkitGetUserMedia || navigator.msGetUserMedia);
    
    if (navigator.getUserMedia) {
              navigator.getUserMedia({video:true,audio:false}, onSuccess, onError);
         } else{
              alert('Your browser isn't supported');
    }
    
    function onSuccess(stream) {
         vidContainer = document.getElementById('webcam');
         var vidStream;
         if (window.webkitURL){
              vidStream = window.webkitURL.createObjectURL(stream);
              }else{
                   vidStream = stream;
         }
         vidContainer.autoplay = true;
         vidContainer.src = vidStream;
    
    }
    
    function onError(){
         alert('Houston, we have a problem');
    }
    
    function picCapture(){
         var picture = document.getElementById('capture'),
              context = picture.getContext('2d');
    
         picture.width = "600";
         picture.height = "400";
         context.drawImage(vidContainer, 0, 0, picture.width, picture.height);
    
         var dataURL = picture.toDataURL();
         document.getElementById('canvasImg').src = dataURL;
    }
    
    
    
    

     

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-9294925e-bc34″][vc_column_text]

    Important Links

    Help support my channel: http://www.patreon.com/tinkernut

    Follow Tinkernut!

    [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]

  • I CAN LERN CODEZ?


    Learn the basics of programming using a simple programming language called LOLCODE.
    LOLCODE Compiler – http://asgaard.co.uk/misc/loljs/
    Final code:
    HAI
    I HAS A DAY ITZ “Today is Caturday!!!!”
    I HAS A NEWDAY
    I HAS A COUNT
    GIMMEH NEWDAY
    BOTH SAEM NEWDAY AN “Saturday”, O RLY?
    YA RLY
    IM IN YR LOOP
    UPZ COUNT!!1
    VISIBLE DAY
    IZ COUNT BIGR THAN 4?, GTFO, KTHX
    IM OUTTA YR LOOP
    NO WAI
    VISIBLE “Iz no Caturday!!!”
    OIC
    KTHXBYE
  • Make A Simple Responsive Website


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=RSoWg29wPVc” browser_url=”https://www.youtube.com/watch?v=RSoWg29wPVc”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-92947b1b-34c3″][vc_column_text]

    A responsive website is a website that changes it’s size and shape so that it can be viewed properly on any device. This is a tutorial that shows you the steps on how to make your own responsive website. Before jumping in, it’s best to watch my beginners guide to HTML and CSS at the links below.

    [/vc_column_text][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-92947b1b-34c3″][vc_button title=”View sample Site” target=”_blank” icon=”none” size=”btn-huge” href=”http://tinkernut.com/demos/315_responsive/index_responsive.html”][vc_column_text]

    How Does A Responsive Website Work?

    A new addition to CSS3 is an element called a Media query, so if you haven’t already, take a look at my CSS tutorial before continuing. A media query allows CSS code to be executed only when certain constraints are met. For instance, you can set the media query to turn the background color of the webpage blue only when the browser size is 480px. So using media queries, you can have several different sets of CSS for your website that can be activated for many different devices or any browser sizes.

     

    How To Create Media Queries

    Media Queries are elements of CSS3, so they go in the CSS portion of your webpage. Normally the CSS is located in the header using style tags. To create a media query, just add the code below to your CSS:

    <style>
    @media {
    }
    </style>
    

    Then after the @media declaration, you can set the parameters you want to target, such as browser size or device size. For browsers, you can use the max-width attribute. For devices, you can use the max-device-width attribute. To set the media parameters in between a maximum value and a minimum value, you can use both the max-width and min-width attributes within the same parameter.

    <style>
    @media screen and (max-width:480px){
    }
    </style>
    

    This is an example of a max and min parameter:

    <style>
    @media screen and (max-width:800px) and (min-width: 480px){
    }
    </style>
    

    The only thing left to do now is to add your own custom CSS code in between the curly brackets. The CSS can be minimal changes, or you can completely change the design and makeup of the entire site. How much or how little is completely up to you.

    <style>
    @media screen and (max-width:480px) {
         div.main{
    	width:300px;
         }
         div.row2col1{
    	font-size:0.5em;
         }
         img{
    	width: 250px;
         }
         p.welcome {
    	font-size:0.8em;
         }
         p.content {
    	font-size:0.7em;
         }
    					
    }
    </style>
    

     

     

    Sample Website Code

    Below is a finished copy of the webpage code used in the video:

    <html>
    	<head>
    		<title>My Data</title>
    		<style>
    			b{
    			color:#000000;
    			}
    			a{
    			text-decoration:none;
    			color:grey;
    			}
    			img{
    			display:block;
    			margin:auto;
    			}
    			p.welcome {
    				text-align:center;
    				font-family: “verdana”;
    				font-size:1.875em;
    				color:white;
    				font-style:bold;				
    			}
    			p.content {
    				font-family: “verdana”;
    				font-size:1em;
    				color:white;
    				font-style:italic;				
    			}
    			div.main{
    				width:50%;
    				margin:auto;
    				background:#251111;
    			}
    			div.row1{
    			width:100%;
    			}
    			div.row2{
    			width:100%;
    			}
    			div.row2col1{
    				float:left;
    				margin:0;
    				padding:1em;
    				color:white;
    			}
    			div.row2col2{
    				margin-left:25%;
    				background-color:#0A1616;
    				padding:1em;
    				border:15px solid #251111;
    			}
    			body{
    				background-color:#393635;
    				color:white;
    			}
    			@media screen and (max-width:480px) {
    					div.main{
    						width:300px;
    					}
    					div.row2col1{
    						font-size:0.5em;
    					}
    					img{
    						width: 250px;
    					}
    					p.welcome {
    						font-size:0.8em;
    					}
    					p.content {
    						font-size:0.7em;
    					}
    					
    			}
    			@media screen and (max-width:800px) and (min-width: 480px) {
    					div.main{
    						width:600px;
    					}
    					div.row2col1{
    						font-size:0.7em;
    					}
    					img{
    						width: 400px;
    					}
    					p.welcome {
    						font-size:1em;
    					}
    					p.content {
    						font-size:0.8em;
    					}
    					
    			}
    		</style>
    	</head>
    	<body>		
    		<div class="main">
    			<div class="row1">
    				<img src="logo.jpg"/>
    			</div>
    			<div class="row2">
    				<div class="row2col1">
    					Navigation
    					<hr align="left" width=75%>						
    						<ul>
    							<li><a href="about.html">About Me</a></li>
    							<li><a href="http://www.google.com">Google</a></li>
    						</ul>
    				</div>
    				<div class="row2col2"><p class="welcome" >Welcome to my data page!</p><p class="content" >This page is a work in progress that will eventually show places for data input, as well as data recall. Check back here for updates and more information! Thanks for visiting!</p>
    				</div>
    			</div>
    
    		</div>
    		
    	</body>
    </html>
    
    
    

     

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-92947b1b-34c3″][vc_column_text]

    Important Links:

    Help support my channel:

    [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]

  • Website Basics 6 – MySQL


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=WKw_Q3wUX0Q” browser_url=”https://www.youtube.com/watch?v=WKw_Q3wUX0Q”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-929441a5-bb59″][vc_column_text]

    Many people on the internet aren’t familiar with how to make a decent website on the internet. In an effort to remedy that, this episode kicks off the first of a five part series explaining the different aspects of building a good looking, database driven website from scratch.

     

    In the final part 6 of this series, we will look at the connecting our website to our MySQL database.

    Here’s a list of the other tutorials in the series:

    [/vc_column_text][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-929441a5-bb59″][vc_button title=”Download Code Sample” target=”_blank” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/309_mysql/309_mysql.zip”][vc_column_text]

    What is a database?

    A database is an organized means of storing data and information. There are several different database software programs out there for creating database, but when it comes to websites, MySQL software is most widely used. In the MySQL software, databases are the top level of organization. You can have dozens of different databases depending on your computers storage capacity. Databases classify data into very broad subjects, such as “Financial Database” and “Office Database”. Within each database is a table. Tables are used to classify the data into common groups. For instance, in the “Office Database”, you could have a table for “Coworkers” and a table for “Shifts”. In each table are columns. Columns divide up the data into much more specific groups. Taking the “Coworkers” table from the “Office Database”, you can have columns for “ID”, “First Name”, “Last Name”, “Phone Number”, and “Address”. Within each column is a row or record of data. This is where the actual data goes.

     

    OFFICE DATABASE

    Coworkers
    ID First Name Last Name Phone Number Address
    14 Bob Dole 999-999-9999 1 Google Drive

     

    Creating A MySQL Database

    MySQL is a popular database for websites. Back in our episode of setting up a WAMP server, MySQL, along with PHP, was automatically installed on our server. There are two main ways of creating databases in MySQL. The first is through using PHPMyAdmin. This is the most common interface for web hosting providers. If you were to purchase hosting space from someone, PHPMyAdmin would most likely be your database interface. The second method is through the MySQL command line. Although the command line may seem intimidating, it’s actually a much easier and faster method of setting up a database.

    Setting up a database through the command line means knowing about database queries. A query is an action request for a database. Some examples of database actions are CREATE, SELECT, and INSERT. Click the query link above for a large list of common database queries. When you open up a the command line interface, it will prompt you for a password. By default there is no password, so hitting enter will bypass this prompt. But for security reasons, we should go ahead and create a password. The default account for the database is called “root”, so this is the account that we will need to make a password for. To set a password, you can use this SET query:

    SET PASSWORD FOR 'root'@'localhost' = PASSWORD('abc123');
    

    It’s important to note how each query ends in a semi-colin (;). The capitalization of the letters (the case) is not important. In this instance, it just shows the difference between queries and custom information. Now that we have secured our database with a password, we can view what databases already exist. By default, the MySQL installation comes with a few sample database. To view them, you can use the SHOW query:

    SHOW DATABASES;
    

    This returns a list of existing databases. So now let’s add our own database to the list. Creating a new database is simple. Just use the CREATE DATABASE query followed by a name that you have chosen for your database. Here’s an example:

    CREATE DATABASE my_data;
    

    Before we can add stuff to our new database, we have to actually select it. So to do that, we will use the USE query:

    USE my_data;
    

    This selects our database and any queries from here on will be executed within our database. So the next step is to create a table within our database. Your database can have several different tables, but for now we will just create one. Using the CREATE query again, we can create a table with a name of our choice:

    CREATE TABLE users;
    

    But to make things simpler, we can use CREATE TABLE query and go ahead and attach our column query onto it. When creating columns, you have to include character specifications for each column so that the database knows which characters are and are not allowed. There’s four core types to choose from: numbers signified by the type INT (for integer), text and numbers signified by the type VARCHAR, text signified by the type TEXT, and date formats signified by the type DATE. For TEXT and VARCHAR types, you can also specify the number of characters allowed for each column. For instance, most first names are generally less than 20 characters long (the name “gigafide” is 8 characters long). So you can set the character limit for those types by adding it in parenthesis, such as VARCHAR(20). Keep in mind that if the characters are longer than that number, only 20 characters will be stored in the database.

    CREATE TABLE users(id int, username varchar(20), password varchar(100));
    

    For records, it’s good practice to have a column that stores a unique value that can be used to differentiate between all of the different records. This is why most tables have an ID column. This column of unique values is called a Primary Key. So that we don’t have to constantly enter a unique value manually when adding a new record, we can set it to automatically increment with each new addition. To do this, add the AUTO_INCREMENT query to the id column. Also, we need to make this column required so that it is never accidently left blank. So we can add the NOT NULL query to it as well. To wrap it all up, after all the columns are listed, add a PRIMARY KEY query and set it to the column that you want to use as the primary key. In this case, it’s the id column. Here is what the final CREATE TABLE query will look like:

    CREATE TABLE users(id int NOT NULL AUTO_INCREMENT, username varchar(20), password varchar(100), PRIMARY KEY (id));
    

    Now we have our database, table, and columns. All that’s left to do is add data to the columns. For inserting data, we will be using the INSERT INTO query. Then we just add the table name that we want, the columns that we will be inserting values into, and then the values themselves.

    INSERT INTO users(username,password) values('gigafide','abc123');
    

    Finally, to view what you’ve just created, you can use the SELECT query followed by an asterisk (*), which says to select all values.

    SELECT * FROM users;
    

    Encryption

    When dealing with passwords, it’s a good precaution to encrypt password values before they are inserted into the database. There are tons of different available encryptions out there, but the most common one when dealing with MySQL is called Md5. Encrypting a value using the Md5 encryption method is really simple. All you have to do is enclose the value that you want to encrypt with parenthesis and add md5 to the beginning of it. Below is an example where the password value has been encrypted.

    INSERT INTO users(username,password) values('gigafide',md5('abc123'));
    

    Be aware that if you want to compare any values to the encrypted database value, the compared value will need to be encrypted as well or else it will not match up with what is in the database.

    Connecting a webpage to your database

    If you want to use the data in our database with your webpage, you will need to create a script that connects it to your database. The most common language used for interfacing a website with a database is PHP. This is because PHP has a lot of built in functions that makes it easy to get information from databases. For example, to log into a database, you can use a function called mysql_connect and it takes the parameters of your server location, you server username, and your server password. If you are running a WAMP server, your server location will be localhost. Otherwise, it will probably be an IP address or URL of some sort.

    mysql_connect("localhost","root","abc123");
    

    To test connectivity, you will need to set this function equal to a PHP variable and then add it to an IF statement to see if there are any errors upon connection. If there are, you can have it return any errors using the mysql_error() function. Otherwise, you can select the database you want to use. This can be done using the mysql_select_db function using your database name and the mysql_connect variable. The full final connection script should look something like this.

    <?php
    	$db_con = mysql_connect("localhost","root","abc123");
    	if (!$db_con)
    	  {
    		die('Could not connect: ' . mysql_error());
    	  }
    	  mysql_select_db("my_data", $db_con);
    ?>
    

    This code can be added directly to the webpage, or it can be added to a page of it’s own. As an example, you can save this script to a page called config.php and then link to this page from any other webpage using the include PHP script:

    <?php
         include('config.php');
    ?>
    

    Verifying User Credentials With A Database

    One primary use of a database is to store user information and then use that information to verify a user when they log in to your website. In the previous PHP tutorial, we created a form that asked for log in credentials and then passed those credentials to a page that verified them and then logged the user into the website if the credentials were correct. We can use this same method to validate the user using the database, but we have to change a few things first. Here is the original verification code:

    <?php
    $mypass = “abc123”;
    $passcheck = $_POST[“password”];
    if ($passcheck == $mypass){
    echo “Welcome, ” . $_POST[“username”] . “! You are now logged in.
    “;
    $_SESSION[‘user’]= $_POST[“username”];
    $_SESSION[‘pass’]= $passcheck;
    }
    else
    echo “Sorry, wrong password.
    “;

    ?>

    The variables store the valid password and the password sent from the form. Since the valid password is now in the database, we can remove the the $mypass variable and replace it with a $usercheck variable that stores the username sent from the form.

    $usercheck = $_POST["username"];
    

    Next we need to create a database query that checks to see if the submitted username is actually in the database. We can use the PHP mysql_query function along with the SELECT * FROM query. Then we set the select parameters WHERE the username is equal to the usercheck variable from the form. Then you can set that entire query equal to a variable.

    $db_query = mysql_query("SELECT * FROM users WHERE username = '" . $usercheck  . "'");
    

    After that, before checking the password, you need to actually run the query and see if it returns any results. So you can use an IF statement to see if it returns a row. If it does, then you can run the password verification script. If not, then you can echo a result saying that the password is wrong.

    if (mysql_num_rows($db_query) == 1){
         ....PASSWORD SCRIPT....
    }
    else
         echo "Sorry, wrong username. <br/>";
    

    In order to check the submitted password variable with the password from the database, we need to assign the row that was found to an array variable using the mysql_fetch_array function.

    $record = mysql_fetch_array($db_query);
    

    This will allow us to select any column from that record. So the column that we want is the password column. To access it, you just type the $record variable followed by the column in question.

    $record['password']
    

    With that in mind, and remembering to encrypt the submitted password, our new password check if statement should look like this:

    if (md5($passcheck) == $record['password']){
    

    The final script in it’s entirety looks like this:

    <?php
    if (mysql_num_rows($db_query) == 1){
         $record = mysql_fetch_array($db_query);
         if (md5($passcheck) == $record['password']){
    	echo "Welcome, " . $usercheck . "! You are now logged in. <br/>";
    	$_SESSION['user']= $usercheck;
    	$_SESSION['pass']= $passcheck;
         }
          else
    	echo "Sorry, wrong password. <br/>";
    }
    else
         echo "Sorry, wrong username. <br/>";
    ?>
    

    Adding Form Data To A Database

    Retrieving information from a database is only half of the database functionality. With PHP, you can also add values and records to a database. A common reason to do this is to store data from a form, such as adding a user to a website. So, you will need to start out with a typical PHP form, that points to a page that can add the data to the database. We’ll call this page “add_user.php”. Here’s a typical form:

    <form action='add_user.php' method='post'>
    Name:<input type='text' name='addusername'/>
    Password:<input type='password' name='addpassword'/>
    <input type='submit' value='Add'/>
    </form>
    

    Notice that the password type is set to password. This will make it so that the form field shows only dots instead of revealing the actual password. This form stores the form fields as addusername and addpassword variables and then passes those variables to the add_user.php page that will then insert the values into the database. For the add_user page, you want to make sure you start the session and that you include the config.php page first so that we connect to the database:

    <?php session_start(); 
    include('config.php');
    ?>
    

    Then you can add your page theme or template. For the content, you want to run an INSERT query using the variables sent from the form. Before adding the password, however, make sure that it is first encrypted using md5. Then assing this query to a variable, and run it through an IF statement to execute it. If it fails, then display the error. If it succeeds then you can echo “User Added”.

    <?php
         $db_query="INSERT INTO users (username, password) VALUES ('$_POST[addusername]',md5('$_POST[addpassword]'))";
         if (!mysql_query($db_query)){
              die('Error: ' . mysql_error());
         }
         echo "User Added";
    ?>
    

    Inserting Database Data Into HTML Tables

    A good way to show data from a database on a webpage is by displaying it in an HTML table. The first step in this process is to create a SQL query variable that selects the table or data that you want to display.

    <?php
         $db_query= mysql_query("SELECT * FROM users");
    ?>	
    

    The next step is to use PHP to echo an HTML table with one row and two columns: One for User ID and one for Username.

    <?php
         $db_query= mysql_query("SELECT * FROM users");
         echo "<center><h1> User List:</h1><table border='1'>
         <tr>
         <td><b>User ID</b></td>
         <td><b>Username</b></td>
         </tr>
         </table>
         </center>";
    ?>
    

    We want to add more rows, but we want the rows to be equal to the amount of data records returned from the query. The most effective way to do this is to put the row HTML within a while loop so that it loops a new row for each record until there are no more records. Then display the results in the columns using record array.

    <?php
         $db_query= mysql_query("SELECT * FROM users");
         echo "<center><h1> User List:</h1><table border='1'>
         <tr>
         <td><b>User ID</b></td>
         <td><b>Username</b></td>
         </tr>";
         while($record = mysql_fetch_array($db_query)){
              echo "<tr>";
              echo"<td>" . $record['id'] . "</td>";
              echo"<td>" . $record['username'] . "</td>";
              echo"</tr>";
         }
         echo"</table></center>";
    ?>
    

    Pay close attention to the echo statements and how you have to make sure the PHP code is not enclosed within an echo statement. Each line of the new row within the while loop as it’s own echo statement.

    Final Code

    Here is the final code for the pages used in this tutorial. You can combine these with pages from other tutorials that are not included here.

    config.php

    <?php
         $db_con = mysql_connect("localhost","root","abc123");
         if (!$db_con){
              die('Could not connect: ' . mysql_error());
         }
         mysql_select_db("my_data", $db_con);
    ?>
    

    add_user.php

    <?php session_start(); 
    include('config.php');
    ?>
    <html>
    <head>
    <title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    
    <?php include("header.php"); ?>
    <p class="welcome" id="greeting">
    <?php
      $db_query="INSERT INTO users (username, password) VALUES ('$_POST[addusername]',md5('$_POST[addpassword]'))";
    
    if (!mysql_query($db_query))
      {
      die('Error: ' . mysql_error());
      }
    echo "User Added";
    ?>
    </p>
    <a href="index.php">Click here</a> to return to the main page.
    <?php include("footer.php"); ?>
    
    	</body>
    </html>
    

    welcome.php

    <?php session_start(); 
    include('config.php');
    ?>
    <html>
    <head>
    <title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    
    <?php include("header.php"); ?>
    <p class="welcome" id="greeting">
    <?php
    	$usercheck = $_POST["username"];
    	$passcheck = $_POST["password"];
    	$db_query = mysql_query("SELECT * FROM users WHERE username = '" . $usercheck  . "'");
    	if (mysql_num_rows($db_query) == 1){
    		$record = mysql_fetch_array($db_query);
    		if (md5($passcheck) == $record['password']){
    			echo "Welcome, " . $usercheck . "! You are now logged in. <br/>";
    			$_SESSION['user']= $usercheck;
    			$_SESSION['pass']= $passcheck;
    			}
    		else
    			echo "Sorry, wrong password. <br/>";
    	}
    	else
    		echo "Sorry, wrong username. <br/>";
    
    ?>
    <a href="index.php">Click here</a> to return to the main page.
    
    <?php include("footer.php"); ?>
    
    	</body>
    </html>
    

    Index.php

    <?php session_start(); 
    include('config.php');
    ?>
    <html>
    	<head>
    		<title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    		<script>
    			function clicked(){
    			var x;
    			var y;
    			x = document.getElementById('nameCheck').value;
    			y = document.getElementById('password').value;
    			if(x !="" && y !=""){
    				return true;
    				}
    				else if(y ==""){
    					document.getElementById('errorPass').innerHTML='<font color="red">(required) Password:</font>';
    					return false;
    					}
    				else if(x ==""){
    					document.getElementById('errorMsg').innerHTML='<font color="red">(required) Name:</font>';
    					return false;
    				}
    				
    				
    			}
    		</script>
    	</head>
    	<body>		
    <?php include("header.php"); ?>
    					<?php
    					if (isset($_SESSION['user'])){
    					$db_query= mysql_query("SELECT * FROM users");				
    						echo "<center><h1> User List:</h1><table border='1'>
    							<tr>
    							<td><b>User ID</b></td>
    							<td><b>Username</b></td>
    							</tr>";
    							
    						while($record = mysql_fetch_array($db_query)){
    							echo "<tr>";
    							echo"<td>" . $record['id'] . "</td>";
    							echo"<td>" . $record['username'] . "</td>";
    							echo"</tr>";
    							}
    						echo"</table>
    						</center>";
    							}
    					else 
    						echo "<p class ='welcome' id='greeting'> Please Login:</p>
    								<form action='welcome.php' method='post' onSubmit='return clicked();'>
    									<b id='errorMsg'>Name:</b>
    									<input type='text' id='nameCheck' name='username'/>
    									<b id='errorPass'>Password:</b> <input type='password' id='password' name='password'/>
    									<input type='submit' value='Click Me'onClick='clicked()'/>
    								</form>";
    					
    					?>
    					<?php
    					if (isset($_SESSION['user']) && $_SESSION['user']=="gigafide")
    					echo "<p class ='welcome' id='greeting'> Add User:</p>
    								<form action='add_user.php' method='post' onSubmit='return clicked();'>
    									<b id='errorMsg'>Name:</b>
    									<input type='text' id='nameCheck' name='addusername'/>
    									<b id='errorPass'>Password:</b> <input type='password' id='password' name='addpassword'/>
    									<input type='submit' value='Add'/>
    								</form>";
    								?>
    				<p class="content" >This page is a work in progress that will eventually show places for data input, as well as data recall. Check back here for updates and more information! Thanks for visiting!</p>				
    <?php include("footer.php"); ?>
    	</body>
    </html>
    
    
    

     

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-929441a5-bb59″][vc_column_text] Help support my channel: http://www.patreon.com/tinkernut Follow Tinkernut! Google + Facebook Twitter [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]

  • Website Basics 5 – PHP


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=j-2Rz3nL2HU” browser_url=”https://www.youtube.com/watch?v=j-2Rz3nL2HU”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-92949565-beb2″][vc_column_text]

    Many people on the internet aren’t familiar with how to make a decent website on the internet. In an effort to remedy that, this episode kicks off the first of a five part series explaining the different aspects of building a good looking, database driven website from scratch.
    In part 5 of this series, we will look at the basics of using PHP and adding its functionality to our site.

    Here’s a list of the other tutorials in the series:

    [/vc_column_text][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-92949565-beb2″][vc_button title=”Download Code Sample” target=”_blank” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/308_php/308_php.zip”][vc_column_text]

    Basic PHP Syntax

    There are several requirements before your PHP page will become functional. The first requirement is to make sure that you have a server with PHP installed. If not, you can learn how by watching the create a server tutorial. Your website files must reside on the server. Next, any file that has executable PHP code must be saved as a PHP file. For example, if your index.html page has PHP code in it, it must be saved as index.php before the code can be executed. Lastly, in order for the browser to process PHP, it has to be declared using the following tag structure:

    <?php
         PHP CODE GOES HERE
    ?>
    

    Anything in between those declaration tags will be processed as PHP code. PHP tags can go anywhere in a webpages HTML structure, but is generally found in the body of the HTML code or above the HTML code (before the opening <HTML> tag). To display text or HTML on a webpage using PHP, you want to use the “echo” command. The “echo” command followed by the text or HTML code in quotes will tell it the web browser to process that text or code as regular HTML. Here is an example:

    <?php
         echo "It's PHP!";
    ?>
    

    Notice how the “echo” command is terminated by a semi-colon. Apart from conditional statements, all PHP code should end with a semi-colon. If an echo statement contains HTML code that has quotation marks (“), you will need to replace them with apostrophes (‘). This prevents confusion when processing the PHP code.

    <?php
         echo "<p class ='welcome' id='greeting'> Hi! Welcome to my site!</p>";
    ?>
    

     

    Variables

    A variable is an object within programming code that can change it’s value as the program is executed. It’s similar to mathmatics were variables are used in equations to represent unknown values i.e. 2 + x = 4. Variables are used very frequently in Javascript because their value can be set to whatever you need it to. To create a variable in PHP, you want to come up with a name for your variable, and then precede it with a dollar ($) sign. Then you can set it equal to the value you desire. To recall the variable at any point in your code, simple type the name of the full name of the variable including the $ sign.

    <?php
         $username = "gigafide";
         echo $username;
    ?>
    

    When returning a variable value, sometimes you may want the variable to appear in the middle of a string of other text, such as a sentence. This is called concatenation As opposed to Javascript where a plus (+) sign is used to concatenate strings together, PHP uses a period (.) to concatenate.

    <?php
         $username = "gigafide";
         echo "<p class ='welcome' id='greeting'> Hi, " . $username . "! Welcome to my site!</p>";
    ?>
    

    Conditional Statements

    A conditional statement is a section of code whose output is dependent on certain conditions. In PHP, this is charactarized by an “if” statement. An “if” statement will output a result if certain conditions are met. The syntax of an “if” statement starts with if followed by the conditions in a set of parenthesis. Immediately following this, you will put the line of code to be executed if the conditions are met. If you have more than one condition to be executed, you can enclose the code to be executed within curly brackets. If the conditions are not met, you can add an “else” statement after the “if” statement. The else statement can contain code to be executed if the conditions are not met.

    <?php
         if($username == "gigafide"){
              echo "<p class ='welcome' id='greeting'> Hi, " . $username . "! Welcome to my site!</p>";
              echo "Thanks for visiting!";
         }else 
              echo "Hi! Welcome to my site!";
    ?>
    

    Include

    A great benefit that PHP offers is the ability to import HTML or PHP code into your page from a separate file. This is through a function called the include command. Include is often used when creating website templates. [WordPress] is a common platform that makes regular use of the include function for its templates. Here is how it works. Create a seperate page (both html and php pages will work) and put a section of HTML code in it. Then, on your main webpage, place the PHP include function with the seperate pages name wherever you want it to appear on the main webpage.

    <?php
         include("header.php");
    ?>
    

    This is a good method of keeping a website organized. If you have a section of your website (such as a navigation menu) that stays static throughout your website, you can use it as an include webpage instead. This will shorten the websites code significantly, as well as allow you to only have to modify one page.

    Think of it this way: if you have 100 pages on your website,and they all had a common menu, it would be a tedious task to edit 100 menus. With PHP, you can include one menu in 100 pages, and edit one menu to complete the task.

    Passing Information Between Pages

    Forms

    Method:GET

    Method:POST

    Storing User Information

    If you’re going to create a website that requires a user to enter information, it’s almost a necessity to store that information somewhere so that the user doesn’t have to enter it again and so that it can be recalled later and used elsewhere in the site. In PHP, there are two methods of storing a users information. One is Cookies and the Other is Sessions.

    Cookies

    Cookies are a means of storing a user’s information so that the user doesn’t have to enter in the same information again. For instance, websites commonly store a cookie of your username and password so that you don’t have to keep logging in to the website everytime you visit. Cookies store the information on the client’s computer as a small file. If the website needs to recall that information later, it can open up the cookie and read the information stored there. Let’s say you want store information from a form to a cookie. First you need to create a cookie using “setcookie” parameter, then give it a name, the value you want to store, and the time before it expires.

    <?php
         setcookie("user", $_POST["username"], time()+3600);
    ?>
    

    Then if you want to recall that value later on, you can use this code

    <?php
         echo $_COOKIE["user"];
    ?>
    

    Or if you wanted to return the entire contents of a cookie, you can use this code

    <?php
         print_r($_COOKIE);
    ?>
    

    To use the cookie information in a conditional statement, you want to use the ISSET command to check and see if there is information stored in the cookie. If there is information stored in it, you can execute one set of commands. IF there is not information stored in it, you can execute another set of commands.

    <?php
         if (isset($_COOKIE["user"]))
           echo "Hi, " . $_COOKIE["user"] . "Welcome to my site!<br />";
    ?>
    

    Finally, if you want to delete the cookie information (such as to create a “log out” page), essentially you just set the cookie expiration date to a negative value.

    <?php
         setcookie("user", "", time()-3600);
    ?>
    

    Sessions

    Sessions are another means of storing users information. Except, unlike Cookies, they store information on the server as opposed to the clients computer. To start a session, you have to put a session_start script at the beginning of every webpage that uses session information (above the opening HTML tag).

    <?php session_start(); ?>
    

    Session information can then be stored to $_SESSION variables the same way you would store any other variable. Then you can recall the session information by simply using the variable name you created. Here’s an example.

    <?php
         $_SESSION['user']="gigafide;
         echo "Hi, ". $_SESSION['user'];
    ?>
    

    Similar to the cookie example above, you can use Session information in an if statement by adding the ISSET command.

    <?php
         if(isset($_SESSION['user']))
           echo "Hi," . $_SESSION['user'] . "!";
    ?>
    

    And then finally, to stop storing information for a session (and to forget the stored information), you can add a session_destroy command underneath the session_start command for your logout page.

    <?php
    session_start(); 
    session_destroy();
    ?>
    

    Final Code

    After completeing the tutorial, you should have something similar to the code below. Please use this code for reference and correction.

    header.php

    <div class="main">
    	<div class="row1">
    		<img src="logo.jpg"/>
    	</div>
    	<div class="row2">
    		<div class="row2col1">
    			Navigation
    			<hr align="left" width=75%>						
    				<ul>
    					<li><a href="about.html">About Me</a></li>
    					<li><a href="http://www.google.com">Google</a></li>
    				</ul>
    		</div>
    		<div class="row2col2">
    

    footer.php

              </div>
         </div>
     </div>
    

    logout.php

    <?php
    session_start(); 
    session_destroy();
    ?>
    <html>
    <head>
    <title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    
    <?php include("header.php"); ?>
    <p class="welcome" id="greeting">
    You are now logged out
    </p>
    
    	</body>
    </html>
    

    welcome.php

    <?php session_start(); ?>
    <html>
    <head>
    <title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    <?php include("header.php"); ?>
    <p class="welcome" id="greeting">
    <?php
    	$mypass = "abc123";
    	$passcheck = $_POST["password"];
    	if ($passcheck == $mypass){
    		echo "Welcome, " . $_POST["username"] . "! You are now logged in. <br/>";
    		$_SESSION['user']= $_POST["username"];
    		$_SESSION['pass']= $passcheck;
    		}
    	else
    		echo "Sorry, wrong password. <br/>";
    ?>
    <a href="index.php">Click here</a> to return to the main page.
    <?php include("footer.php"); ?>
    	</body>
    </html>
    

    Index.php

    <?php session_start(); ?>
    <html>
    	<head>
    		<title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    		<script>
    			function clicked(){
    			var x;
    			var y;
    			x = document.getElementById('nameCheck').value;
    			y = document.getElementById('password').value;
    			if(x !="" && y !=""){
    				return true;
    				}
    				else if(y ==""){
    					document.getElementById('errorPass').innerHTML='<font color="red">(required) Password:</font>';
    					return false;
    					}
    				else if(x ==""){
    					document.getElementById('errorMsg').innerHTML='<font color="red">(required) Name:</font>';
    					return false;
    				}
    				
    				
    			}
    		</script>
    	</head>
    	<body>		
    		<?php include("header.php"); ?>
    			<?php
    			
    			if (isset($_SESSION['user']))
    				echo "<p class ='welcome' id='greeting'> Hi, " . $_SESSION['user'] . "! Welcome to my site!</p>";
    			else 
    				echo "<p class ='welcome' id='greeting'> Please Login:</p>
    						<form action='welcome.php' method='post' onSubmit='return clicked();'>
    							<b id='errorMsg'>Name:</b>
    							<input type='text' id='nameCheck' name='username'/>
    							<b id='errorPass'>Password:</b> <input type='text' id='password' name='password'/>
    							<input type='submit' value='Click Me'onClick='clicked()'/>
    						</form>";
    			
    			?>
    			<?php
    			if (isset($_SESSION['user']))
    				echo "<center><h1> User List:</h1>
    					<table border='1'>
    					<tr>
    					<td><b>User</b></td>
    					<td><b>Login password</b></td>
    					</tr>
    					<tr>
    					<td>" . $_SESSION['user'] . "</td>
    					<td>" . $_SESSION['pass'] . "</td>
    					</tr>
    					</table>
    					</center>";
    			?>
    			<?php if (isset($_SESSION['user']))
    				echo "<center><a href='logout.php'>Logout</a></center>";?>
    			<p class="content" >This page is a work in progress that will eventually show places for data input, as well as data recall. Check back here for updates and more information! Thanks for visiting!</p>
    				
    		<?php include("footer.php"); ?>
    	</body>
    </html>
    

     

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-92949565-beb2″][vc_column_text] Help support my channel: http://www.patreon.com/tinkernut Follow Tinkernut! Google + Facebook Twitter [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]

  • Make A Complete Website From Scratch – Part 4:Server


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=cUMYcuOjfns” browser_url=”https://www.youtube.com/watch?v=cUMYcuOjfns”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-9294f5dc-5b7c”][vc_column_text]

    Many people on the internet aren’t familiar with how to make a decent website on the internet. In an effort to remedy that, this episode kicks off the first of a five part series explaining the different aspects of building a good looking, database driven website from scratch.

     

    In part 4 of this series, we will look at the basics of creating a MySQL database that will store the content for our website.

    Here’s a list of the other tutorials in the series:

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-9294f5dc-5b7c”][vc_column_text]

    Links used in the video:

    1. http://www.wampserver.com
    2. http://www.thegeekstuff.com/2008/09/how-to-install-or-upgrade-lamp-apache-mysql-and-php-stack-on-linux-using-yum
    3. http://www.mamp.info/en/index.html
    4. http://www.cmyip.com
    5. http://www.no-ip.com

     

    Help support my channel: http://www.patreon.com/tinkernut Follow Tinkernut!

    1. Google +
    2. Facebook
    3. Twitter

    [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]

  • Make A Complete Website From Scratch – Part 3: Javascript


    [vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=TLjJM-CsOIs” browser_url=”https://www.youtube.com/watch?v=TLjJM-CsOIs”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-9294″][vc_column_text]

    Many people on the internet aren’t familiar with how to make a decent website on the internet. In an effort to remedy that, this episode kicks off the first of a five part series explaining the different aspects of building a good looking, database driven website from scratch.

     

    In part 3 of this series, we will look at the basics of using Javascript and using it to enhance our site.

    Here’s a list of the other tutorials in the series:

    [/vc_column_text][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-9294″][vc_button title=”Download Code Sample” target=”_blank” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/306_javascript/306_javascript.zip”][vc_column_text]

    Javascript Syntax

    To create a Javascript within an HTML file, you generally need to start with “Script” tags to mark the beginning and end of the script. Although not mentioned in the video, it’s a good habit to describe what type of script you are going to be invoking by using the type=”text/javascript” attribute, which you can see in the example below.

    Though not required for simple scripts, it’s also a good idea to divide sections of your script into “blocks”, which are charactarized by opening and closing curly brackets. They are required for functions.

    The lines in between the curly brackets are the Javascript code that is to be executed.

    <script type="text/javascript">
         {
              document.write('Hi! Welcome to my site');
         }
    </script>
    

    Not all browsers support Javascript. Because of this, there is a method to code your Javascript so that it doesn’t try to run on unsupported browsers. The syntax resemebles an arrow and is demonstrated below.

    <script type="text/javascript">
    <!--
         {
              document.write('Hi! Welcome to my site');
         }
    //-->
    </script>
    

    ID’s

    In order to keep Javascripts organized and in one location within your HTML, there needs to be a way to reference elements within the HTML code. When using CSS, this is done through an attribute called “class” that allows you to label the elements that you want to reference. Similarly, when using Javascript, you can use the “ID” attribute to label elements. The value of the ID can be whatever you want, but it’s common practice to use only letters and to make sure it is no longer than one word. In the example below, you see a paragraph element that has been given and ID of “mainText”:

    <p id="mainText">This is my main text </p>
    

    To call an ID from your Javascript code, you want to use the “document” function followed by “getElementById” and then the Id name in parenthesis and quotes. Here’s an example:

    document.getElementById('mainText')
    

    Following this format, you can call other functions such as “value” to return the value of the element, or “innerHTML”, which will overwrite the element with HTML code. You can find examples of both in the final code below.

     

    Functions

    A benefit of Javascript is that you can set aside blocks of code so that it only runs when it’s triggered. This is done through a coding process called “Functions”. Functions let you divide your code up into different sections that can be triggered by different events. To create a function, simply block the Javascript code you want to be in the function with curly brackets {} and before the first curly bracket type function and then the name of your function, which can be anything. The example below shows a script with two different functions within it.

    <script type="text/javascript">
         function changeText{
              document.getElementById('mainText').innerHTML='Welcome to my data page!';
         }
         function alertUser{
              alert('This is an alert!');
         }
    </script>
    

    An important thing to note is that functions will not run unless there is something that executes or triggers it. A common way of triggering a function is through the “onClick” attribute, which can be added to HTML elements. This attribute makes it so that when a user clicks on an element, then the function will be executed. Here’s an example:

    <p id="mainText" onClick="ChangeText">This is my main text </p>
    

     

    Variables

    A variable is an object within programming code that can change it’s value as the program is executed. It’s similar to mathmatics were variables are used in equations to represent unknown values i.e. 2 + x = 4. Variables are used very frequently in Javascript because their value can be set to whatever you need it to. To create a variable in Javascript, you need to declare the var object and then give the variable a name. Commonly x is used, but it can be whatever letter or word you want. After you have declared the variable, you can set it equal to a value. You can change the variables value as many times as you need to throughout the course of your script. Here is an example of a variable in use:

    <script>
         var x;
         x = 'Daniel';
         document.write('My name is ' + x);
    </script>
    

    To make Javascript more concise, you can combine the variable declaration with it’s value declaration. Using the same example as above, here’s what the code would look like if you combined the two:

    <script>
         var x = 'Gigafide';
         document.write('My name is ' + x);
    </script>
    

    Concatenation

    To “concatenate” something means to join or combine two different object together (such as word strings). Each programming language has their own unique way to concatenate strings. In Javascript, we use the + sign. Concatenation is primarily used in displaying the results of something. Here’s what it looks like:

    <script>
         var x = 'Gigafide';
         var y = 'My name is ';
         document.write(y + x);
    </script>
    

    The results of this code would be “My Name is Gigafide”.

    Conditional Statements

    When creating programs in Javascript, you often run across the need to display one of many possible outcomes or options. As an example, if you ask a “yes” or “no” question, you want to display different results depending on what the user answers. This is often accomplished through “conditional statements”. The most commonly used conditional statement in Javascript is the “If” statement

    Operators

    Common Javascripts

    Linking to an external Javascript file

    As with CSS, you can copy all of your code to an external document and link to it from your HTML. What would you want to do this? There’s two possible reasons. The first reason is that it is a good way to keep your HTML code clean and streamlined. The second reason is so that one Javascript can be used on multiple webpages. To create an external file, copy all of your Javascript code (between the <script> tags) to a new document and save it as myjavascript.js, or whatever you want to call it, and save it to the same directory as your index.html file. Then you can add this line to the head of your HTML document:

    <script type="text/javascript" src="myjavascript.js"></script>
    

    Dates and Times

    Another common usage of Javascripting is to display a date or to use a date or time in a function. When dealing with the date function, it’s important to keep in mind that the time that is used is the time on the client/users computer and not the time on the server that your webpage is on. Displaying a date string is very simple. Just use the date object like this:

    <script>
    	document.write(Date());
    </script>
    

    If you want to display only the year or the date, you would need to assign a variable to the date object and then call either getFullYear(), getTime(), or getDay() depending on your need.

    <script>
         var myDate=new Date();
         document.write(myDate.getFullYear());
    </script>
    

    Cookies

    Another useful aspect of Javascript is the ability to store script information on the clients computer. This stored infomration is known as a “cookie”. It’s general purpose is to store user information so that the user doesn’t have to enter in the same information again. For instance, websites commonly store a cookie of your username and password so that you don’t have to keep logging in to the website everytime you visit. Cookies can get very complicated but below you’ll find an example of a cookie that stores the users name and remembers it each time they visit a site. This example is taken from w3schools.com

    Creating a cookie:

    function setCookie(c_name,value,exdays)
    {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
    }
    

    Reading a cookie:

    function getCookie(c_name)
    {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name)
        {
        return unescape(y);
        }
      }
    }
    

    Checking a cookie:

    function checkCookie()
    {
    var username=getCookie("username");
      if (username!=null && username!="")
      {
      alert("Welcome again " + username);
      }
    else 
      {
      username=prompt("Please enter your name:","");
      if (username!=null && username!="")
        {
        setCookie("username",username,365);
        }
      }
    }
    

    Printing a page

    Javascript provides a really simple way to print a web page. The script calls the browsers print function and uses it to print the webpage that the Javascript is on. All that’s required to invoke this script is the “onClick” attribute:

    <form>
    <input type="button" value="Print This Page" onClick="window.print()" />
    </form>
    

    Page Redirect

    “Redirecting” a page is a means of having a webpage auto-forward to a different webpage. A good reason to use this would be for if you are making changes to your web page and you want users to be redirected to a temporary page until your changes are finished.

    <script type="text/javascript">
         window.location = "http://www.google.com/"
    </script>
    

    Final Code

    After completeing the tutorial, you should have something similar to the code below. Please use this code for reference and correction. There are three files, the first one is index.html, which is the HTML code for the main page in your website. The second one is style.css, which is the CSS code referenced in the index.html webpage. don’t say

    INDEX.HTML

    <html>
    	<head>
    		<title>My Data</title>
    		<link rel="stylesheet" type="text/css" href="style.css" />
    		<script>
    			function clicked(){
    			var x; 
    			x = document.getElementById('nameCheck').value;
    			if(x !=""){
    				document.getElementById('greeting').innerHTML='Hi, '+x+'! Welcome to my site!';
    				}
    				else{
    					document.getElementById('errorMsg').innerHTML='<font color="red">(required) Name:</font>';
    				}				
    			}
    		</script>
    	</head>
    	<body>		
    		<div class="main">
    			<div class="row1">
    				<img src="logo.jpg"/>
    			</div>
    			<div class="row2">
    				<div class="row2col1">
    					Navigation
    					<hr align="left" width=75%>						
    						<ul>
    							<li><a href="about.html">About Me</a></li>
    							<li><a href="http://www.google.com">Google</a></li>
    						</ul>
    				</div>
    				<div class="row2col2"><p class="welcome" id="greeting">
    				Hi! Welcome to my site!
    				<form>
    					<b id="errorMsg">Name:</b>
    					<input type="text" id="nameCheck" />
    					<input type="button" value="Click Me" onClick="clicked()" />
    				</form>
    				</p><p class="content" >This page is a work in progress that will eventually show places for data input, as well as data recall. Check back here for updates and more information! Thanks for visiting!</p>
    				</div>
    			</div>
    
    		</div>
    
    	</body>
    </html>
    
    

     

    [/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-9294″][vc_column_text] Help support my channel: http://www.patreon.com/tinkernut Follow Tinkernut! Google + Facebook Twitter [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]