A Web Design Blog


Wednesday, July 2, 2014

Image filtering these days are all over the web. It all got hot when Instagram started it. So in today's post we will be dealing with how to create those image filter effects using PHP and trust me they are really simple.

CSS also got a property called filter that could do the same job but the biggest problem with that is Cross Browser Compatibility. Chrome 18.0+ and Safari 6.0+ and Opera 15.0+ support them completely. Its difficult to implement in Firefox and the so called browser from Microsoft doesn't support that as usual.

So there is a PHP solution which could help you out. This is using the PHP GD library. Lets get started and see on how to do this thing. Your first job would be to install the PHP GD library. It usually comes along with PHP and is pre installed and enabled in most cases. If not you could find the install instructions here. To check if it is already  enabled or to enable it follow the steps below :

1. Open up your php.ini file.
2. Find the following line.
extension=php_gd2.dll
3. If this line is prefixed with a semicolon then remove it. If not its already enabled and you are good to go.

In this example we will be dealing with JPG images. But you could use other formats including gif, png and even bmp. You just need to change the parts which says jpeg from the code that we are dealing with, with the name of the extension that you wanna use. So lets get started.

Black And White Filter :

Technically its called grayscale. So varying your grayscale-ness would increase and decrease your black and white intensity accordingly. The following code would produce a complete black and white effect to the image.
<?php
$image = imagecreatefromjpeg('me.jpg');
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagejpeg($image, 'output.jpg');
imagedestroy($image);
?>
1. In the first line of code we say $image = imageccreatefromjpeg(‘me.jpg’) and in this line we are simply creating a image stream with the image specified as the argument. This is image that we would convert.

2. In the second line of the code where we say imagefilter($image, IMG_FILTER_GRAYSCALE); we are just applying the filter, in this case a black and white effect, to the image stream that is mentioned as the first argument.

3. And in the third line of the code where we say imagejpeg($image, ‘output.jpg’) we are just writing the image stream which we just modified into a new file named output.jpg which php would create.

4. Finally in the fourth line where we say imagedestroy($image); we are just shutting down the image stream and cleaning that.

And similarly if you wanna apply the filter to a png file then you need to modify the code to look like the following :
<?php
$image = imagecreatefrompng('me.png');
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagepng($image, ‘output.png');
imagedestroy($image);
?>
So you are just applying the filter to a png file and you are just outputting it as a png file as well.

Brightness Filter :

And lets just discuss another example and in this case we will be increasing the brightness of the image. The following code would do your job.
<?php
$image = imagecreatefromjpeg('me.jpg');
imagefilter($image, IMG_FILTER_BRIGHTNESS, 100);
imagejpeg($image, 'output.jpg');
imagedestroy($image);
?>
The only change in this code compared to the code above is the third line where are say imagefilter($image, IMG_FILTER_BRIGHTNESS, 100); You could notice that we changed the second parameter so that it asks the compiler to change the brightness and not into a black and white image and as a third parameter we just specify the amount of brightness that we would want. You could use positive values to increase the brightness and negative values to decrease the brightness.

Okay. So like these two examples you could use a wide range of fitlers available. The following are the available ones.

IMG_FILTER_NEGATE - Reverses all colors of the image.
IMG_FILTER_GRAYSCALE - Converts the image into grayscale.
IMG_FILTER_BRIGHTNESS - Changes brightness of the image  (Takes one more argument)
IMG_FILTER_CONTRAST - Changes the contrast of the image (Takes one more argument)
IMG_FILTER_COLORIZE - Like IMG_FILTER_GRAYSCALE, except you can specify the color.
IMG_FILTER_EDGEDETECT - Uses edge detection to highlight the edges of the image.
IMG_FILTER_EMBOSS - Embosses the image.
IMG_FILTER_GAUSSIAN_BLUR - Blurs the image using Gaussian method.
IMG_FILTER_SELECTIVE_BLUR - Blurs the image.
IMG_FILTER_MEAN_REMOVAL - Uses mean removal to achieve a sketchy effect.
IMG_FILTER_SMOOTH - Makes the image smoothy (Takes one more argument)
IMG_FILTER_PIXELATE - Applies pixelation effect to the image (Takes two more arguments)

You can find the complete guide to use these effects from this PHP manual. So you could try out your own image filter effects. Happy coding :)

Thursday, June 26, 2014

Hey there ! Used Pinterest and love that fluid image layout ? Well you could easily create a similar layout with Bootstrap. In this post we would be creating an image layout similar to the one in Pinterest and we would be doing this with Bootstrap and Picturebox (a jQuery Lightbox plugin). The output that we create would be completely responsive and fluid. So alright lets dive into the topic. 


Prerequisites :

Getting Started with The Code :

Ok so lets get started with the code. Create a folder on your desktop and open it up. Copy the Bootstrap.css file that you just downloaded into this folder. And also paste folders images and includes that was present in the Picturebox plugin that you just downloaded. Now just create a couple of files in the folder and name it as index.html and another one as pinterest.css. Keep the pinterest.css file in your includes folder. We would first be dealing with the index.html file. So open it up and type in the following code and this would link the script files and the css files that we would be using.

<link rel = "stylesheet" href = "bootstrap.css">
<link rel = "stylesheet" href = "includes/picturebox.css">
<script src = "includes/jquery.js"></script>
<script src = "includes/picturebox.js"></script>
We would be using Bootstrap's grid system in this project. You might be familiar with that but still its worth explaining. Bootstrap's grid system divides the entire width of your browser into 12 columns which would arrange itself depending on the width of the window. To make use of the Bootstrap grid just create a class called container which would be the grand parent class and a class named rows which would be the parent class. We would be creating four child columns each with a class col-md-3 and the 3 here implies that we are combining 3 of those 12 columns and making that into a single column. And so we would now have 4 columns and each of them would be a combination of 3 columns which we spoke about early. So below is the code that would create what we spoke now.
<div class = "container">
<div class = "row">
<div class = "col-md-3"></div>
<div class = "col-md-3"></div>
<div class = "col-md-3"></div>
<div class = "col-md-3"></div>
</div>
</div>
Now lets fill these columns with images. The first child div corresponds to the first column of images, the second child div the second column of images and so on. So lets fill it up and the end code would look something like below.
<div class = "container">
<div class = "row">
<div class = "col-md-3">
<img src = "images/1.jpg">
<img src = "images/2.jpg">
<img src = "images/3.jpg">
<img src = "images/4.jpg">
</div>
<div class = "col-md-3">
<img src = "images/5.jpg">
<img src = "images/6.jpg">
<img src = "images/7.jpg">
<img src = "images/8.jpg">
<img src = "images/9.jpg">
<img src = "images/10.jpg">
</div>
<div class = "col-md-3">
<img src = "images/11.jpg">
<img src = "images/12.jpg">
<img src = "images/13.jpg">
<img src = "images/14.jpg">
</div>
<div class = "col-md-3">
<img src = "images/16.jpg">
<img src = "images/17.jpg">
<img src = "images/18.jpg">
<img src = "images/19.jpg">
<img src = "images/20.jpg">
<img src = "images/15.jpg">
</div>
</div>
</div>
And so the final task we need to do with the index.html file is integrating this with the Picturebox plugin. To do that cover the image tags with a div of class lightbox. That's it. Its really so simple to integrate the Picturebox plugin. The entire index.html file would look like the following :

index.html file : 
<link rel = "stylesheet" href = "includes/bootstrap.css">
<link rel = "stylesheet" href = "includes/picturebox.css">
<script src = "includes/jquery.js"></script>
<script src = "includes/picturebox.js"></script>
<title>Pinterest Style Image Gallery</title>
<div class = "container imggrid">
<div class = "row">
<div class = "col-md-3">
<div class = "lightbox">
<img src = "images/1.jpg">
<img src = "images/2.jpg">
<img src = "images/3.jpg">
<img src = "images/4.jpg">
</div>
</div>
<div class = "col-md-3">
<div class = "lightbox">
<img src = "images/5.jpg">
<img src = "images/6.jpg">
<img src = "images/7.jpg">
<img src = "images/8.jpg">
<img src = "images/9.jpg">
<img src = "images/10.jpg">
</div>
</div>
<div class = "col-md-3">
<div class = "lightbox">
<img src = "images/11.jpg">
<img src = "images/12.jpg">
<img src = "images/13.jpg">
<img src = "images/14.jpg">
</div>
</div>
<div class = "col-md-3">
<div class = "lightbox">
<img src = "images/16.jpg">
<img src = "images/17.jpg">
<img src = "images/18.jpg">
<img src = "images/19.jpg">
<img src = "images/20.jpg">
<img src = "images/15.jpg">
</div>
</div>
</div>
</div>
</body>
You could see that we have added an extra class to the div with the class container called imggrid. So the entire index.html file is now done. Lets now add some code the pinterest.css file and lets complete the task. Add the following code to the css file.

body {
  background-color: #0072c5;
  color: #fff;
  font-family: Lato;
  font-weight: 700;
  font-size: 50px;
}
.imggrid img {
  width: 100%;
  margin-bottom: 15px;
}
 So its all done now and your Pinterest style image layout is now ready ! Just open up the index.html file in the browser and you could see the awesome Pinterest style image layout in your browser ! Try resizing your browser and take a look at the responsiveness of the layout. Good looking right ? And you can download the source code or see the live demo below.


I used the following book to learn Twitter Bootstrap and its really awesome. Wanna know more about Bootstrap ? Then make sure you check out the following book.

 Live Demo
 Download Source Code




So leave your doubts if any in the comments section. Happy designing :)

Wednesday, June 25, 2014

Just created your node application and dont know what to do with that further ? Well your application would be of no use to others if you are not gonna host it online somewhere. But hosting a node js application is kinda different compared to hosting your PHP application. You just dont have any file manager that would let you upload your node js and you could not run it. It doesn't work that way. So how do you do it ? We would be dealing the exact same thing in this post on how to host your Node JS application online.


We would be using IBM Bluemix to host your node js application. IBM Bluemix is a cloud hosting platform that lets you to host your applications online. It accepts loads of different languages including even PHP. You could upload your PHP application too. But still, this is in beta as of now and it is free unless it is beta. Maybe they would have a free plan to go with, including loads of limitations. So now lets see on how you would host your Node application online using IBM Bluemix.

Hosting your First Node JS Application :

1. Head over to this link and join the free beta. Sign up for it and move on to your dashboard.

2. The next thing that you would need to do is to download and install the cloud foundry tool that is a command line tool for IBM Bluemix. You could get that from this GitHub link. Scroll down to the downloads section.

For Windows users just copy the downloaded file which would be name cf to your system32 folder so that the command could be accessed via the command prompt.

For Ubuntu users I hope that tool is available via the Ubuntu Software Centre. 

3. Now that you have downloaded and installed the Cloud Foundry tool open up your Terminal and type in the following command so that the api gets set.

cf api https://api.mybluemix.net/

I hope that it would already be set for Windows users but still there is no harm in running the above code.

4. Make a copy of your Node application folder and open it up. You need to create a file named manifest.yml in your root (make note of the extension). And open it up in your text editor and type in the following in it.
---
applications:
- name: NAME OF YOUR APPLICATION HERE
  memory: 256M
  instances: 1
  host: YOUR PREFERRED HOST
  command: COMMAND YOU NEED TO RUN TO START THE APPLICATION
Make sure that you replace the things written in caps. Name of your application MUST match the name of the folder in which your Node application resides.

YOUR PREFERRED HOST - This is where your Node application would reside online. If you enter in xproweb then your application would be hosted at xproweb.mybluemix.net given the fact that it is not taken by some other user. If it had been taken you will get an error while upload and we will be uploading the file now.

For example my manifest.yml file for the chat application which I created in the last post looked like this :
---
applications:
- name: xproweb
  memory: 256M
  instances: 1
  host: xproweb
  command: node server.js
5. Alright now that you have created your manifest file, open up your terminal and change directory to your Node application root folder. And type in the following command :

cf login

It would now prompt you for an Email ID and a password. Enter in the email and password that you used to sign up at Bluemix.

6. Now you need to make a small change to your code. Add the following snippet before everything in your server.js file. This is a must for every application.
var port = (process.env.VCAP_APP_PORT || 8192);
var host = (process.env.VCAP_APP_HOST || 'localhost');
7. Before you upload your application you MUST delete your node_modules folder. Cloud Foundry will look into your package.json file and it would install the dependencies by itself.

8. And its time to upload your application to Bluemix. Type in the following command in your terminal and hit enter to start upload.

cf push app_name

Replace app_name with the name of your application as specified in your manifest.yml file. So now your application would be uploaded successfully. Just point your browser to the host provided in your manifest.yml file and you would see your application there !

There is also an alternative to Bluemix called as Heroku and you could check about it here.

That is it ! You now have a successful Node application running online ! Happy Node-ing :)

Monday, June 23, 2014

Node JS is the new hotness for developers out there. Well not completely new. It came out about five years back but still if fairly new. It was mostly noted because of its non blocking procedure. And so it would be much useful for creating a file upload system which does not affect the rest of your code, can be used to create a chat system and much more. So lets get started with our chat system.

Getting Started with Chat System :

There are some pre-requisites that you would need to know for creating this. Take a look below for them :
  • Knowledge on Javascript would help
  • Good Text Editor
  • Node JS on your computer
So well just head to this site and install Node JS.

NOTE : This is just a test application to get you started and has no measures for security.

Starting with your Code :

 Create a folder on your desktop and lets call it "chat". Open your terminal or your command prompt and change the directory to the chat folder on your desktop and run the following command.

npm init

It would prompt you to enter you some details regarding your application. Enter those details and hit return. Now that a package.json file would be created in your chat folder. This package.json file would be containing details that you entered in the terminal. And now you need to enter the name of the modules that you need to use in your application. In our case we would be using two modules connect and socket.io. I would be explaining the need of these modules later. For now open up the package.json file that was just created and type in the following in it. You need to enter this before the closing curly braces.
,"dependencies": {
  "connect": "2.0.0",
    "socket.io": "0.9.6"
  }
And now you need to install these modules before you could use it. To do the installation type in the following command in your command prompt after you change the directory to the chat folder.

npm install

And so now the modules got installed and lets get started with some node code.

Create a file called server.js in your chat folder. You would be creating your server in this file. We would be using the connect module to create the server. This would redirect your server to the index.html file in a folder named public which you need to create. Type in the following code to create the server and redirect it.
var connect = require('connect');
var io = require('socket.io');
var app = connect().use(connect.static('public')).listen(8080);
var chat = io.listen(app);
Now just create a folder named public and create a file named index.html in that folder. Just type in some sample content in it and lets test your app to see if that works well. To start your application type in the following command in your terminal after changing the current directory to the chat folder.

node server.js

Now open up your browser and navigate to http://localhost:8080 and this should display the index.html file of your public folder.

And now lets make our page to look like a public chatroom. Just add the following code in your index.html file.
<title>Chat Room - Node JS</title>
<link rel = "stylesheet" href = "style.css">
<script src = "/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div class = "room">
<div class = "messages">
<b><p class = "text" style = "color: #0072c5;">Messages</p></b><hr>
<div class = "text" id = "chat">
</div>
</div>
<textarea class = "msginput" id = "chattr" placeholder = "Hit Enter To Send Message" onkeydown = "check(event.which)"></textarea>
</div>
</body>
And to do some styling add the following code in your style..css file.
body {
background-color: #f1f1f1;
}
.room {
background-color: #fff;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 70%;
height: 70%;
padding: 2%;
}
.msginput {
resize: none;
width: 95%; font-family: Arial;
font-size: 16px;
padding: 10px;
border-radius: 10px;
position: absolute;
bottom: 10px;
left: 2%;
}
.messages {
border: solid #d1d1d1 1px;
padding: 10px;
height: 80%;
overflow-y: scroll;
}
.text {
font-family: Arial; }
Ok so now the markup part is done and lets get started with some socket.io code. So what is socket.io ? It is used for web socket programming in Node JS. Web sockets are bidirectional and full duplex that allows you to send and receive data back and forth between the server and the client simultaneously unlike the http protocol.

Socket.io allows you to emit and receive events between the client and the server. You can emit an on the server side and the client can listen for that and do some function or a client can emit an event and you can listen for that event on the server side. So we first need to create a variable that contains the sockets object. And we could use the connect event that is already present in the module to run a function when a new client connects to the site. So type in the following code in your index.html file.
<script src = "/socket.io/socket.io.js"></script>
<script type = "text/javascript">
var chat = io.connect();
var nickname;
chat.on('connect', function(){
              console.log('New user connected');
});
</script>

Try running this using the node server.js command in your terminal. Now open up your browser and redirect to http://localhost:8080. And then open up your terminal and you would see the message New user connected. We now need to create a prompt that asks the user to enter their name. After getting the name of the user we would then fire an event from the client that would contain the name of user. On the server side we would just listen for that event and would broadcast that message to all the sockets connected at that time. We will be dealing with the server side events at the end. To do that modify the above code as follows :
<script type = "text/javascript">
var chat = io.connect();
var nickname;
chat.on('connect', function(){
nickname = prompt("Enter Your Name :");
chat.emit('message', {message: "<i><b style = 'color: #0072c5;'>" + nickname + "</b> Joined</i><hr style = 'opacity: 0.3;'>"});
});
</script>
Instead of sending just a boring plain text I have just formatted it with some html tags make it look good. Alright. You could see that in the index.html we already had created a chat room look with a textarea with id chattr. We would just check every character that the user enters and check for him hitting the return key. Once he hits the return key we would fire the chat event and would send the message that the user entered along with the event. If you had noticed above we would have created an onkeydown event in the textarea that fires a check() function along with the event parameter. So lets create the check function now. Using this we would check the key code of the key pressed. And if it matches the keycode of return key (i.e. 13) we would fire the chat event. Add the following code to the script tag.
function check(e){
if(e==13){
chat.emit('chat', {message: nickname + ": " + $('#chattr').val()});
$("#chattr").val("");
    }
}
Ok so now lets go to our server side and lets listen for the events that we fired from our client. To do that add the following code to your server.js file.
chat.sockets.on('connection', function(client){
client.on('message', function(data){
chat.sockets.emit('message', {message: data.message});
});
client.on('chat', function(data){
chat.sockets.emit('message', {message: data.message + "<hr style = 'opacity: 0.3;'>"});
});
client.on('disconnect', function(){
   chat.sockets.emit('message', {message: "<p style = 'color: red;'>An User Left.</p> <hr style = 'opacity: 0.3;'>"});
});
}); 

You could notice that we are emitting another event called message event to all the sockets while listening to the chat event. We would be listening to that event on the client side again and would be displaying it to the user. And we also are emitting an event when the user gets disconnected which displays a message An User Left to all the users connected. So now our final job would be to display the message to the user. To do that add the following code within the script tag of your index.html file.
chat.on('message', function(data){
$("#chat").append(data.message);
});
We have just appended the div with id chat with the message that an user sends. So this would complete your application.

With all these said you could see that Node JS is already becoming too popular due to its asynchronous code. So it is a must to learn if you are going to be one of those awesome web developers out there. I used the following book learn Node JS and its really awesome. So why don't you do that too. You can buy it from the link below.

 You can find the code in the link below.

 Live Demo
Download Source Code




Try opening the live demo in a couple of tabs and test it out. And so that's the end of the post. Hope it helped out. Happy Node-ing :)

Thursday, June 19, 2014

CSRF stands third in the top 5 most important PHP security issues. Most of the sites out there are vulnerable to this CSRF attack. This can be carried out if you got some form submission on your site. So the first part of this post we would be seeing on what is CSRF attack, how it could be carried out and in the next post we would be dealing with the steps that we could take to prevent the attack.


How CSRF is carried out :

So the first step that you need to take in preventing any kind of hack is to learn how that hack works and how an hacker carry out that attack. So now lets see on how a CSRF attack is carried out.

Lets consider that you are having a site that allows your users to enter a list of movies that they've seen using a simple form that allows them to enter the name of the movie and their rating of the movie.  Let the form code look something like the following : 
<form method = "post" action = "submit.php">
<input type = "text" name = "movie">
<input type = "text" name = "rating">
<input type = "submit">
</form>
Lets say that your site's address is yoursite.com. Below is how the attack could be carried out considering this kind of a form.

1. The hacker would create a simple page containing the exact same form. He would change the action of the form that he just created to "yoursite.com/submit.php". So he is now redirecting the form to the submit.php file which is on your host.

2. The hacker would just fill in the details of the form by himself and the form would look something like this.
<form method = "post" action = "submit.php">
<input type = "text" name = "movie" value = "Inception">
<input type = "text" name = "rating" value = "5">
<input type = "submit">
</form>
3. The hacker would hide the form and would just trigger the submit button using javascript when someone visits this page.

4. So when a user who is logged in to your site visits this page then the movie Inception would be added to your database with the rating of 5 which the user would not be aware of. And the hacker has successfully completed his attack.

This is not the most basic example. The most basic example of this kind of an attack can be carried out if the developer is using a GET request. The hacker can simply modify the GET parameters and create an URL. He could then make the user to just open the link by some means.

This is just an example. In the same way the hacker could do any stuff. Even Bank Transactions ! Frightening right ? Well no worries. There are solutions for you, the developer, to overcome this issue.

How To Prevent CSRF :

1. Captcha Verifictaion :

Well, using captchas is one of the best ways to prevent a CSRF attack and this is the reason why most of the sites have a captcha verification when the user wants to do some sensitive changes to his/her account. But still captchas are not user friendly and a normal user would not understand the significance of a captcha code and would just get frustrated by entering it again and again. So there is another alternative which proves to be much efficient and user friendly.

2. Using Secret Token :

This is considered to be the best way to prevent CSRF attacks by most of the developers out there The basic concept is that you are including a hidden field in your form and you are entering a secret token as a value in it. You need to save this token value in a session variable. And in the form submission page all you need to do is to check if the value of the hidden field matches the value in your session variable. If it doesn't match then that would most probably be a CSRF attack. You can do it like follows.

<!-- form.php file --><form method = "post" action = "submit.php">
<input type = "hidden" value = "secret_token" name = "postsecret">
.... <!-- Rest of your Form goes here -->
</form>
<?php
 $_SESSION['secret'] = "secret_token";
?>
<?php
//submit.php file
if($_SESSION['secret'] != $_POST['postsecret']){
     //It's a CSRF attack
}
else{
    //Rest of your code here
}
?>
The only thing that you need to make sure is that if the secret_token is sufficiently hard to guess and it gets regenerated every time the user visits the form.php file.

And so this would be the end of the post and hope this helped you. Safe coding :)

Thursday, June 5, 2014

Security has been much of a concern for a long time and so it is important that you secure your web apps in the right away and you add the right amount of security.



Cross Site Scripting (XSS) is one of the most common vulnerability that most of the sites out there have got. It seems that about 65% of the websites over the internet are vulnerable to XSS. So why don't you just add your site to the rest 35%.

YOU MIGHT ALSO LIKE : What is And How To Prevent Session Hijacking in PHP


In this video showing you a demo on how XSS is performed and how you could prevent that.


Basic Principle :

The Basic principle behind XSS attacks is that if the user has got a text area to enter some details in it and pass it in a form and if you don't monitor the data that the user enters then he would be able to add HTML tags and even inject Javascript ! So you need to filter the data to make sure that the user input is free of Javascript for sure and the HTML part is just your wish. So take a look into the video to get to know on how to prevent the user from entering some Javascript into the input fields.

The Awesome Google Chrome :

If you are going to try XSS on Google Chrome you are going to fail even if the developer has not added any kind of data sanitization. This is because Chrome has some inbuilt stuff that prevents the users from entering Javascript into the input fields. But rest of the browsers out there are vulnerable to this attack. So it is even safer to use Chrome when you browse.

So maybe I'd be making more such videos in the future on PHP Security. Safe Coding :)

Sunday, June 1, 2014

CSS animations do rock according to me when compared to other kinds of web animation. I love those just for the fact that they are pure CSS. But still a few of those CSS animations are not completely pure CSS. They need JavaScript to handle some stuff. In this post we will be seeing on how to create a simple CSS slide up and slide down animation. So lets get started.

YOU MIGHT ALSO LIKE : CREATE YOUR FIRST CSS ANIMATION


The HTML Part :

The first thing of course is that you need to create the stuff that you need to animate. In this case we would be creating a simple HTML div that has a background color of black or whichever you prefer. Just add the following code to create the element and about the background color we would be dealing that with CSS.
<div class="slide" id = "slide">Random Stuff in here.</div> 

CSS :

And so now lets get started with the fun part. Add the following CSS stylings to your page. This basically adds a CSS transformation that lets you to animate the div that we created in HTML.
.slide {
overflow-y: hidden;
max-height: 500px; /* approximate max height */
width: 200px;
height: 200px;
background-color: red;
transition-property: all;
transition-duration: .5s;
transition-timing-function: cubic-bezier(1, 1, 1, 1);
}
.slide.closed {
max-height: 0;
}
The basic concept behind this is that we are just adding an additional class the div when we click on a button that we are about to create. This can be done using JavaScript. And so just add the following code and you would get the complete finished product.
<button onclick="document.getElementById('slide').classList.toggle('closed');">Click Me !</button>

 Download Source
 Live Demo



And so that is it ! Happy Animating :)

Monday, May 26, 2014

MySQL is almost dead and people are moving towards PDO and MySQLi a lot these days. The most important reason that people switch from MySQL is the fact that it is prone to injection. This could be prevented but still it is a major security flaw. So it is now time for you to migrate to PDO.

PHP Data Objects :

PDO is not as difficult as you think. It is pretty simple, in fact much simpler than MySQL. It is a more standardised way for dealing with Databases. It has common  syntaxes for different types of databases including MySQL, PostgreSQL, MS SQL Server etc. So watch the video below to get to know the basics of PDO.

Thursday, May 22, 2014

Scrollbars would look really cool if they get customized in the right way. It would for sure enhance the visual appearance of your site. And so in this post we would be seeing on how to customize the scrollbar using jquery and CSS. There is a method to customize it using pure CSS but the big problem with that is that it wont take effect in non webkit browsers like Firefox or Opera. And so we would be using jQuery plugins to make this task easier. This would just include a single line of jquery. So lets get started.


jQuery enscroll Plugin :

This plugin would help us in customizing the scrollbar. You can download the plugin from here.

Writing Down the Markup :

So lets just write in the HTML part now. Wrap the content that you want to be scrollable with a div of class scrollbox. Below is a sample code :

<script src = "jquery.js"></script>
<script src = "enscroll.js"></script>
<div class = "scrollbox">
   //Your Content Here
</div>

And so that is it we are done with the markup ! Simple as that !

The CSS:

And so it is time to customize the scrollbar. This of course we would be doing with CSS. Take a look at the code below :
.vertical-track {   //For the background track of the scroll bar
   //Stylings Here
}
.vertical-handle { //For the scrollbar pointer
   //Stylings Here
}
This styling holds good only for the vertical scrollbar. You can use .horizontal-track and .horizontal-handle for styling the horizontal scrollbar.

jQuery Part :

And so we are done with the markup and CSS. Lets add the jquery line now. Before that make sure that you have included the enscroll.js file and your jquery.js file. The following is the jQuery code that you would need to add.
<script type = "text/javascript">
$(document).ready(function(){
   $('.scrollbox').enscroll();
});
</script>

 Live Demo
 Download Source for Live Demo



And so that is it for this post. Happy styling :)

Tuesday, May 20, 2014

CSS Animations ! Yeah you can really do some good looking animation stuff in CSS and the basics are pretty simple too. In this post I would be writing on how to do some basic animation using CSS. To get started with CSS animations you need to learn a little bit about CSS transforms. They are kinda simple too.


So CSS animations are made of keyframes. Keyframes are parts of the animations and they define the animation. There are two steps in creating some animation effect using CSS.

  • Defining the CSS animation
  • Assigning it to an HTML element
And so let us get started with the first step i.e. defining the CSS animation. And by the way in this post we will be creating an animation that moves an image from one end to another.

Defining CSS Animation :

And so to define a css animation we need to use the @-keyframes keyword and you need to use moz and webkit to make sure that it works on all webkit browsers and as well as firefox and in addition to this keyword you need to add a name to the animation. So type in the code below to create the keyframe :
@-keyframes firstanim {
from{transform: translateX(0px);} 
to{transform: translateX(500px);}
And so that is it about defining the CSS Animation. You have now created the keyframes. And now you need to make it compatible with all those webkit browsers and firefox. It is really simple to do that. Just add the following lines of code and you could do it.


@-webkit-keyframes firstanim {
from{transform: translateX(0px);} 
to{transform: translateX(500px);
@-moz-keyframes firstanim {
from{transform: translateX(0px);} 
to{transform: translateX(500px);}
It is better that you add these two pieces of code before the previous one. And now that you have completed with the keyframes stufff. It is now time to add the HTML code and associate this animation with the HTML image.

Assigning Animation To HTML Image :

Lets just add a simple image using HTML and add a class to it.
<img src = "image.jpg" class = "animation">
And now let us add the animation to the HTML element. Add the following code to the CSS file.

.animation {
animation-name: firstanim;
animation-duration: 2s;
animation-timing-function: ease-in;
}
The first two lines are self explanatory. The third line wont be clear if you are new to this. It just defines the type of animation that you would like it to happen. It can take 5 type of values. They are linear,ease,ease-in,ease-out,ease-in-out. You can just experiment these things if you want. And the last thing that you need to do is to just add the following code to the same class so that it supports webkit browsers and firefox.

-webkit-animation-name: firstanim;
-webkit-animation-duration: 2s;
-webkit-animation-timing-function: ease-in;
-moz-animation-name: firstanim;
-moz-animation-duration: 2s;
-moz-animation-timing-function: ease-in;
 Download Source Code

And so that is it for this tutorial on basic CSS Animation. You can just download the Source code from the above link and try the demo. Happy Animating :)

Monday, May 19, 2014

So you would have seen in many sites that images would be displayed in a separate container and the background would get dull while the image gets displayed, just like lights off ! This is called a jQuery lightbox. And many think that it is a bit difficult to create and implement a jQuery Lightbox. That is kind of true if you are going to create your own Lightbox. The trouble comes in when you need to center the image in the dead center of the page.

Related Post : Horizontal and Vertical Centering in CSS



So to help you out of those troubles many developers started to create lightbox plugins. And I too did so keeping in mind that simplicity should be delivered. 

I created a jQuery Lightbox plugin called as PictureBox and the advantage of this plugin from others lies in its simplicity to implement and you will find out that in the later part of this post.

PictureBox ! - A Simple Yet Awesome jQuery Lightbox plugin

Features :

  • Completely Responsive
  • Very Easy To Implement
  • Very small footprint of 4.7 KB
  • Responds to your KeyStrokes
  • Includes Image Slider

How To Implement :

As I have been saying the implementation is so simple that even newbies could handle it. Here is the sample implementation code :

<link rel = "stylesheet" href = "includes/picturebox.css">
<script src = "includes/jquery.js"></script> 
<script src = "includes/picturebox.js"></script> 
<div class = "lightbox"> 
                   //Your Images 
</div> 
To put it much simpler just wrap the images that you want to appear in the image slider with a div of class lightbox. Simple as that ! So it is worth trying and you would love it.

 Download The Plugin

Thursday, May 15, 2014

Facebook recently updated the PHP SDK. And so the current version is version 4.0. And things have changed a lot from the previous version. It is now completely object oriented and is kinda easier when compared to the earlier version which was 3.2.3. I already made a video on how to Login To Facebook and Get the name of the user using PHP SDK V 3.2.3 and so in this post we will be seeing on how to do the same using this version. Lets get started.


Downloading the Facebook PHP SDK :

And so it is similar to download the PHP SDK and its just like the last version. So get headed to the link below to download the PHP SDK.

DOWNLOAD FACEBOOK PHP SDK V4

Writing Down The Code :

And so the next part is to code the stuff. The first thing that you need to do is that you need to extract the downloaded file and you need to copy the folder named Facebook inside the src folder. Copy that folder to the root of your project. And then write the following piece of code inside your index.php file.

<?php

session_start();
include 'Facebook/FacebookSession.php';
include 'Facebook/FacebookRedirectLoginHelper.php';
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphUser.php' );
Use Facebook\FacebookSession;
Use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
$helper = new FacebookRedirectLoginHelper('http://cyberfreax.com/test/index.php');
$session = $helper->getSessionFromRedirect();
if($session != NULL){
echo "Logged In !<br>";
}
else{
echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';
}
?>
And so in this code what we basically do is that we just include the Facebook PHP SDK files in our index page. Unlike the earlier version of the Facebook PHP SDK in this version Facebook has separated the different functions into different files so that you don't need to includes unnecessary functions in all files. And moreover it uses namespaces.

We are getting the Facebook session using the default function. If the session is not available then we prompt the user to login by displaying the Login link. And if the session is set it would mean that the user is logged in. And so we are at first just displaying the name of the user. But we would want to display the name of the user too. And so add the following piece of code right below the echo "Logged In !<br>"; line.

$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graph = $response->getGraphObject(GraphUser::className());
echo $graph->getName();
Instead of the above piece of code you can also combine them into a couple of lines. You can add something like the following :
$request = (new FacebookRequest(
      $session, 'GET', '/me'
    ))->execute()->getGraphObject(GraphUser::className());
    echo $user_profile->getName();
But the problem with the above code is that it works for only PHP version 5.3 and above. So make sure that you have a suitable version of PHP before running the above code.


 Download Source Live Demo



And so that is it. You can now easily add a Login with Facebook link to your website using the latest version of Facebook PHP SDK. Happy Coding :)

Wednesday, May 14, 2014

Responding to key strokes using Javascript is pretty simple and not as difficult as you think it is. This can be done using a simple javascript event called as onKeyDown and onKeyUp. And so this is a simple video tutorial teaching you guys on how to respond to key strokes using simple javascript.



 Live Demo

 Download Source Code


Wednesday, May 7, 2014

Drop Caps ! So they are one of the cool ways to design your site. The first thing you need to know is what is a drop cap ? Drop Cap is the one that you see in most of the books that the first letter of a chapter would have different stylings. It would have a bigger font size when compared to other parts of the paragraph. That is called as a drop cap. You can see that in this post too. So lets see on how to add that using CSS.


Using a Span :

One of the easy way to do that is to cover the first character of a paragraph to be within a span. You can do that using the CSS code like in the below.
<style>
.dropcap {
  float: left;
  color: #0072c5;
  font-size: 50px;
  line-height: 50px;
  margin-top: -3px;
  padding-right: 5px;
}
</style>
<p><span class = 'dropcap'>D</span>rop Caps are really awesome !</p>

Targeting first character using CSS :

In most cases it is possible that the text that you would like to enter in would be dynamic and so the above method would not be of use in such a case. So lets see on how to handle it. It can be done using CSS selectors.
<style>
p:first-child:first-letter {
  float: left;
  color: #0072c5;
  font-size: 50px;
  line-height: 50px;
  margin-top: -3px;
  padding-right: 5px;
}
</style>
<p>Drop Caps are really awesome !</p>
The output of this method would be the same as that of the previous method.But there is a catch here. This method wouldn't work for IE < 9. But that would not be a big problem. Only a very small percent of IE users would be using IE < 9. So don't worry about that. The output of the above methods would be something like the follows :

Drop Caps
And so that is it about this short post. Happy Designing :)


Sunday, May 4, 2014

Ever wondered how to create a lightbox ? So here is a video tutorial on how to create a fully functional LightBox in jQuery. This includes a Image Slider too. Watch the Video Below to do it in minutes :)





 Download Source

 Live Demo



Horizontal and vertical centering in CSS has been a boss for the css newbies who din't know the right way on centering elements in CSS and here is a guide on how to horizontally and vertically center elements in css. There are a few scenarios in this case. And lets deal with all of them.

Images :

1. Know Dimensions Horizontal and Vertical Center :

And so let us you are in such a situation where you are having an image with known dimensions and you want to center the image both horizontally and vertically so that it is in the dead center of the page. Then you can do something like the follows :
<style>

img {
position: absolute;
top: 0;
left: 0;
top: 50%;
margin-top: -250px; //half the height of the image - vertical alignment
left: 50%;
margin-left: -250px; //half the width of the image - horizontal alignment
}
</style>
<img src = "images/1.jpg" width = "500" height = "500">

OUTPUT 

This is the best way to align an image of a known width and height. What if you don't know the width and the height of the image that you are displaying for example if you are displaying images dynamically then you would not be knowing the width and height. So to align them take a look at the next scenario.

2. Unknown Dimensions - Dead Center Align :

To align an image in such a case you first need to create a div and let that div be the parent. The image would be a child in this case and so now you can easily align the image in the dead center of the div.

If you want to align the image in the dead center of the page then just expand the div to the entire page by using a width and a height of 100%.
<style>

#parent{
position: relative;
background-color: #d1d1d1;
width: 80%;  //this is your choice. But make sure you use % instead of pixels
height: 80%;  //this is your choice. But make sure you use % instead of pixels
}

#parent img {
position: absolute;
top: 5%;                           //vertical alignment
bottom: 5%;                  //vertical alignment
margin: auto;               //horizontal alignment
left: 0;
right: 0;
max-width: 70%;    //this is your choice. But make sure you use % instead of pixels
max-height: 70%;   //this is your choice. But make sure you use % instead of pixels
}

</style>

<div id = "parent">
<img src = "images/1.jpg">
</div>

And so the the image now has been dead center aligned ! So now lets see on how to align a text element.

Text

1. Dead Center of the Body :

Add the following code to your text editor. Make sure that the javascript comes after your element's markup.
<style>
p{
text-align: center; //horizontal align
}
</style> 
<p id = "new">Hello World</p>

<script>
var height = window.innerHeight;
alert(height);
document.getElementById("new").setAttribute("style","line-height: " + height +"px;");   //vertical align
</script>

2. Dead Center of a DIV :


It is easier to align text in the dead center of a div than the dead center of the body. This does not include javascript if you know the height of the div. Use the code below for the purpose :
<style>

div {
border: 1px solid #000;
height: 300px;
width: 300px;
}

p{
text-align: center;
line-height: 300px;  //same as height of parent div
}

</style>

<div>
<p>Hello World</p>
</div>

And so that is it for this short tutorial. You can now easily horizontally and vertically align both images and text in your markup.  Stay tuned for more and Happy Coding :)

Sunday, April 27, 2014

Ever wondered how those apps that you use in facebook are able to post content to your profile or your groups ? Well here is the solution. In my last post I've dealt with how to Login to your facebook account using the PHP SDK. And in this post I'll be dealing with how to post to facebook using PHP SDK. Watch the video below to know how to do


Useful Post : Login and Get name of the user using the Facebook PHP SDK

Video Tutorial :



 Download Source 

Wednesday, April 23, 2014

Hello there. I recently created a facebook web app that lets you to post to multiple groups, pages and your profile with just one click. You can post a message and even a link. Sounds cool right ? You can find the app here. And so I surfaced a lot through the facebook php sdk while creating the app. So now I thought of writing a series of posts dealing with the facebook php sdk.

In this post I'll be dealing with how to login to a facebook account using the facebook php sdk and how to retrieve the user information. And so lets get started.


VIDEO TUTORIAL



Prerequisites :


You need to have the following :

  • Fair knowledge on PHP

  • Facebook PHP SDK (We will be downloading this)

  • Your Text editor

Creating the app :


The first step is to create the actual facebook app. And this will be a kind of a communication link between facebook and your site. Follow the steps below to create your app :

1. Go to Facebook Developers Page.

2. Click on apps on the header and go to Register as a Developer. 

3. And once you have registered as a developer you will get into the documentation. (I swear Facebook has a really bad documentation)

4. Click on the same apps tab and click on Create a new app.



5. Enter a name, choose a category and proceed with creating the app.

6. In your app dashboard go to the settings tab and enter a contact email address.

7. Click on Add Platform and select Website.

8. In the site URL text box type in the domain of your site if you have one else type in localhost if you would be testing the app at your localhost. (Note : Facebook PHP SDK code would work only in the site which you mention here)

9. Save it return to your dashboard.

10. Make a note of your App ID and App Secret.

Bringing in the Facebook Login :


And now that you have completed creating the app and it is time to creating the login functionality. Follow the steps below to do so.

1. Download the Facebook PHP SDK.

2. Unzip it and copy the src folder inside it to the root of your app.

3. Create an index.php file where you placed the src folder.

4. Fire up your index.php file and type in the following code.
<?php

require_once 'src/facebook.php';

$fb = new Facebook(array(

'appId' => 'YOUR APP ID',

'secret' => 'YOUR APP SECRET ID'

));

Remember to replace your app id and your app secret. What this basically does is it creates an instance of the class BaseFacebook present in the facebook.php file.

5. And now to login the user add the following code.
if($fb->getUser() == 0){    //checks if the user is already logged in

$loginUrl = $fb->getLoginUrl();   //carries out if user not logged in

echo "<a href = '$loginUrl'>Login</a>";

}

else{

echo "<a href = 'logout.php'>Logout</a>";  //we will be creating the logout.php file later

}

In this piece of code we are letting the user to login to your site using his facebook account. We are displaying the login link if the user is not logged in else we are displaying the logout url.

6. We have completed logging in the user and now the job is to display the profile picture and name of the user. To do add the following code in the else part.
$api = $fb->api('me');

$name = $api[first_name] . " " . $api[last_name];

$id = $api[id];

echo "<img src = 'http://graph.facebook.com/$id/picture?width=150&height=150'><br>";

echo "Hi $name";

7. And so the only job left is to create the logout.php file. Create a file named logout.php and add the following code in it.
<?php

require_once 'src/facebook.php';

$fb = new Facebook(array(

'appId' => 'YOUR APP ID',

'secret' => 'YOUR APP SECRET ID'

));

$fb->destroySession();

?>

Replace your app id and the app secret in the respective places.

 Download Source Code

And that's it ! We have successfully created a facebook which lets the user to login and we have displayed the user's profile picture and his name ! We are done for the tutorial. Stay tuned for more tutorials on Facebook PHP SDK. Happy Coding :D