Monitoring errors in php

After developing a system, the next thing that’s supposed to be done is testing it in the real world to make sure that it doesn’t have any problems. Good thing php shows errors whenever they occur on the script that you have written. But its not really good to show errors on a production environment that’s why we need to hide them and make use of the php error log to log the errors occurring in the system as the users are testing it.

Requirements

  • Wampserver / XAMPP
  • jQuery

 

Configuring php.ini

Lets start by configuring the php.ini file so that php won’t display any errors to the users. To do that, just left click on the Wampserver tray icon, select php, then php.ini. Open the file using a text-editor.
Then search for the string below:

display_errors = On

By default, it is set to On. Set it Off by changing the value to Off:

display_errors = Off

Next, search for error_log which has a path assigned to it. It may look like the one below:

error_log = "D:/wamp/logs/php_error.log"

Just change it to match the installation directory of wampserver in your computer. Then press ctrl+s on your keyboard to save the file.

Then click on restart all services from the wampserver tray icon. This is to make sure that the settings will take effect.

 

Monitoring errors

Now all we have to do is to write a script which will read the error log file and display the contents in the browser. Name it error_reader.php.

<script src="jq.js"></script> //import jquery file
<script>
$(function(){
	setInterval(logfile, 1500); //calls the logfile() function every 1500ms

	function logfile(){
		$('#errors').load('read_file.php'); //dynamically load the contents of read_file.php
	}
});
</script>
<div id="errors"></div> //this is where the contents of the error log are being displayed

Then create a new file and name it read_file.php.

<?php
//reads text file
$file = "D:\wamp\logs\php_error.log"; //path + filename of the php error log file
if(filesize($file) > 0){  //checks filesize; nothing is executed if filesize = 0
$handle = fopen($file , 'r');  //open a file
$data = fread($handle, filesize($file));  //reads a file
fclose($handle); //closes the file
?>
<pre> <!--preformatted text: text will be displayed in the same way as it appears on a text-editor-->
<?php echo $data; ?> <!--output file contents -->
</pre>
<?php } ?>

That’s it, open error_reader.php and start monitoring errors.

How to store and retrieve images from mysql database

In this tutorial I’m going to show you how you can store and retrieve images from mysql database. Remember that this is not always the best way to go if what you want to do is to be able to add image upload functionality to your website. You can always specify a folder in the web server to be used as the upload directory. And there are php functions which allows you to create directories in your web server in case your problem is categorizing the images into different folders.

Requirements

  • Wampserver
  • Text Editor

 

Creating the Table

First we need to create the table where we are going to store the images. If you already have researched on storing images on a database, you might already know that in order to store images, we need a special data type called blob. Therefore we need to specify the image field to be of type blob. At its simplest level, your table might look like this.

Field Data type
image_id int[PK][Auto-increment]
image blob

 

Storing the Image

Once you’ve built the table its time to write the script that will store the image into the database.

First, include your database configuration file:

require_once('image_config.php');

Open the image file using the fopen() function:

$file = fopen("switch.jpg", "rb");

Then use the fread() function to store all the necessary image information. The fread() function requires 2 arguments. The file resource, and the file size. The file size is easily obtained using the filesize() function. Just be sure to supply the correct argument, an image which actually exists on a specific location on your computer.

$image = fread($file, filesize('switch.jpg'));

Then use the fclose() function to close the file. This is to make sure that the image resource can’t be used later on.

fclose($file);

Next, use the base64_encode() function to encode the image into base 64. This is to make sure that the image won’t be truncated when you store it on the database. More like a file covering that makes sure that the file will be intact.

$image = base64_encode($img);

Lastly, perform a usual insert query to store the encoded image data into the database:

$db->query("INSERT INTO tbl_images SET image='$img'");

The data would look like this in phpmyadmin:

image

It has the word BLOB on it, together with the file size in KiloBytes. In the example above, the file size is 60KB. But the actual size of the image that I used is just 45 KB.

The file size increased because we used the base64_encode() function a while ago. Based from what I’ve read at PHP.Net, file size increases by 33% if you use base64_encode(). This is a down-side when compared to that of just storing the images in a folder in the web server.

Basically, your database will grow into a big monster which eats up lots of space if you use this method to store images into your database.

 

Retrieving the Image

Okay, were here at the most awaited part. The actual retrieval of the image that has been stored in the database.

First of all you need to specify the type of content that you want to display on the browser. This is the very first thing that should appear on the script which will output the images. Not even your database include, doctype or <html> tags will come first. Everything will crumble if the content type declaration doesn’t come first.

<?php

header("Content-Type: image/jpeg");

?>

Just to give you an example of what happens when you did not specify the content type at the upper most portion of the page:

image

Yep! All you will see is gibberish that a normal human person could not understand. Maybe not even the geeks who have reach geek nirvana is able to understand this.

Next, include your database configuration file.

Then retrieve a single row from the table:

$retrieve = $db->get_row("SELECT image

FROM tbl_images WHERE image_id = 2");

Lastly, do a one-liner code to output the image in the browser:

$image = imagejpeg(imagecreatefromstring(base64_decode($retrieve->image)));

Let’s break the code down:

  • base64_decode($retrieve->image) – what this does is to decode the image data. This simply converts the image back to its original form before it was uploaded.
  • imagecreatefromstring() base64_decode() returns the gibberish set of characters that I showed you a while ago. Those set of gibberish characters is used by the imagecreatefromstring() function to create an image
  • imagejpeg() this simply outputs the image file into the browser

Here’s a sample output:

image

 

Conclusion

That’s it! You’ve learned how to store image data into the mysql database. As I have said earlier, this method consumes much more space than just saving the uploaded images into a specified folder in the server. And this isn’t actually very nice, because when specifying the content type to be an image. All other contents like text will not be displayed. Only the image will be displayed.

Simple user management in php

I’m back after about 2 weeks of absence. This time I’m going to show you how to create a simple php program which allows you to manage the users of a particular system. And this includes the following:

  1. Roles
  2. Transactions
  3. User Registration
  4. User Privileges
  5. Implementing Privileges

 

Requirements

  • Wampserver – the usual software used by Windows users to easily install php, apache, and mysql
  • jQuery

 

Building the Database

First, we’ll go over with the basics of user management. First is the roles. Roles are a particular group of users with the same privileges on the system. An example of a role is the system administrator. The system administrator is able to do everything on the system. Another example of a role is the user. Or the ordinary people using your system. Each of the roles has different amount of privileges on the system. Privileges are the task or transactions that a specific role is able to do in a particular system.

Next, let’s build the database that we will be using.
First, we need a table which will store the different roles:

  • role_id – unique id for the role.
  • role_description – description or the role. Example: author, administrator

Next, is the table which will store the transactions or tasks which can be carried out by the different roles:

  • transaction_id  – unique id for the transaction
  • transaction – description for the transaction. Example: delete users
  • file location  – stores the filename and its location in the server. Example: user_registration.php

Also create another table which will associate a role with a specific transaction:

  • role_id – foreign key from the roles table
  • transaction_id foreign key from the transactions table
  • transaction_state  – state of the transaction. 1 if it can be done by the role, 0 if its not

Lastly, the user table. Where the user login information will be stored:

  • user id   – unique id for the user
  • password  – password used by the user to login
  • role_id foreign key from the roles table

Go ahead and build your database using phpmyadmin or any database management software which supports mysql.

 

Roles

Next, let’s create the form which allows us to create the roles. Roles as I have said earlier, is a group of users having the same privileges.

<form action="create_roles.php" method="post">
    <label for="role">Role:</label>
    <input  type="text" name="role" id="role" required/>
    <input type="submit"/>
</form>

Then the sql query which inserts the role into the database:

$create_role = $db->query("INSERT INTO tbl_roles

SET role_id='$role_id', role='$role', departmentID='$dept'");

 

Transactions

Next, let’s create the form which allows us to create transactions. Transactions are the links that the user sees in the navigation. Which means that whatever transactions are assigned to a role, those are the only links that will be seen by the user assigned with that role.

<form action="create_transaction.php" method="post"> <label for="trans">Transaction:</label> <input type="text" name="trans" id="trans" required/>

<label for="file_loc">File location:</label>

<input type="text" name="file_loc" id="file_loc" required/> <input type="submit"/> </form>

Then the sql query which inserts the transaction into the database:

$ctransaction = $db->query("INSERT INTO tbl_transactions SET

transactionID='$tid', transaction='$transaction',

file_location='$location'

departmentID='$dept_id'");

 

User Registration

Next is the user registration. This is where the role for the user is being selected. The rule is only one role per user. But its also possible to assign multiple roles to a single user. But we won’t be discussing it here.

<form action="user_registration.php" method="post"> <label for="user_id">User ID:</label> <input type="text" name="user_id" id="user_id" required /> <label for="password">Password:</label> <input type="password" name="password" id="password" required/> <label for="user_role">Role:</label> <input type="text" name="user_role" id="user_role" list="roles"

autocomplete="off" required> <datalist id="roles"> <?php $roles = $db->get_results("SELECT * FROM tbl_roles"); if(!empty($roles)){ foreach($roles as $k=>$v){ ?> <option value="<?php echo $v->role_id; ?>">

<?php echo $v->role; ?></option> <?php } ?> <?php } ?> </datalist> <input type="submit"/> </form>

Then the query. Don’t forget to encrypt the users password before saving it into the database. You can use common hashing methods like md5() and sha1(). To encrypt user passwords.

$reg_user = $db->query("INSERT INTO sys_users

SET UserID='$user_id', strPassword='$pword',

intRole='$role_id' ");

 

User Privileges

Next, is the designation of user privileges through roles. In this part, the system administrator will search for a specific role. Then a list of transactions will be displayed with a checkbox associated with it. If the checkbox is checked, the role can perform the transaction. If its not checked, then the role cannot perform the transaction. It’s like a switch which hides and shows the different links in the navigation depending on what is checked.

<?php $s_trans = $db->get_results("SELECT * FROM tbl_transactions"); if(!empty($s_trans)){ ?> <table border="1" id="dtable" class="display"> <thead> <tr> <th>Transaction</th> <th>Active</th> </tr> </thead> <tbody> <?php foreach($s_trans as $st){ ?> <tr> <td><?php echo $st->transaction; ?></td> <td><input type="checkbox" id="cbox" data-transid="<?php echo $st->transactionID; ?>" name="transtate[]" <?php if(stat_fetch($role_id, $st->transactionID) == 1){

echo 'checked'; }

?>></td> </tr> <?php } ?> <tbody> </table> <?php } ?>

As you can see from the above code, I used a little function called stat_fetch(). Which fetches the status of a specific transaction based on the selected role. The status is equal to 1 if it can be done by the role, and 0 if it cannot.

The function returns the transaction state, which is then used by the if statement to determine whether to put a check mark on the checkbox or not.

Oops, that’s only halfway through our user privileges. Next, we need to update the table which stores the role id, transaction id, and transaction state.

And we will make use of that file through jQuery. Since it’s a whole lot easier to perform ajax calls using jQuery rather than using pure Javascript. This code only executes when the user clicks on the checkbox. It then gets the transaction id and role id from the attributes that we set earlier on the checkbox. The data-transid attribute stores the transaction id, and the value attribute stores the role id.
Next, we checked if the checkboxes checked attribute is set to true. This simply means that were checking if the checkbox is checked or not. We then assign it to the variable cbox_st(short for checkbox state). Then lastly, we submit the role id, transaction id, and the checkbox state to a file called transactions_update.php.

$('#cbox').live('click', function(){    var trans_id = $(this).attr('data-transid');    var role_id = $('#roleid').val();

var cbox_st = 0; if($(this).attr('checked') == true){ cbox_st = 1; }else{ cbox_st = 0; } $.ajax({ type: "POST", url: "../ajax/transactions_update.php", data: "role_id=" + role_id + "&trans_id="

+ trans_id + "&state=" + cbox_st

}); });

Then here’s transaction_update.php, the file that is called by the jQuery ajax() function. Remember that we specified earlier, that the data is going to be submitted using the POST variable. That’s why we are getting the values through $_POST. What this does, is to check if the transaction id and role id already exist in the table which stores the transactions which can be performed by a role. If it exists, then we just perform an update to the transaction state. Transaction state is updated to hold a value of 1 or 0 depending upon the checkbox associated with the transaction. If its checked then the value is 1, if its not checked, then the value is updated to 0.

<?php require_once('db_config.php'); //database configuration $trans_id = $_POST['trans_id']; $state = $_POST['state']; $role_id = $_POST['role_id']; $checker = $db->query("SELECT * FROM def_transactions

WHERE roleID='$role_id' AND transactionID='$trans_id'"); if($checker > 0){ $role_up = $db->query("UPDATE def_transactions

SET transactionState='$state'

WHERE transactionID='$trans_id' AND roleID='$role_id'"); }else{ $role_create = $db->query("INSERT INTO def_transactions

SET transactionState='$state', roleID='$role_id',

transactionID='$trans_id'"); } ?>

 

Implementing Privileges

Lastly, we implement the privileges. This is where we control what links will be seen by the user on the navigation bar.

<?php $transactions = $db->query("SELECT file_location,

transaction FROM tbl_transactions LEFT JOIN def_transactions

ON tbl_transactions.transactionID = def_transactions.transactionID WHERE roleID='$role_id' AND transactionState = 1 ?>

<?php if(!empty($transactions){ ?> <?php foreach($transactions as $k=>$v){ ?> <a href="<?php echo $v->file_location; ?>">

<?php echo $v->transaction; ?>

</a> <?php } ?> <?php } ?>

That’s it in its simplest form. As you can see the code above just  loops through the transactions which is associated with the role id and has a transaction state of 1. It’s in a straight line. So your links will appear in one line. You might as well want to group the different transactions into a few main links to group each transactions. Of course, you will have to perform a few changes on your database to do that.

 

Conclusion

Yes, in case you haven’t figured out yet. This method only hides the links from the users. It doesn’t actually set what specific pages can be accessed by the users. It’s weakness is that the page can still be accessed if the user knows the actual URL of the page.
That’s it for this tutorial, see you next time! Thanks for reading!

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!