ad

Wednesday, 29 April 2015

How to login to a website using cURL extension in PHP

In this quick tutorial I am going to show you guys how to login to a website using cURL extension in PHP. Here is two different tutorials that will help you understand this tutorials. Please have a look at them before you proceed. Note that this tutorial may not work on every sites as they will require different headers that come in request HTTP header.
GET and POST fundamentals 
HTTP-  the very basics

Lets crack it on! So you want to login to a website, no problem! Here's what you will need to do.
1. URL where the data is submitted to be processed.
2. Fields name, like username password and submit button.
3. PHP with cURL extension enabled.

Here is an example I have setup to demonstrate it. I have two files here, 1st is index.php where we will send the data from, and 2nd is process_login.php where the data is sent to - where it is processed. Basically we're sending all the data from index.php to process_login.php. Assuming process_login.php is the other website page where its data is processed.

The code I have in process_login.php checks if data received is valid, it checks if username and password match.
    session_start();
    if(isset($_POST["login"])){
        if( ($_POST["username"] == "username12345") and ($_POST["password"] == "password54321") ){
            $_SESSION["is_logged_in"] = $_POST["username"];
            echo "You're logged in, {$_SESSION["is_logged_in"]}";
        }else{
            echo "Couldn't process the request, something enexpected happened";
        }
    }


In index.php we do following:
- Store all data in a string, username, password and submit button name and value.
- Initiate curl.
- Set option,  CURLOPT_URL, URL we're working on.
- Return the result, instead of echoing it on screen. CURLOPT_RETURNTRANSFER
- What type of method we are using. CURLOPT_POST
- HTTP string we want to send to process_login.php to be processed. CURLOPT_POSTFIELDS

    if( isset($_SESSION["is_logged_in"]) ){
        echo "Welcome, {$_SESSION["is_logged_in"]}";
    }
   
    $username = "username12345";
    $password = "password54321";
    $submit_button_name = "login";
    $fields = "username=".$username."&password=".$password."&login=".$submit_button_name;
   
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://localhost/curl/process_login.php");   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);
    echo $result;

What is Object Oriented Programming and its 4 principles

Today I am going to talk to your guys about OOP Object Oriented Programming. So lets first define what OOP is, OOP is a programming style based on Objects - Object can be anything, for instance TV is an Object, and so it everything else we see in physical world. But when it comes to programming it slightly  changes any data structure can become an object. Data structure is simply a way of organizing data.

Now, you may ask whats the need to use OO style. Well here is what may surprise you, most if not all libraries are written in this style. If you ever start using one, and do not already know OOP, you are going to have hard time understanding how things are working. Another advantage of learning OOP is code organization, chances are if something has been written in well structured manner, it will be easier to re used in future.

As mentioned above object is the actual thing. But what actions are executed in order to get an object?? Well, there's something called a Class, a class is a template to make Object. Have you ever been or seen a factory? Basically the major part of it is occupied by machines, now in a biscuit factory there is couple of machines, either biscuit is made with all machines working together - each playing its own role or there can be just one machine that makes whole biscuit. In either situation, our machine is our Class and biscuit our Object.

Lets talk about the principles.

Abstraction
First of all we have Abstraction. Abstraction is nothing but a concept in OOP. Basically, a Class helps us achieve abstraction, often when someone shares code we do not need to know how things are working on the other end, all we know is if I do this, I will get this. For example, whenever you hit press a key on your keyboard, you really do not know what exactly is happening the moment you press the key, all you know is if I press a key I will see a word on screen. It has given us an interface, the button.

Encapsulation
Now we have Encapsulation, Encapsulation is pretty straightforward, it is basically packing your data so people only have access to certain things that they really need. Lets say you are making a mobile phone, user can make calls, charge, take pictures etc.. But what if user tries to change mobile phone model? its other mechanism? What if you tried charging it with different cable? Well it will not allow you to do so. Because those things are encapsulated. It only gives you access to what you need.

Inheritance
Inheritance is used a lot. Inheritance is something that inherits(comes form) something else that is more generic.You can inherit its features into something specific you may want to make. For example, you have a class that validates username, password, email. If you inherit another class from it, your new class will have all the functionality that the original class had, you would not need to copy paste features from original class to new class because you have inherited it all to new class. Now you can add more features to the new class and you have something with additional features. Inheritance allows to not repeat same code over and over again.

Polymorphism
Polymorphism is also easy to understand. I will quote this from code.tutsplus.com, it explains it quite well.
"The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism."

Saturday, 25 April 2015

Post advertisement banner on your site and track the impressions!

Well thought I'd write this little script, it essentially stores/tracks hits/impressions. Has the option to show both total and unique hits. Creates table itself.

How to get it working:
1. Go to your DB management  and create database, name it whatever you like.
2. Get connected to database. Just edit info in connection_to_db.php file.
3. Change info as desired.File: index.php






4. You're good to go!
If you want to see the hits without visiting database just uncomment every line of code and it will start showing.

Git repository.
https://github.com/phpdevsami/Impressions-tracker



Wednesday, 22 April 2015

Model, View and Controller - with example

What we've been told since the childhood is if you put things at the right place, it's easier to find later on and everyone can do their work without having problems, and that's what MVC essentially is, MVC it's a design pattern, it says, keep everything seperately, model - view - controller.

Model is like storage, it interacts with databases, stores files etc.. Database developer or admin work with it.
View is whatever you see on webpage, design, interface etc.. web designer or front end developers usually work with it.
Controller is where all your logic goes if statements, loops functions etc.. developer/programmer work with with it.

VIEW:: Lets use view, show user interface.. input boxes etc..
CONTROLLER:: Lets gets data to controller POST/GET.
CONTROLLER:: Lets do logic, validate it etc..
CONTROLLER:: Lets now call model to validate(see if credentials are right or not/or store data etc..) the data.
MODEL::Lets check data against database.
CONTROLLER:: Lets check what model has returned.
CONTROLLER:: Lets do action depending on what model has returned.
VIEW:: I'm waiting for controller to reply back.
VIEW:: I will show interface/graphics/text depending on what controller has replied back. 

Index
include("login_view.php");
include("login_model.php");
include("login_controller.php");

Login_view::show_login_form();
$Login_controller = new Login_controller();
$Login_controller->validate($conn);


Model(Interacting with database trying to match information against information in tables)
    class Login_model{
        function __construct($conn){
            $this->conn = $conn;
        }
        function check_user_and_pass($username, $password){
            $select_user_pass_query = $this->conn->prepare("SELECT username, password FROM users WHERE username = :username, password = :password");
           
            if($select_user_pass_query->execute(array(':username'=>$username, ':password'=>$password))){
                $details = $select_user_pass_query->fetch(PDO::FETCH_NUM);
                if(!empty($details)){
                    return true;
                }else{
                    Login_view::show_message("Wrong user or password");
                }
            }else{
                Login_view::show_message("Error occured");
            }
        }
    }


View(Showing the form)
class Login_view{
    static function show_login_form(){
        echo
        "<form method=\"GET\" action=\"{$_SERVER["PHP_SELF"]}\">
            Username: <input name=\"username\" type=\"text\"> </br>
            Password: <input name=\"password\" type=\"password\"> </br>
            <input name=\"login\" type=\"submit\" value=\"Login\">
        </form>";
    }
   
    static function show_message($message){
        echo $message;
    }
}


Controller(doing all the main logic that's needed to be done before model starts his job - ignored the check of session whether user is logged in, view is usually invoked if controller decides to. For example, it could say, user is logged it do not show the form.)
    class Login_controller{
        function validate($conn){
            if( isset($_GET["username"]) && isset($_GET["password"]) ){
                if( !empty($_GET["username"]) and !empty($_GET["password"]) ){
                    $Login_model = new Login_model($conn);
                    if($Login_model->check_user_and_pass($_GET["username"], $_GET["password"])){
                        session_start();
                        $_SESSION["username"] = "is_logged_in";
                        Login_view::show_message("logged in");
                    }
                }else{
                    Login_view::show_message("empty");
                }
            }
        }
    }

Monday, 20 April 2015

GET and POST - The fundamentals

Please read HTTP the very basics before you start this tutorial.

I'm sure many of you are already familiar with HTML forms, if not, HTML form is a way to collect information from user. Most common HMTL form is login. You put in your username and your password and hit submit button.

Now you might be wondering, yeah that's fine I've filled the form and pushed the submit button, what happens next..? Well that's the reason I'm writing this tutorials, by the end of it you'll have a solid grasp of both methods, GET and POST, and also what happens after you've pressed the button.

Lets start from scratch, the moment you hit the submit button one of these two things happens, your data is checked, if it's valid, it's send to server - where it's then processed.

Lets start by GET request, here's a simple example.
Filled form, pressed submit. Client(browser/you) sends HTTP request to server, sending regular headers and request method. However this time, with request method it will send something else too, it's form data! When form data reaches server, it gets stored in $_GET variable

Client requesting URL and sending parameters(data) along with it.




Here's a simple example of POST request.
POST requests is simple too, instead of sending data with request URL it sends it with request body! and when server receives it, instead of $_GET it stores it into $_POST variable.
















Your data is always send in name value pair, like and separated by ampersand. When you're making get request anyone can see what you've typed in form from address bar. However if request is POST data is send in HTTP request body.

More about POST and GET requests.
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php

HTTP the very basics

What the heck is HTTP? Well first off, it is a protocol, you ask what’s a protocol, protocol is set of rules, that something must follow! What if you it doesn’t follow it? Well it doesn’t work properly. HTTP is Hypertext Transfer Protocol. Whenever you wanna transfer something on web, you must follow the protocol/rules! And that essentially what HTTP is.

Now that we know what HTTP is lets try understanding what exactly is happening, when you open a site. Lets say you open www.example.com your client/browser will send a request to server asking, hey! I want that file.. Server will try finding a file, if it does it find it, it will send it back.

Client asking for a file is called request, and server sending file or message back is called response.

Now for example, when you open www.google.com you’re also sending server certain information, like our browser details – like user agent, telling server what browser is it, on what platform etc etc.. Then server responds back with some headers of its own.

Basic HTTP request/response structure.
First thing we see in picture is request list, and rest of it is request header. We’ve requested the page. And send some header along with it.




And here is server sending us some response headers back.


Once you've understood this, make sure to have a look at requests type tutorial, which I'll be posting soon.

Detailed information on RFC
http://tools.ietf.org/html/rfc2616#section-1

Friday, 17 April 2015

Connect to database using PDO extension and error handling

First off, those who don't know what database is, in lay man's term it's a place where you can store,
update or retrieve information. Like, username, password, user IP address and much more!

Let's start by learning how to connect to database. Note that you will need PHP v5.1.0 as we'll be using PDO(PHP data objects) extension - extension is something that's usually added later on to add more functionality. PDO extension is used to access databases.

Whenever you're ready, lets get to it.

PDO is a class, so we needa create an instance off it. And if you head over to PHP manual, http://php.net/manual/en/class.pdo.php it shows us that there's a constructor that requires certain things. First parameter we provide it database engine name, host and databse name. Then user and pass.

$host    = "";
$db        = "";
$user    = "";
$pass    = "";
$Connection_object = new PDO('mysql:host='. $host . ';dbname=' . $db, $user, $pass);



You've now connected to database, but how do you make sure? Well PHP provides a way to hande error. Here's the syntax, you TRY, then you CATCH, you provide catch keyword the class name which's Exception, and a variable, which then will turn into an object so you can call its methods.

$host    = "localhost";
$db        = "forum";
$user    = "root";
$pass    = "hpdevsami";

try{
    $Connection_object = new PDO('mysql:host='. $host . ';dbname=' . $db, $user, $pass);
    throw new Exception("error");
}catch(Exception $m){
    echo $m->getMessage();
}

   
Now your $Connection_object is an object and has methods like prepare, execute etc.. which can then be used make queries, fetch data etc..

Useful links:
Exception class:
http://php.net/manual/en/class.exception.php#exception.props.message

Type hinting:
http://php.net/manual/en/language.oop5.typehinting.php

PDO class:
http://php.net/manual/en/class.pdo.php

Free forum script made in PHP

samforum

I have been working on this forum for a while, thought of adding couple premium features and sell it but due to lack of time I may or may not be able to finish it - so here, I am going to release what has been done, for free. Forum has been made with general security in mind, all queries in uses PDO and the best is that I have written all the code in Object Oriented style which will give you ability to extend of easily make modifications with ease.

Functionality:

  • Sql injections protected(PDO)
  • Basic XSS protected
  • Registration
  • Login
  • Captcha(basic)
  • Recover password
  • Change password
  • Chatbox
  • Search
  • Post threads
  • Post replies
  • Edit threads(edit own thread title/body)
  • Create category(admin)
  • Edit category(admin)
  • Delete categories(admin)
  • Edit threads(admin)
  • Delete threads(admin)
  • Delete replies(admin)
  • Clicks tracker

Functionality that may be added in future.

  • Mentioning system
  • Private messaging
  • Avatar
  • Status update
  • Design

How to guide.

Open connection_to_db.php file and write down your dataabse details, hostname, username, password and databse name. Change site_name name in form_registration_class.php on line 110 to your website/forum link, and "from" to your website's name, for example "sam forums".
There is no need to import database or table, I have written all the queries, that should make required tables for you. Just create a database named "forum".

Here's a link to my github samforum repository where you can download/clone it from.
https://github.com/phpdevsami/samforum

Overwhelming data on page? write a pagination script.

Imaging you've 100 rows in database, and you're wanna show them all. What're you gonna do? Well obvious answer would be to just throw all of it on one page or.. you can divide the content into small chunks. 100 rows, what about we show just 10 rows one first page, then other 10 on another, and so on.. 1st page shows 10, 2nd another 10, 3rd another 10.. and like so until we reach 100.

Whenever you're ready, go ahead and try it out!  All code's been commented in details. Enjoy!


//including  database file.
include("connection_to_db.php");

//We're getting page number from url, using get variable.
if(isset($_GET["page_num"])){
    $page_number = $_GET["page_num"];
}else{
    $page_number = 1;
}

//Select all the data.
$select_city_data_query = $conn->prepare("SELECT * FROM city LIMIT 100");
$select_city_data_query->execute();


//Lets get how rows are there in total.
$row_count = count($select_city_data_query->fetchAll());

//first page.
$first_page = 1;

//Alright I wanna show 5 chunks per page. We also need this number to divide the total pages so we know how many pages there will be in total.
$chunks_per_page = 5;

//Lets get what number would be our last page, we'll need that so when user clicks on last page link it sends him to it. You see that ceil function? well it rounds fractions up, imagine if we had unknown number of rows, lets say 121 and we wanted to show 5 per page. That if divided would be 24.2 rows per page? huh? Well yeah we cant have that, so ceil will just round the fraction up. It'll then be 25 rows per page, not 24.2..!
$last_page = ceil($row_count/$chunks_per_page);

//Okay, what do we need now? Well we needa way to display right messages on every page. If we just went now and tried our script it'd show same messages on every page. It's just grab value from GET variable do nothing with it..

//We needa do something so it shows right messages on each page. 1st page, 1st 5 messages, 2nd page, 2nd five messages and so on.. We're on 1st page, we wanna show first five messages, we all we do is make a query and limit it by 5. But what about 2nd page..? Here's what we're going to do. We start from certain messages and end it after 5 messages. We need to know where to start.
//well we got our starting point, according to our formula on 1st page we start from 0, 2nd page from 5, 3rd from 10...
$limit_starting = ($page_number - 1) * 5;

//We also needa to know where to end. According to this forumula 1st page ends at 5, 2nd at 10, 3rd at 15, 4th at 20, 5th at 25, 6th at 30...
$limit_ending = $page_number * 5;

//So now lets make query and show the result.
$select_limited_message_query = $conn->prepare("SELECT * FROM city ORDER BY ID LIMIT $limit_starting, 5");
$select_limited_message_query->execute();


//Basic while loop to show all the results and now just first one.
while($data = $select_limited_message_query->fetch(PDO::FETCH_ASSOC)){
    echo $data["Name"] . "</br>";
}

//Aren't we missing something? Yeah, we need actual link 1, 2, 3, 4, 5, 6, 7...
for($i=1; $i<=$last_page; $i++){
    echo "<a href=\"?page_num=$i\"> $i </a>";
}

//Lets show link, which when clicked sends us to first page.
echo "<a href='?page_num=".$first_page."'>First page</a> ";
echo "<a href='?page_num=".$last_page."'>Last page</a> ";