Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

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.

Note:
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.

DOWNLOAD SOURCE FILES


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


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

No comments:

Introduction:
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.

Advantages:
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.

Configuration:
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)
SMTP TLS/SSL: yes

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:

<?php
function mail_sender($to, $subject, $body) {
   require_once 'class.phpmailer.php';
   $from = "YOU_EMAIL_ADDRESS";
   $mail = new PHPMailer();
   $mail->IsSMTP(true);
   $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->AddReplyTo($from,'RECEIVERS_NAME');
   $mail->Subject = $subject;
   $mail->MsgHTML($body);
   $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.

<?php
   require_once 'mailer.php';
   $to = "RECEIVERS_EMAIL_ADDRESS";
   $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:


DOWNLOAD SOURCE FILES

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.
<?php
   if(isset($_GET['id'])) {
        // Further Code..
   }else {
        header("Location: index.php");
   }
?>

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

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

PHP: Header Function to convert PHP file into Text File.
<?php
   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.
<?php
   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:

Monday, October 21, 2013

Preventing PHP websites from SQL injections

1 comment:
SQL injections are another pain for developers. If you have created a users database then you might save the users: name and password. But what if any hackers breaks the security of your website and get in to your users account unethically. So this might make your users not to trust on you and soon many others will leave your website.
What is SQL injection:
SQL injection is a way of breaking the websites SQL query and customize it according to the hacker.
For example, if your website query for user to login is:
$u = "Ashwin";
$p = "TheCodePress";
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

But if i'm a hacker then i'll simply do something like this to break the security of your login system:
$u = "Ashwin' -- ";
$p = "Hacked";
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

So, what i have done ?
I have simply entered my correct username but after that i have added ' -- and this means comment in SQL.
So we have commented the rest of the portion of the query. That means we now don't need to enter password, we'll directly login into the website.

How to Solve this problem:
Well, the best way to do it without using any library or API is to use in built PHP functions. Such as mysql_real_escape_string(); and htmlentities();
If you are using mysql_real_escape_string function then all the vulnerable symbols will be parse, but it will parse safely.

PHP Code: So the code will be something like this:
$u = mysql_real_escape_string("Ashwin' -- ");
$p = mysql_real_escape_string("Hacked");
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

Is their any other better way to do it?
Yes, you can use the Library such as PDO or MYSQLI.
If you are more familiar with object oriented programming (OOP) then i'll prefer you to go with PDO.
Soon, i'll be too writing tutorials about PDO and Mysqli. You can learn it now on PHP manual.

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

Wednesday, October 16, 2013

Protecting your website from Vulnerable Script Tags and Codes

No comments:


It's really important for you to protect your website from hackers, but without removing any features from your website.
In this post we are going to understand how to solve the problem of XSS - Cross Site Scripting problems.

What is XSS:
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy.
                                                                                                                                -Source Wikipedia

Now to prevent our website from XSS attack, we are going to use a PHP function called: htmlentities()
This function of PHP will help your website to parse all harmful tags safely.

For example, if you have a website which displays comments submitted by the user and that comment system is XSS vulnerable, then if a user will enter some comment like this:

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

and now this comment is stored in your website's comment database. So whenever any user will meet the page where this comment is loaded from your database. Then the user will re-directed to the specified website.

So to prevent this problem we are going to use PHP function: htmlentities()
This function will replace all the < > / " ' = & and other symbols to a non-vulnerable signs. Like to display and in your website we use HTML Entities: &amp;
So in the similar way we are going to covert the vulnerable symbols in to non vulnerable HTML Entities.

You'll just need to wrap htmlentities() to the variable from which you POST the comment to the database.

PHP Code:
<?php
   $comment = htmlentities($_POST['comment_area']);
?> 

So that's how you can protect your website from XSS. In the next post we'll be discussing about how to prevent our website from getting hacked using SQL-injections.

About the javascript code, if we parse it using the htmlentities() function then this is the safe result and this can be added in our database.

Result:
&lt;script type=&quot;text/javascript&quot;&gt;
window.location = &quot;http://www.google.com&quot;;

&lt;/script&gt;

What we have done:

PHP Code:
<?php
$comment =
<<<comment
<script type="text/javascript">
      window.location = "http://www.google.com";
</script>
comment;

echo htmlentities($comment);
?>

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

Monday, October 14, 2013

Counting your website's loading time using PHP

No comments:


Counting your website's loading time is very useful and helpful for you to know that you need to make it more efficient or not.
Here, in this tutorial we are going to use PHP microtime() function to get the time and we'll be formatting it using number_format() function.
PHP code:
<?php
$mt = microtime(true);
        $format_time = number_format(microtime(true) - $mt, 2)." Seconds";
echo $format_time;
?>

If you are trying this code block on your on a blank page then probably you'll get 0.00 Seconds in results.
So to test it on a blank page follow this block of code:

PHP code:
<?php
$mt = microtime(true);
file_get_contents("http://www.thecodepress.info");
        $format_time = number_format(microtime(true) - $mt, 2)." Seconds";
echo $format_time;
?>

I'll always recommend you to use this but if you don't want to display it on your website then you can do something like commenting it something like this:

echo "<!--".$format_time."-->";

So after using that method the seconds will display in your website's HTML source code.
Another method which some other sites are using is to add the seconds at the bottom of the page (footer) you can too follow that.

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

Saturday, August 17, 2013

Loading website in a DIV using Ajax and PHP

4 comments:
Loading a website or content inside a DIV in ajax using php is common, everyone learns it when they are new to ajax. I'm also a beginner in Ajax. Let's start learning it from beginning, covering all the history of ajax as well as how to use ajax.

History: 
If you want you can read the history of ajax at wikipedia: http://en.wikipedia.org/wiki/Ajax_(programming)

To run ajax you'll need a server if you own a hosting then you can use that to run the application or you can download the XAMPP local server / host.

First we'll create two files, one will be the index.html and another one will be url.php (Refer below image to understand the directory structure.)


In the inder.html file we'll add our javascript inside the head tags and we'll call that using click event.
HTML & Javascript: index.html source code.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function loader() {
var ajaxhttp;
try {
//For major browser like Chrome etc...not for IE
ajaxhttp = new XMLHttpRequest();
}catch(e1) {
try {
//For IE6 and above
ajaxhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e2) {
try {
//For IE5
ajaxhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e3) {
//If all returns an error then we'll return false!
return false;
}
}
}
ajaxhttp.onreadystatechange = function() {
if(ajaxhttp.readyState==4) { //it should be 4 or 200
document.getElementById("frame").innerHTML = ajaxhttp.responseText;
}
}
ajaxhttp.open("GET", "url.php", true);
ajaxhttp.send(null);
}
</script>
</head>
<body style="margin:0px;font-family:trebuchet Ms;">
<h2 onClick="loader()" style="background:#2C2C2C;text-align:center;color:white;padding:15px;margin:0px;">Click to load the website in a DIV!</h2>
<div id="frame"></div>
</body>
</html>
We are using try..catch construct, which is a powerful exception-handling technique that was initially implemented in OOP languages. Basically, when an error happens at run time in the JavaScript code, an exception is thrown. The exception is an object that contains the details of the error. Using the try..catch syntax, we can catch the exception and handle it locally, so that the error won't be propagated to the user's browser.

Now we'll make url.php file to send the data from the server.
PHP: url.php source code.
<?php
   $url = "http://www.thecodepress.info";
   echo file_get_contents($url);
?>
Basically the url.php file loads the content of the specified URL which is fetched from variable url.
and then we are printing the contents of the file. So when our index.html tries to get the responseText from the server, the server sends the contents of the file and that's the reason for the website to be displayed.
Demo screenshots:
Before the page will load this will look like this and when we'll click the black header the page will load the website without refreshing the page.
When the user will click the black header then the specified website will load.


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

Saturday, July 20, 2013

Basic pagination with Mysql, PHP

6 comments:
Have you ever noticed why blogger or wordpress or any other blogging platform have added a 'Next Page' button or you ever noticed that why facebook directly won't shows all the posts as well as twitter won't load the tweets ? The reason is: while loading tweets or loading status or articles from database developers loop over the database again and again and if their are many thousands or hundreds of status, tweets etc.. than the page get slow/crashes. That's the reason why they use pagination. By the way facebook and twitter loads their feed using Ajax.


Let's first connect to our database:
PHP: Connecting to mysql database.
<?php
    $db_host = 'localhost'; // your mysql host
    $db_user = 'ashwin1999'; // your mysql user name
    $db_pass = ''; // password not set
    $db_name = 'pagination';
    mysql_connect($db_host, $db_user, $db_pass);
    mysql_select_db($db_name);
?>

After connecting let's move on adding tables and columns. First we'll create a table called 'page' and then we'll create column which name will be 'data' just for example i'm adding this names. You can even use PHPmyadmin (PMA) to make tables columns. Also i have added numbers from 1-20. Refer below image to understand it properly.









Let's begin with PHP code blocks!
PHP: Pagination code
<?php
   @$p = $_GET["page"]; //Getting Page number

   $pages_query = mysql_query("SELECT COUNT(data) FROM page"); // Counting total rows
   if($p=="" || $p=="0" || $p>$pages_query) { //checking is p is set and greater than 0
   $p = 1; //if not set than setting it to 1
   }

   $per_page = 5; //Total data to display per page
   $pages = ceil(mysql_result($pages_query, 0) / $per_page); //dividing total rows with total data to
   display for example 20/10=2 so 2 pages

   $start = ($p - 1) * $per_page; // subtracting $p value with 1 and multiplying it with $per_page for                  example 2-1=1*10 = 10

   $query = mysql_query("SELECT data FROM page ORDER BY data ASC LIMIT $start, $per_page");      //Running our query

   while($fetch_data = mysql_fetch_array($query)) { //fetching data using array method
   echo $fetch_data["0"]."<br />"; //printing the data
   }

   for($a=1;$a<=$pages;$a++) { //using for to display number
        echo "<a href='?page=$a' class='page_link'>$a</a> "; //printing numbers also using link tags
   }
?>

It just looks hard but it's not hard, just need to do the subtract and divide part properly and the it's done.

Sunday, June 23, 2013

Non-database page views counter using PHP

1 comment:
Page views counter is very helpful to get numbers of visitors visiting your website, but most of time many people saves that in database and in text files. In this tutorials we are going to save it in text files.


PHP:
<?php
function hits(){
$ips = Array("127.0.0.1");     //Enter ip address which you don't want count
$file = "hits.txt"; //file name
$ip = $_SERVER["REMOTE_ADDR"];     //getting ip address
if($ips[0]!=$ip){     //checking that 'ips' are not matched with var 'ip'
if(file_exists($file)){      //checking for hits.txt exists or not
$fr = fopen($file, "r");     //Opening file for reading
$fre = fread($fr, filesize($file))+1;      //reading and incrementing 1 
$fh = fopen($file, "w");      //Opening file for writing
$fw = fwrite($fh, $fre);     //writing
}elseif(!file_exists($file)){      //if not exists var 'hits.txt' then to create one 
$fh = fopen($file, "w");     //opening file for writing
$fw = fwrite($fh, "0");     //writing 0 to start from zero
echo "File Created.";     //displaying a positive message
}
}
}
hits();    // calling our function
?>

The ideal way to use this script is not to make the numbers of hits visible to your users, but if you want so make it visible then read the file and print it.

Add this block of code after calling the function 'hits()'.
PHP:
$fr = fopen("hits.txt", "r");    //open file to read
$read = fread($fr, filesize("hits.txt"));   //read the file
echo "Total Views: ".$read; // print the contents of file 'hits.txt'

Friday, May 24, 2013

A button hit counter for your PHP website.

1 comment:
In this tutorial, i'm going to share how to make a button hit counter, it's a basic level PHP so many can understand it and modify it. For this tutorial i'm going to save the counts in a text file, but if you want you can store it in a database.


Sunday, May 5, 2013

Change Background Color on every refresh using PHP and CSS

2 comments:
In the last post you have seen how to change background image of the website using PHP. But what if you want to change the background color of a website?. Let's see how to do it using PHP and CSS.



Friday, April 19, 2013

Change background on every refresh using PHP and CSS

7 comments:
Have you seen the old TWITTER on which after every refresh the site changes it's background image not only twitter the old AOL was doing the same and many other major and minor sites are doing it. By using this method you can also change the background image of your website. In this post i have implemented few lines of code which will help to change your sites background image on every refresh. Don't forget to check the live demo.



Monday, March 25, 2013

Find your Internet Protocol (IP) Address and Remote Port using your self made PHP Script

4 comments:
Internet Protocol (IP) address is a unique key / number of your personal or your office computer. Most of the people who want to know their PC's / Laptop's IP Address, they directly go to IPChicken.com or any other IP Finding service. What if you create your own PHP Application which finds your PC's / Laptop's IP Address ?. In this post i'll show you few lines of PHP script which will help you to find your IP address and also it will find Remote Port.