Tuesday, March 18, 2014

Cross site request forgery (CSRF) Protection in PHP

1 comment:
Nowadays almost every website applies CSRF protection in their forms to make it more secure and safe. In this post i'll be first create a Class called Security and then we'll be making some methods to achieve the goal of making a Cross Site Request Forgery secure forms. Because of Cross site request forgery vulnerability an attacker can simply submit or process the form on behalf of the user without knowing of the users. This kinds of attacks are mainly done on E-commerce websites to place bogus orders.

Creating the Class:

Using the Class:
What we are doing here is first creating the class and then creating the 'Static' methods. The first thing what we have done is to get the token and then to inject it into our HTML using hidden input field. We have chosen hidden input type because we don't want the token (hash) to be displayed on our webpage.
We are also saving the token in the session so that we can verify it when user submits the form.

To verify the token we have build up a method called 'checkToken()' which firsts checks whether the token in set or not and then checks whether the token submitted by the user matches the token saved in our session. If it is then it first unset the session and then it returns a boolean value TRUE. If not then it returns FALSE.

Make sure you before using the Class you use session_start() function to start the session.

Saturday, February 22, 2014

Validating file extension in PHP

1 comment:
While making a file uploading or sharing system many do mistakes while adding the extension checking functionality and because of that many users are able to upload vulnerable files such as upload a PHP or Javascript or any other file. To prevent it what we do is to make a list of allowed extensions. When the user will upload the file then we'll retrieve the file extension and check whether that file extension is in our list or not. This makes a beautiful layer of security and it's important to do it.

What mistakes many do?
The mistakes what many people do is to check the MIME type. It's not recommended to compare the MIME type. Because MIME type can be changed.
For example, let's take that a user has uploaded a PHP file which contains some terrible code that can produce a DDOS attack on your website. So if he has successfully uploaded that file and shared the URL to access it. If 10 users click on the same URL, then probably your website will go down. This will happen because of the server got crashed or if your host is strict against bandwidth then obviously the host will shut your website down.

What's the best option to protect against this problems?
The best option is to add a file extension check. So whenever a user tries to upload any file our script will first check for the extension. If the extension is in the list then the file can go for other checks like size etc. But if it's not in the list then we'll show an error to the user to notify him about it.

Live Demo Download Now

Here's the function:

Example usage:

Tuesday, January 14, 2014

Validating and Embedding Youtube and Vimeo video dynamically using PHP

1 comment:
This function will help you to embed Youtube and Vimeo video dynamically. I made this for a project and now sharing it with you guys to use it in your projects or applications.
At the moment it's supporting Youtube and Vimeo URLs but soon i'll be adding support for other websites like Daliymotion etc.. When it will be completed i'll also share it with you through Github so follow me on Github https://github.com/thecodepress

Here's the function:
function v_embed($url) {
   $video = Array();
   $url = "video://".$url;
   if(strpos($url, "youtube")==true) {
      $host_pos = strpos($url, "youtube");
      $video["host"] = "youtube";
   }else if(strpos($url, "vimeo")==true) {
      $host_pos = strpos($url, "vimeo");
      $video["host"] = "vimeo";
   }else {
      $error = true;

   if($video["host"]=="youtube") {
      $video["id"] = substr($url, strpos($url, "watch?v=")+8);
   }else if($video["host"]=="vimeo") {
      $video["id"] = substr($url, strpos($url, ".com/")+5);
   }else {
      $error = true;

   if(isset($error)) {
      return false;
   }else {
      return $video;

Example Usage:
After pasting the code it's looking non-indented so it's suggested to download the source files of this tutorial which contain the example.

Don't forget it's just a small piece of code which is used for a project..so if you find any changes then you can comment it below or if you want you can use it anywhere. Soon a repository will be available on Github which will support many other video platforms.


Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:

Making URLs SEO friendly using .htaccess

No comments:

Making URLs SEO friendly is tried by many web developers and they use .htaccess to achieve it. Before proceeding to use .htaccess method you should enable Rewrite Module on your server. By default it's enabled.

By using this method you can remove the extension of a file and make it accessible without it's extension.
For example: http://www.example.com/example.php to http://www.example.com/example

That's quite interesting to have pretty URLs for search engines to index. Because the crawler index it according to the keyword.

Here the code which you have save in the root directory of your server.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php


Using Gmail’s SMTP as your SMTP Server with a PHP example.

No comments:

Gmail provides amazing features for developers; they provide developers to use their SMTP server to send emails from the application. In this article we’ll be configuring Gmail’s SMTP server for our application, we’ll also use an open source project called PHPmailer to send email from our Application.

Using Gmail’s SMTP servers for your application assures you that your email is sent, whereas sometimes when we use our own SMTP server we face problems like getting blocked or marked as spam by the automated spam filtering features. Another benefit I’ll like to mention here is if you use Gmail’s SMTP server then the emails which are sent from your application will be stored in Gmail’s Database. Another reason for using Gmail’s SMTP is that it’s not using Port 25 because there are many ISPs who are blocking the emails sent using Port 25.

Points to be noted:
Before starting to configure the Gmail’s SMTP server, it’s important for you to know that Gmail’s SMTP server only allows 99 emails per day. It means that you can only send 99 emails every day. The limit before was 250 emails per day, but because of high usage the limit decreased and came from 250 to 99 emails per day. Second point to note is that Gmail’s SMTP server requires authentication before sending emails. So make sure you have the password of the email which you’ll be using to send emails.

First you’ll need to login into Gmail account. After logging in navigate the settings button at the top right corner of your browser.

Now click on Settings, after clicking you’ll see a page like this:

Now click on Forwarding and POP/IMAP then you’ll see a like this:

Now just make sure all the setting which is shown above is the same for your account. If not then you can do it, it’s damn easy to do.
Below are the SMTP information which you’ll need to use in your application.
SMTP Server: smtp.gmail.com
SMTP Port: 465
SMTP Username: (your gmail email address, eg: example@gmail.com)
SMTP Password: (your gmail account password)

Example Application:
Let us make an example PHP application which sends email using Gmail’s SMTP server.
In this example we’ll be using PHPmailer which is an open source project you can know more about it on their official Github. Here’s the PHP code:

function mail_sender($to, $subject, $body) {
   require_once 'class.phpmailer.php';
   $from = "YOU_EMAIL_ADDRESS";
   $mail = new PHPMailer();
   $mail->SMTPAuth = true;
   $mail->Mailer = "smtp";
   $mail->Host = "tls://smtp.gmail.com";
   $mail->Port = 465;
   $mail->Username = "YOUR_EMAIL_ADDRESS";
   $mail->Password = "YOU_PASSWORD";
   $mail->SetFrom($from, 'YOUR_NAME');
   $mail->Subject = $subject;
   $address = $to;
   $mail->AddAddress($address, $to);

   if($mail->Send()) {
return true;
   }else {
return false;

Above we have created a function called mail_sender, this function will help us to send email without writing the SMTP details again and again. We have saved this function in a PHP file called mailer.php.
Now we are going to use this function.

   require_once 'mailer.php';
   $subject = "Test Mail Subject";
   $body = "Hi<br/>Test Mail<br/>Localhost Test";
   if(mail_sender($to, $subject, $body)) {
echo 'Sent!';
   }else {
echo 'Error!';

When the email is sent then it will look something like this:

If you have followed all the steps and done everything thing properly then surely you’ll send an Email. If you have got any errors or problem then first thing you should do is to check whether you have configure the Forwarding and POP/IMAP properly. If still you find any problem then check that the details you used in your application is correct. If still you receive any error then comment below.

Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:


Saturday, November 9, 2013

Creating custom HTML tags which support all Major Browsers

No comments:
Do you know that we can create custom HTML elements/tags? when i got to know about it i was like WOW! that will be kinda awesome and hard. But later when i researched about it i found it's really easy for anyone to create custom HTML elements. You don't need to do thousands of lines of coding.

For creating a HTML element/tag you just need to write the name of it like the standard HTML element/tag.
For example:
<computer brand="Acer" price="28,900" ratings="4" id="pc">Acer Aspire R7</computer>
 you are done by creating a custom HTML element. But this will only support all major browsers, excluding Internet Explorer.

To make the custom HTML tag work with Internet Explorer you'll just need to write a single line of Javascript.
<script type="text/javascript">
this will create an HTML element named as "computer".
Another point to note is, by default a custom element has a display inline. But you can change that with CSS.
<style type="text/css">
   #pc {
Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:

To learn more: http://www.x-tags.org/

Thursday, November 7, 2013

Using Header function in PHP

No comments:

Header function in PHP is quite powerful function. You have came across with such situations like: if some condition is false then the user should re-directed on the Index page of your website or may be after some seconds he should. Also Header function is useful while send the Content type of your webpage.

PHP: Re-directing to a webpage using Header Function.
   if(isset($_GET['id'])) {
        // Further Code..
   }else {
        header("Location: index.php");

PHP: Re-directing to a webpage after 10 seconds using Header Function.
   if(isset($_GET['id'])) {
       //Further code...
   }else {
       header("Refresh: 10; url=index.php");

PHP: Header Function to output a PDF file.
   header('Content-type: application/pdf');

PHP: Header Function to convert PHP file into Text File.
   header('Content-Type: text/plain');
   echo "This is just a text file...we have converted a PHP file into a Plain Text File.";

PHP: Header Function to convert PHP file into XML.
   header("Content-type: text/xml");
   echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
   echo "<person>";
   echo "<name>Ashwin Pathak</name>";
   echo "<age>14</age>";
   echo "<twitter>@TheCodePress</twitter>";
   echo "</person>";

Their are many other header functions you'll discover it by searching.

Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox: