Directory

PHP and MySQL

 

Javascript and Jquery

 

CSS

 

HTML 5

 

Programming Practices

 

.Net Framework

 

Ruby on Rails

 

Java

 

PHP Frameworks

 

Troubleshooting

 

Software

 

Hardware

 

CMS

 

Security

 

Theme Customization

 

Resources

 

Anime

 

PSP Games

How to create a chat box using jquery and php

Yo! what’s up? It’s been 2  weeks since my last post so I ‘m going to try to make up for those 2 weeks that I haven’t posted anything on my blog.

In this tutorial I’m going to show you how to build a simple chat box using jQuery and php.

 

Requirements

 

Resources

I guess this is a new portion so let me introduce to you what resources is. Resources is where you can find the links to some of the sites that in one way or another has given me an idea on how to build something. In this case a chat box.

 

Procedure

First thing that you have to do is to create your working folder where you will put all the files for this mini-project.

Next, create the database where we are going to store the user information and messages.

Here’s the table structure for users:

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

And the table structure for the chat box:

CREATE TABLE IF NOT EXISTS `chat_box` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sender` varchar(30) NOT NULL,
  `sendto` varchar(30) NOT NULL,
  `message` varchar(140) NOT NULL,
  `date_sent` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=33 ;

You can use the table structures above. But you can also build your own if you want. Since what I’m showing you is very minimal. You might want to add up some fields and other tables as well.
You might also want to insert some data on the table for users using phpmyadmin or any database manager that you know. Since were not going to create a page where the users can register.

 

Next, create a page where the users can login.

<?php require_once('tutorials_config.php'); //database configuration file ?>

<!-—form—-> <form action="login.php" method="post"> <p> <label for="username">Username:</label> <input type="text" name="username" id="username"> <input type="submit" value="login"> </p> </form> <?php

//form processing if(!empty($_POST)){ $username = clean($_POST['username']); $exist = $db->query("SELECT username FROM users WHERE username='$username'"); if($exist == 1){ header('Location:test.php'); //redirect to chatbox page $_SESSION['user_logs'] = $username; //create a session for user }else{ header('Location:login.php'); //redirect to login page } } ?> <?php

//sanitize user input function clean($str){ return trim(mysql_real_escape_string($str)); } ?>

First, you have to include your database configuration file at the uppermost portion of your php file. Then create an html form. You might have notice that I only have a text field for the user id. You can also modify the code and add a password if you want. But as I have said earlier, I want to keep things as minimal and simple as possible. Please read the comments in the code to help you understand what it does.

If we have a login, we also need to have a logout.

<?php
session_destroy(); //destroy the session created from login page
header('Location:login.php'); //redirect to login page
?>

Again, this code is very minimal. It actually destroys the whole session. So if one person logs out, all the other people who is currently logged in will also be logged out. You can always improve this one if you like. That is by looping through all the users in the session and unsetting only the session for the user who wants to logout.

 

We’ve arrived at the point of interest. The chat box itself.
First, include the database configuration file. And check if a user session is already set:

<?php

require_once('tutorials_config.php');


if(empty($_SESSION['user_logs'])){ //check if user session is set
    header('Location:login.php'); //redirect to login page if user session is not set
}

?>

Next, include the files that you have downloaded earlier from the links in the requirements portion. The jquery file, jquery ui files, and the jquery chat box plugin files.

<link rel="stylesheet" href="ui-lightness.css" type="text/css" media="screen" />
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript" src="jq_ui.js"></script>    
<link type="text/css" href="jquery.ui.chatbox.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.ui.chatbox.js"></script>

After that, create the html form for the chat box.

First, the link to the logout page. And the hidden field where we are going to store the username. I always use hidden fields when I want to store php generated values which I want to access through javascript later on. I don’t know what tricks you are using to achieve the same thing. But that’s the one that I’m using.

<p>
<a href="logout.php">Logout <?php echo $_SESSION['user_logs']; ?></a>
</p>
<input type="hidden" id="username" value="<?php echo $_SESSION['user_logs']; ?>">

Next, also create a text field where the user can choose whom to send the message. I used an auto-suggest field to fetch the usernames from the database except the username of the user who is currently logged in. I have previously written an article discussing about datalist you can check it out if you don’t know how to use datalist yet. I also mentioned there that datalist doesn’t work for Chrome yet, and I have no idea when will they have it on Chrome. So use Firefox 5 or higher if you want to make this work. On the other hand, you can use jquery ui auto-suggest so that you can make it work on all browsers.

Also create a button which will call up the chat box.

<p>
	<label for="chatwith">Chat with:</label>
	<input type="text" name="chatwith" id="chatwith" list="otherusers">
	<datalist id="otherusers">
	<?php 
	$current_user = $_SESSION['user_logs'];
	$users = $db->get_results("SELECT username FROM users WHERE username != '$current_user'");	
	if(!empty($users)){
	?>
		<?php foreach($users as $v){ ?>
			<option value="<?php echo $v->username; ?>"><?php echo $v->username; ?></option>
		<?php } ?>
	<?php } ?>
	</datalist>
	</p>
	<input type="button" id="btn_chat" name="toggle" value="chat" />

Next create a div for the chat box. This is where all the conversations will show up.

<div id="chat_div">
</div>

Next, write the jquery code that will serve as the processor for all the stuff which we are going to do in the chat box. And that includes: selecting the receiver of the message, saving the message into the database, updating the contents of the chatbox so that the most recent messages will be previewed without refreshing the whole page.

First, let’s set what we want to do once the page loads.

$(function(){

$('#chat_div').hide();  setInterval(load_messages, 2500); var username = $.trim($('#username').val()); var box = null;

});

Here’s what the code above does:

  • $(function(){ .. });  – the built in jquery function which serves as an initializer. Its equivalent to the document.ready() function in javascript. Anything which goes inside it will get executed once the page loads
  • $(‘#chat_div’).hide(); – we hide the chat box div since the recent chat messages from the database will get loaded into the div which is not enclosed in the chat box
  • setInterval(load_messages, 2500); – we call the load_messages() function every 2500 milliseconds
  • var username = $.trim($(‘#username’).val()); – we store the username of the user
  • var box = null; – we set the value of the chat box to null ensure that it doesn’t store anything on page load

 

Next, we set what happens when the user clicks on the chat button. Remember that the user must first select another user to chat with before clicking on the chat button. But I guess I didn’t include the code that checks if the text field indeed contains a username which is stored in the database. So you might as well include that while you’re following this tutorial.

$("#btn_chat").click(function(event, ui) {
		  
      if(box){
         box.chatbox("option", "boxManager").toggleBox();
       }else{
       
          box = $("#chat_div").chatbox({id: username, user:{key : username}, title : "chat", 
                                                messageSent : function(id, user, msg){
													
	 $.post('send_message.php', {'username': username, 'sendto' : $.trim($('#chatwith').val()), 'message' : msg});
													
          $("#chat_div").chatbox("option", "boxManager").addMsg(id, msg);
                                                }});
              }
          });

Here’s what the code above does:

  • box.chatbox(“option”, “boxManager”).toggleBox(); – toggles the chat box. When the user clicks on the chat button for the first time the chat box shows up. And when the user clicks on it again, it hides.
  • box = $(“#chat_div”).chatbox(); – setting the options for the chat box.
      • id – the id of the user who currently uses the chat box
      • user – json string which stores the name of the current user
      • title – title of the chat box. In facebook the title is the name of the user you are chatting with
      • messageSent – what you want to do once the user sends the message(pressing enter). The function assigned to this variable has 3 return values. The id, user, and msg 
  • $.post(); – we call up a php script which inserts the message into the database. In the code above, we passed in 3 arguments: the sender, receiver, and message. Scroll down to the latter part of this tutorial to view the code for inserting the message into the database
  • $(“#chat_div”).chatbox(“option”, “boxManager”).addMsg(id, msg); – lastly we call up the addMsg() function which appends the name of the user and the message into the chat box

 

Next, write the function which calls up the php script which loads up the recent messages from the database. Scroll down to the latter part of this tutorial to view the code of the load_messages.php script. Remember that this is the function that we call from the setInterval() function so that it will be called up every 2500 milliseconds.

 function load_messages(){
	$('#chat_div').load('load_messages.php');
 }

Next, create a new php file and name it send_message.php. The code is pretty self-explanatory, it’s the one that we use to save the user information, message and current date into the database.

<?php
require_once('tutorials_config.php');

$username = clean($_POST['username']);
$sendto = clean($_POST['sendto']);
$message = clean($_POST['message']);
$date = date('Y-m-d');

$send_message = $db->query("INSERT INTO chat_box SET sender='$username', sendto='$sendto', message='$message', date_sent='$date'");
?>


<?php
function clean($str){
	return trim(mysql_real_escape_string($str));
}
?>

Next, create a new php file again and name it load_messages.php. This one is also self-explanatory, we just fetch the recent messages, and sender from the database. We only fetch the messages which has the same date as the current date.

<?php
require_once('tutorials_config.php');

$user = $_SESSION['user_logs'];
$date = date('Y-m-d');
$messages = $db->get_results("SELECT * FROM chat_box WHERE date_sent='$date' AND sendto='$user' OR sender='$user'");

if(!empty($messages)){
foreach($messages as $v){
?>


<b><?php echo $v->sender; ?> :</b> <?php echo $v->message; ?><br/>
	

<?php } ?>
<?php } ?>

 

Output
Here’s a sample output. Yep! that’s me talking to myself just to test if its really working. Of course, the auto-suggest didn’t work in Chrome, so I had to type the name manually.

image

 

Conclusion
I guess that’s it for this tutorial. You’ve learned how to create a very simple chat box using jquery and php. If you like this tutorial, please don’t forget to share it. Thanks for reading!

How to create a simple CRUD application using Mongo db and php

In this tutorial I’m going to show you how to create a simple crud application using Mongo DB and php. If you want to know how to install Mongo DB, visit the link below:

How to install Mongo DB on php

Configuration File
First you’re going to need to create a database configuration file which connects to your Mongo DB. Just like in MySQL, we also make use of a configuration file that we will just include on the files where we are going to need to query the database. This is to save time and avoid repeating of code.

<?php
$conn = new Mongo();
$db = $conn->test;
$collection = $db->people;
?>

Let me break down the code for you:

  • $conn = new Mongo()  – this initializes the Mongo DB class which contains all the methods which you can use to manipulate data in mongo DB through php.
  • $db = $conn->test – the default name for the Mongo database is test. This code is used for connecting to the database.
  • $collection = $db->people – collections are similar to tables in mysql. This code is used to reference the collection called people. But not unlike in mysql where you have to create the table first from the mysql console or a third-party database manager like phpmyadmin or heidi sql.
    In mongo DB you can basically use any collection name that you want, without having to create it.

 

Create
Now on to the exciting part, first let’s try inserting data into the database. Go ahead and create a form which the user can interact with. Don’t forget to include the database configuration file.

<?php
require_once('mongo_config.php');
?>
<form action="create_users.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name">
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes">
</p>
<p>
<input type="submit" value="Save">
</p>
</form>

Next, create the function that will check if all the values has been filled out. What the function does is to loop through the array of values that is being passed through it. But we have check first if the value is actually an array so that we don’t get any errors. If one or more values are empty, the function returns 1. If not then it returns its original value which is 0. We can then use that returned value to make a decision whether to continue the insertion of the record or not.

<?php
function check_empty($ar){
    $empty = 0;
    if(is_array($ar)){
        foreach($ar as $v){
            if(empty($v)){
              $empty = 1;
            }
        }
    }
return $empty;
}	
?>

Next is the code for inserting records.

<?php
if(!empty($_POST)){
	$people = $collection->find();
	$people_count = $people->count();
	
	$empty = check_empty($_POST);
	if($empty != 1){
		$id = $people_count + 1;
		$name = $_POST['name'];
		$age = $_POST['age'];
		$likes = $_POST['likes'];
		
		$person = array('id'=>$id, 'name'=>$name, 'age'=>$age, 'likes'=>$likes);
		
		$collection->insert($person);
		echo $name . ' is registered!';
	}else{
		echo 'Please fill out all the fields!';
	}
}
?>

  • if(!empty($_POST)) – First we checked if the $_POST superglobal is empty. This is the first step, because we don’t want to be executing all the code when the user access the page.
  • $people = $collection->find() – Call the find() method, this returns an array of all the records in the collection. Which if you still remember, the people collection as we have declared in the configuration file.
  • $people_count = $people->count() – Call the count() method, as the names suggests it just counts how many records are in the people collection. We then store that value into the $people_count variable.
  • $empty = check_empty($_POST) – Call the check_empty() function that we created earlier, and use the $_POST superglobal as an argument.

Next is just the assigning of the values from the submitted form to a php variable. Then place all those values in an aarray called $person. We then use the insert() function and supply the $person array as an argument. Nice and simple.

 

Read
Fetching the data is also dead simple. We only have to call the find() method and loop through it. Of course, we also need to use the count() method to check if there are actually records to fetch. We ditch the whole thing if the $people_count stores the value of 0.

<?php
require_once('mongo_config.php');


$people = $collection->find();
$people_count = $people->count();

echo $people_count . ' records found<br/>';

if($people_count > 0){
?>

<table border="1">
<thead>
	<tr>
		<th>ID</th>
		<th>Name</th>
		<th>Age</th>
		<th>Likes</th>
	</tr>
</thead>
<tbody>
	<?php foreach($people as $v){ ?>
	<tr>
		<td><a href="update_user.php?name=<?php echo $v['name']; ?>"><?php echo $v['id']; ?></a></td>
		<td><?php echo $v['name']; ?></td>
		<td><?php echo $v['age']; ?></td>
		<td><?php echo $v['likes']; ?></td>
	</tr>
	<?php } ?>
</tbody>
</table>
<?php } ?>

 

Update
Updating is also dead simple. We just make use of the findOne() function to fetch a single record from the collection. The argument that it will need is an array which contains the field name and its value. We already supplied the value in the link for updating. Were going to make use of the name as the query string(since the id that I supplied doesn’t work for me, grr. I guess the problem is the name id itself, you’ll have to use a different name if you want to make use of a custom id to reference the records).

<a href="update_user.php?name=<?php echo $v['name']; ?>">

Here’s the code(sorry for the poor indentation):

<?php
require_once('mongo_config.php');

if(!empty($_GET['name'])){
$name = $_GET['name'];
$query = array('name'=>$name);

$person = $collection->findOne($query);
$name = $person['name'];
$age =  $person['age'];
$likes =  $person['likes'];

?>
<form action="update_user.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>" readonly>
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age" value="<?php echo $age; ?>">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes" value="<?php echo $likes; ?>">
</p>
<p>
<input type="submit" value="Update">
</p>
</form>
<?php } ?>

Remember that $_GET is not a secure way of passing variables from one page to another. This is just for examples, don’t use it on any project(although personal projects may do, or any projects that will not be used by other people).

To update the record. First we check if any fields is empty, we don’t actually do a thing if one of the fields are empty. Assign the $_POST values to a variable. Call the findOne() method, using the name as the query string. Assign the new values, then commit to the database using the save() function.

<?php 
if(!empty($_POST)){
	$empty = check_empty($_POST);
	if($empty != 1){
	
	$name = $_POST['name'];
	$age = $_POST['age'];
	$likes = $_POST['likes'];
	
	$query = array('name'=>$name);
	$person = $collection->findOne($query);
	
	$person['age'] = $age;
	$person['likes'] = $likes;
	$collection->save($person);
	
	echo 'Update Successful!';
	}
}
?>

Note: we used the check_empty() function again. You might want to copy it on the file if you don’t want to get WHAT FUNCTION ARE YOU TALKING ABOUT errors.

 

Conclusion
That’s it for this tutorial. We have just touch the surface of using Mongo DB and php to create database oriented applications.
Yes I’ve said CRUD application, but I’m going to leave record deletion as your assignment. You just have to make use of the findOne() and the remove() function. Thanks for reading!

How to install Mongo db on php

In this tutorial I’m going to show you how you can install the  Mongo DB extension on php. But first, let me give you a simple introduction on what Mongo DB is. Mongo DB is a NO SQL database, which means Not Only Standard Query Language. Here’s a list of NO SQL databases:

http://nosql-database.org/

So what’s the advantage of Mongo DB over MySQL or other databases which uses SQL? Here’s the introduction of Mongo DB:

http://www.mongodb.org/display/DOCS/Introduction

And here’s a summary in case you’re feeling lazy today:

  • Document-oriented
  • High Performance
  • High availability
  • Easy Scalability
  • Rich query Language

Well, I’m not that expert at explaining things. And the main purpose of this article is to show you how to install Mongo DB, so I guess a simple outline will do. And yeah, you’re lazy today so you won’t really be reading this part and have gone ahead with the installation.

 

Requirements

 

Installation

First, you’ll have to go to the download page of the Mongo DB. And you’ll see a highly confusing table, you’ll really have to examine it carefully in order to download the right one. Basically you’ll want a production release that is for Windows 32-bit operating system. It says Windows 32-bit, but I don’t really know if it works on Windows 95 or the first version of Windows. But if you are on Windows 7 just like me, the it will probably work for you.

image

Next, download the mongo DB extension for php. You can use this link to download the php extension if you didn’t catch the link above. But first, you need to make sure that we have the same php version and compiler. If not then you can use this link, a collection of mongo DB extensions for php 5.3.5. And if you don’t know how to get the information below, just create a new php file and type phpinfo(), save it then access the file on your browser.

image

Next, extract the mongo DB archive file. Then go to the bin folder. What you’ll see is a bunch of executable files, but you only have to execute 2 of them. Here’s the order of execution:

  1. mongod
  2. mongo

You can go ahead and try some commands like:

db.people.save({name: 'ash'});

It’s the equivalent of the insert command in sql.

If you want to verify that it is actually stored in the database, you can try out this command:

db.people.findOne({name: 'ash'});

Yup!, that’s the equivalent of the select statement in sql.

Ok, enough with that. You can go give yourself a jumpstart by taking up the tutorial in the mongo DB site, just click on the big TRY IT OUT LINK to get started.

Next, paste the mongo DB extension to the ext folder in php. The path to my ext folder looks something like the one below. You can make use of it as a basis.

D:\wamp\bin\php\php5.3.5\ext

Next, you have to insert this line on the php.ini file. Of course, you don’t paste it on just anywhere else. You have to paste it where the other extensions are

extension=php_mongo.dll

I have placed mine as the first extension on the list, the one’s with the semi-colon at the beginning are disabled. You can also enable and disable existing extensions from the wampserver tray icon. But because the mongo DB extension doesn’t yet exist, we needed to manually place it on the php.ini file:

image

After that, save the changes to you php.ini file and restart all services from the wampserver tray icon.

To test if you can already make use of Mongo DB in php, just create a new php file and paste this line:

$conn = new Mongo();

If you don’t get any error, then All Izz Well as Phunsuk Wangdu said(that’s from the movie called 3 idiots, definitely worth watching, very funny and inspiring).

But if you get any errors, here’s what you need to do:

  • Make sure that mongo.exe and mongod.exe are running, you can go check it out from the Windows Task Manager.
  • Make sure that you have the right mongo DB php extension and that it is enabled.

 

Conclusion
That’s it for this tutorial! Mongo DB is a good My SQL alternative for small php projects. Next time, were going to make a simple CRUD application using php and mongo DB.

Things to do before you present your php project

In this article I’m going to share to you some of the things that you need to check before you present your php project. Some of these things often get left out and actually stays unpatched. Yup! I’m talking about errors here. Errors which only shows up accidentally. Errors which can only appear by letting an idiot or a monkey use your system. Yes, systems are made for humans but sometimes you need to act like a monkey in order to uncover the errors.

 

String Sanitization
Sanitizing your string is number one on this list folks. Most of the web applications today uses databases to store and retrieve data. And to store and retrieve data, we use SQL or the Standard Query Language. And SQL only allows certain keywords, you actually get an error if you don’t comply with the syntax just like with any programming language.
So where does string sanitization enter from here? Here’s an example query to let you understand where will we need string sanitization, try to run it if you don’t know the output yet:

SELECT * FROM def_transactions WHERE transactionID='''

That’s just the query, in php it looks like this:

<?php
$transaction_id = $_POST['trans_id'];
$db->query("SELECT * FROM def_transactions WHERE transactionID='$transaction_id');
?>

You can conclude now that the same SQL error will pop out if someone inputs a single quote on the transaction id field. Go ahead and try it.

So how do we sanitize the string?The simplest way to sanitize a string is already built-in to php. The mysql_real_escape_string() function. You use it this way:

<?php
$transaction_id = mysql_real_escape_string($_POST['trans_id']);
$db->query("SELECT * FROM def_transactions WHERE transactionID='$transaction_id');
?>

The error won’t bother you again. What mysql_real_escape_string() does is to escape all the characters which are invalid in SQL. You might say that it’s an addslashes() on steroids.

 

Empty Results
Second on the list is empty results. Its crucial to check if the query that you’re trying to call actually returns any result set. You’re asking for trouble if you don’t perform checks. Consider the following example:

<?php

$name = $_POST[‘name’]; $results = $db->get_results("SELECT * FROM tbl_people WHERE name LIKE ‘%$name%’"); foreach($results as $r){ echo $r->name.'<br/>'; } ?>

So what’s wrong with the code above? Aside from the fact that we didn’t perform sanitization. You might also noticed that we’ve gone ahead and loop through the results without even checking if there are any results at all. The code returns an error which tells you that the argument passed to the foreach loop is invalid. To fix the code we change it to the one below.

<?php$name = $_POST[‘name’];
$results = $db->get_results("SELECT * FROM tbl_people WHERE name LIKE ‘%$name%’");
    if(!empty($results)){
        foreach($results as $r){
            echo $r->name.'<br/>';
        }
    }
?>

 

Thorough Checking
Before you present any application you must thoroughly check that its working fine and that errors doesn’t show up here and there. But test your application in such a way that errors will actually show up. Here’s how:

  • Input all sorts of crazy stuff, symbols, and other unnecessary characters on the text fields.
  • Test all the possibilities, not just one. For example, if you have a function that returns either true or false based on the value of the argument that is passed to it, then test it in such a way that you see true and false. Don’t conclude that its working 100% if you’ve only seen one side of the coin.
  • Examine your application. If you see something that you think isn’t user friendly, something that you think might cause some errors in the future, or a text field which shouldn’t take a specific data type. Then take note of it and change it if you have enough time. Don’t push lots of changes overnight if you think you can’t make it.
  • Make sure that the flow of the program is correct.
  • Let others use your application. And ask them for suggestions or if they’ve seen any errors.

 

Turn Off Error Reporting
This might be your last option. Turning off error reporting is not advisable if you’re still in the process of testing your application. But if you don’t want anyone to be seeing errors while your presenting your application this is your best bet. To turn off error reporting just uncomment the production values just like the one below, you can use the find tool to quickly jump to the lines below:

; display_errors
;   Default Value: On
;   Development Value: On
    Production Value: Off

; display_startup_errors
;   Default Value: Off
;   Development Value: On
    Production Value: Off

; error_reporting
;   Default Value: E_ALL & ~E_NOTICE
;   Development Value: E_ALL | E_STRICT
    Production Value: E_ALL & ~E_DEPRECATED

; html_errors
;   Default Value: On
;   Development Value: On
    Production value: Off

Here’s a sample code that will issue an error if the default values for error reporting are being used:

<?php
echo $a;
?>

Here’s what you usually get if you run the code above:
image

And here’s what you get if you uncomment the production values for error reporting:

image

Awesome, but I only recommend this one as  a last resort. Be careful to comment out the production values after your presentation as this might give you the illusion that there is nothing wrong with your program.

 

Conclusion
I guess that’s it! You’ve learned some of the things that you should do before presenting your php application. These tips might also apply to other programming project not just in php. I hope you enjoyed reading!

How to solve router disconnection problems

Yep! I know why you’re here, you’re  router always disconnects when you’re doing something really important. Like downloading anime or streaming a youtube video.
In this quick tutorial I’m going to show you how to solve the problem.

 

Reboot the router
You can always reboot the router if it suddenly disconnects. To do that, just access your router from the browser by going to http://192.168.1.1/  or http://192.168.0.1
Its not always those two, a little googling will help if you cannot access anything from the addresses that I gave you.
To reboot your router, just go to system tools then select reboot. Click the reboot button if there is any. If the reboot is successful, you’ll be once again connected to the rest of the world.

 

Reboot the modem
If the first one didn’t do the trick. Then maybe the router isn’t the problem. Just try to reboot the modem if the problem still persist. To do that just open up the cmd. And type the following to release your current ip address:

ipconfig/release

Then renew it:

ipconfig/renew

 

Remove the plug
If all else fails, perhaps its now time to remove the plug for about 3 minutes then put it back again. In short a physical reboot.

 

Conclusion
Ok that’s it. The solutions that I have shared to you are not long-term solutions, the problem might still persist in the future.

Programming practices

When developing an application, especially a huge one that may take several months to finish. We tend to develop some practices and techniques that we use all throughout the development process. Some are bad, some are good. In this article, I’m going to share to you the practices that I have developed so far. Its up to you to classify if it’s a good or a bad practice.

Code Comments
Using comments to indicate where a block ends.

if(){
    do(){

   }//end of do while
}//end of if

 

Table Truncation
Writing a separate script for truncating the tables that are affected by the current program that I’m testing. That is to easily work on a clean slate if the program didn’t work correctly. Which in turn messes up the table. What I do is to open the file in the browser, then refresh the page if anything goes wrong to start with a clean table.

 

Fresh Air
Breathing air from the outside environment is very effective in solving a programming problem. If you’re stuck with a problem for more than an hour already and you believe that you could have done it in just 5 minutes, then its better to get out of chair, go outside and breath some fresh air. 80% of the time you will come up with a solution, believe me.

 

 Firebug + console.log()
Using debugging tools like Firebug when developing applications to reduce the time spent on debugging. And using console.log to output things on the console. Perhaps most of us uses the alert() function. That’s very time consuming especially if you have to output lots, you also have to click on the OK button lots of times. And there are also other things that you cannot output using the alert() function.

 

Testing Folder
Also called the testing area. This is where I put files which are intended for testing code. If I’m not sure with the code that I’m writing. Or if I want to test out some other things which are not directly connected to the application that I’m working on, I put them all to the testing folder. To isolate things and to give myself the feeling that I’m working in a smaller file, with lesser code in it. Its not really easy to work on a file that has already lots of code in it.

 

Taking Notes
Taking down notes, making sketches in a scrap paper if you can’t directly write the code on your computer. It’s also a good place to write an algorithm. One of the most useful apps for note taking is Evernote. I definitely recommend it.

 

Breaking Down
Breaking down the procedural code into their respective functions. Makes it easier to copy those code into a larger file later on. But before you can break down something, make sure that you have already the working procedural code where you will base things.

function get_monthsDelayed(){

}

function get_surcharge(){


}

 

Database Backup
Always see to it that you are backing up the database that your application is using. Especially if you are the kind of person who is making modifications in the database structure while creating the application. Its always wise to have backups of the previous version of your database.

 

Code Snippets
Storing codes that you often used in a program like Snippley to save time. Retyping the same code over and over again isn’t time efficient, especially if you are to meet deadlines.

Naming Conventions
As we type more code, develop more applications. We also tend to come up with our own naming conventions. For naming files, databases, tables, fields, classes, functions, and variables. Just be sure that the names that you give to each of those are comprehensive. You can check out this post from stackoverflow if you want to learn the best practices for naming conventions:

http://stackoverflow.com/questions/332831/best-practices-for-naming-conventions

Just make sure that you maintain the naming convention of your choice throughout a project. Be consistent.

 

Folder Structure
When developing applications make sure that you properly organize different files. Here’s an example of a folder structure:

image

Here’s a summary of the folder structure that I’m using:

  • First, make individual folders for each file types. That would be .php, .css, .js
  • If using an external library, frameworks or javascript plugins place them on a separate folder. To distinguish which file belongs to what library.
  • If the application comprises of modules, also separate the files that belong to each module. That is by creating a separate folder for each module. Common files for each module can be placed outside of the folder.
  • If using files which processes data in the background, also create a separate folder for them. You may want to further group those files using folders or by just using a naming convention to distinguish which module uses which file.

 


Screenshots
Taking screenshots  to compare outputs. When saving data into the database and you want to verify that what you have inputted is actually going to the right place, then you can use tools like Snipping Tool. A built-in Screenshot tool for Windows 7.

 

Google
We don’t know everything. No matter how good you are there will always be a time that you’ll need to consult Google. If it is a specific code that you’re looking for, its always nice to study it first. Study what the code does, and how it work. Don’t just copy and paste. You won’t learn anything from that.

 

Give yourself a break
No matter how passionate you are there are always times when you feel like you have lost all energy to continue working on your project. That’s why its also important to have a break. Watch some movies, listen to relaxing music, play some games, or watch anime. Once you come back,  you’ll feel that you’ve been energized and you’ll actually want to work on your project as soon as possible.

 

Conclusion
There you go. As I’ve said earlier, its up for you to decide if what I’ve tackled here are good or bad practices. And as I have said in the disclaimer, I’m not in any way expert in this field. I’m still just learning just like the rest of us.
Feel free to use the comments section if you have anything to share or to ask. Thanks!

How to store and retrieve special characters on mysql database

In this quick tutorial I’m going to show you how to save special characters in a mysql database. Which we will later on try to retrieve.

First, setup a testing folder then create a new php file. Also include your database configuration file on the new file that you created.

Next, copy the following code into your file. Make sure to change ‘specialchars.php’ to the name of the file that you are using:

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

The text field with the name of ‘specar’ is the text field where we are going to paste the special character.

image

Then the code which will process, save, and retrieve the special character:

<?php
if(!empty($_POST)){
$id = htmlentities($_POST['x']);
$unique_key = substr(md5(time()), 0, 5);
$create = $db->query("INSERT INTO sys_users SET UserID='$unique_key', strPassword='$id'");

$selector = $db->get_var("SELECT strPassword FROM sys_users WHERE UserID='$unique_key'");
echo html_entity_decode($selector);
}
?>

Yup, the table that I’m using is not in any way related to the data that were trying to store. But don’t mind that. You’re here to learn something on saving and retrieving special characters.

So what we did in the code is to first check whether we have any post data to process. So our script only executes if something is actually submitted to the server. Then we used a function called htmlentities. What it does is to convert a special character into an html entity. An html entity is basically a representation of a special character in terms of html.

 

Why convert?
We need to convert a special character into an html entity because you might run into problems later on if you store these kinds of characters as it is. I haven’t dug so much as to what problems might occur. Querying those values later on might produce some unexpected errors. Like an error in your sql query.

And yes, without using htmlentities. It works fine:

<?php
if(!empty($_POST)){
$id = $_POST['x'];
$unique_key = substr(md5(time()), 0, 5);
$create = $db->query("INSERT INTO sys_users SET UserID='$unique_key', strPassword='$id'");

$selector = $db->get_var("SELECT strPassword FROM sys_users WHERE UserID='$unique_key'");
echo $selector;
}
?>

 

Decoding
After saving the htmlentity to the database, we then retrieve it using the unique key that we assigned earlier. The unique key is pretty much very unique in the sense that it uses the unix timestamp as the primary source of data, then it encrypted it using the md5() function. Then we reduce the whole string into just 5 characters by using the substr() function.

To decode the html entity that was saved on the database, we used a function called html_entity_decode. And it does pretty much what its name says it does. It only requires a single argument which is the actual html entity to be decoded.

 

Conclusion
That’s pretty much what I have for this tutorial. To add a bit of security, you might want to include this function. And just call it whenever you feel like a character that you’re trying to save might ruin your query.

function clean($str){
    return trim(mysql_real_escape_string($str));
}

How to use phpmyadmin to secure mysql database

Its been a while since I’ve wrote a full fledged blog. I should really be writing 2 to 3 articles in order to make up. But making sure to make it a quality post. Since my blog has really been stagnating. I only get a minimum of 93 views each day and a maximum of 383 views each day. Haven’t got any higher amount of views.

So enough with the little blabber. Let’s get to the main point of this article. This time I’m going to show you how you can use phpmyadmin to configure your mysql database to have more security.

I know that most of us, especially the beginners often use the root account when developing web applications. Its actually fine to use the root account when in a development environment. But once you deploy the application, it would be wise to create another account that has privileges which are only applicable to the actions that the users are going to perform.

Go ahead and launch Wampserver and access phpmyadmin on your browser. Yes, its totally fine to use IE here but I don’t really recommend it. As you can see from the screenshot below, the root user has actually all the privileges. Pretty much every feature, functionality that is embedded in the mysql database can be performed and used by this user. If you examine the screenshot further, you will notice that the configuration is not in any way secure. Passwords hasn’t been setup for most of the accounts, only the root account accessing from the localhost has a password.

image


Creating a new user

To address the issue, we have to create a new user. And limit its privileges.
The first section is the login information. Here we define the username, password, and the host. The host is pretty much the location of the user or the access point. It might be local, any, or specified host. Localhost means, the user is accessing the database from the computer where it is installed.

image

 

Assigning Database

Next, is the database for the user. You can pretty much ditch this one and just select none. But doesn’t mean that if you select none, the user won’t actually have any database to play with.

image

 

Setting up privileges

Now, for the privileges. Most of the options are self-explanatory. But we’ll go ahead and try the most obvious ones. Under the data group box. Just check the select checkbox and then click go.

image

 

Database configuration file

And then go ahead and write a database configuration file:

<?php
include('ez_sql/shared/ez_sql_core.php');
include('ez_sql/mysql/ez_sql_mysql.php');

$db = new ezSQL_mysql('reader', '1234', 'orgbpls', 'localhost');
?>

I’m using a php library called ezsql for manipulating databases. Just make use of the usual way of how you connect to mysql database if you don’t  use the same library as I am.

 

Selector file

Next, create a testing folder, then create a new php file called selector.php. Which will contain the following code:

<?php
require_once('reader_config.php');

$select = $db->get_results("SELECT * FROM sys_users");

if(!empty($select)){
?>
<table border="1">
<thead>
	<tr>
		<th>User</th>
		<th>Password</th>
	</tr>
</thead>
<tbody>
	<?php foreach($select as $s){ ?>
	<tr>
		<td><?php echo $s->UserID; ?></td>
		<td><?php echo $s->strPassword; ?></td>
	</tr>
	<?php } ?>
</tbody>
</table>
<?php } ?>

In the above code, we just did a normal select query. Which yields us the following output:

image

Yup the hashed passwords are pretty much the same. Since I used 1234 on all of them. But I’m telling you not to use that dumb password once you’re going to deploy your application. Better yet generate a strong random password if you can’t think of anything secure.

As you can see, the query executed without problems. That’s because we checked the select action a while ago.

Updater file

This time, create another file called updater.php. And yes, were going to perform an update query using this file.

<?php
require_once('reader_config.php');
$db->query("UPDATE sys_users SET strPassword='1234' WHERE UserID='badmin'");
?>

Go ahead, and access that php file in your browser. And see what happens:

image

It issues an error saying that update command is denied to the user. I can’t think of anything that  an attacker could do if this is the case. Since the user that’s been set to manipulate the database doesn’t have enough privileges to perform the action.

 

Other settings

There are more settings that you can check out and play around with. One of those is the resource limits. Which lets you setup the maximum number of queries that can be performed on an hourly basis, and other interesting stuff.

image

There’s also the structure settings. Most of the time, you can uncheck these guys if the users are just going to perform CRUD operations on the database. These are pretty much admin stuff.

image

 

Conclusion

You have learned how to setup user privileges using phpmyadmin. Making applications secure is a must for developers. Even if you think there might be no hackers that might try to hack your system. Its still important to protect the system that you have created.

Web Development Resources September 17, 2011

Time for another roundup. I don’t really track what links I’m posting here so a few things might get repeated. Especially now that this is the third time that I’m gonna be doing this. So here’s a bunch of links that you might want to check out:

 

Uni-Form
As the name implies it makes form creation easier.

Form validation hints
A tutorial showing you how to create nice looking validation hints.

Ql.aonic.net
Quick lookup for php, mysql, js, and css stuff. Yeah pretty much like a search-engine.

Spurapp.com
A web-application for checking if your site conforms with design basics.

Use google+ to improve your UI
If you want to use the same UI Elements that are used in Google+. Then you can try this one. They also have some of the UI elements inspired by OS X Lion.

Date.js
Awesome Javascript library for formatting date and time.

JS Bin
If you want to experiment on some Javascript code, this is the way to go. You can also include some of the most popular Javascript Libraries. Like Mootools, Jquery, Prototype, and YUI.

jVal
Yet another Jquery form validation plugin.

Jquery Easing
A jquery plugin for performing animations.

Jquery Animations
A beginner tutorial showing you how to perform animations in jquery.

Php js
Php functions ported to Javascript.