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

2/28/16

How to Create Simple Notepad with Save & Clear Option | PHP

To create a simple Notepad Application using PHP we need 3 main things : Connect page, Index page and Save page . The Connect page is used to create connection to your backend database .The Index page is used to interact with the front end user and the Save page actually saves your content or put your text content from front end Notepad to backend database . We will also use AJAX and Jquery for displaying the instant error messages .

How to Create Simple Notepad with Save & Clear Option | PHP


View demo   Find this Project on Github

Connect.php


<?php
$HOST='localhost';
$USERNAME ='root';
$PASSWORD='';
$DATABASE='notepad';

// Create connection
$connection = new mysqli($HOST, $USERNAME,$PASSWORD,$DATABASE);

// Check connection
if ($connection->connect_error) {
    die("Connection failed: ".$connection->connect_error);
} 

?>


The host in this example is Local Host but you can change this and point to your custom domain address.
Username and Password are used to get access to the MYSQL database .
I have used notepad as name of the MySQL Database .


Index.php


<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
  $("#save").click(function() {
  var filename = $("#filename").val();
  var textarea = $("#textarea").val();
  var formdata = 'filename='+ filename + '&textarea=' + textarea;

if(filename=='' || textarea=='')
{
  $('.onfailure').fadeIn("fast").delay(2000).fadeOut("fast");
}
else
{
   $.ajax({
    type: "POST",
    url: "save.php",
    data: formdata,
    success: function(){
    $('.onsuccess').fadeIn("fast").delay(2000).fadeOut("fast");
    }
  });
}
return false;
});
});
function eraseText() {
    document.getElementById("textarea").value = "";
 $('.onclear').fadeIn("fast").delay(2000).fadeOut("fast");
}
    </script>
  </head>
<style>
#outer-wrapper {
  padding:0px 50px;
}
#inner-wrapper {
 padding: 50px 0px 20px 0px;
}
#options {
 padding:20px 0px 20px 0px;
}
#status span{
 padding:20px 0px 20px 50px;
}
</style>
</head>
<body>
<div id="outer-wrapper">
<form id="notepad" >
<div id="inner-wrapper"><input type="text" id="filename" name="filename" placeholder="Enter your Filename ..." value="" >.txt</input></div>
<textarea id="textarea" rows="20" cols="100" name="textarea" placeholder="Type your text here ..." value="" ></textarea>
</form>
<div id="options">
<input type="button" id="save" name="save"  value="Save the file " ></input> | <input type="button" id="clear" onclick="javascript:eraseText();" value="Clear"></input>
</div>
</div>
<div id="status">
<span class="onsuccess" style="display:none"> File has been Saved Successfully. </span>
<span class="onfailure" style="display:none"> Text Area or Filename cannot be left Blank.  </span>
<span class="onclear" style="display:none"> Text Area has been Cleared.  </span>
</div>
</body>
</html>



I have used Jquery On Click function.So On click of Save button ,get the filename and Text Area value and store it in 2 variables.Then validate these two data (check if it is empty) , if it is empty display error message using Jquery fadeIn() and fadeOut() function or else use AJAX post request to send the form data to Save.php . Dont forget to add or link to Jquery library file.

Save.php


<?php
include('connect.php');
$filename="";
$textarea="";
if($_POST)
{
$filename=$_POST['filename'].".txt";
$filename = str_replace(' ', '_',$filename);
$textarea=$_POST['textarea'];
$query = "update notepad_table set filename='".$filename."',textarea='".$textarea."' where id=1 ;";
$result = mysqli_query($connection,$query);
}else { }

?>


Get the Filename and Text Area from Index.php,Store it in 2 variables and finally update the MYSQL Database notepad table using Connect.php connection.All Done .Any Questions Please comment below.

Also Read :  Java Program to Implement Simple PageRank Algorithm

11/8/15

How to Extract the IP Address of the Visitor (Client) | PHP

To extract IP Address of any real Website visitor or client using PHP , We should have some basic idea about predefined variables that are used in PHP. The predefined variables in PHP are Superglobal , which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods. Under this predefined variables we need look at $_SERVER['___'] variable to get IP Address . 


How to Extract the IP Address of the Visitor (Client) | PHP


$_SERVER is an array containing information such as headers, paths and script locations.The entries in this array are created by the web server .

You can get more details of $_SERVER : http://php.net/manual/en/reserved.variables.server.php

How to extract IP Address of the Visitor ?

IP address of the Client or user who viewed your Website can be got by using $_SERVER['REMOTE_ADDR'] . This will Print the IP Address of the Visitor (viewer) who requested the webpage to the Server . So when the request is made to the Server ,It stores the IP Address in $_Server Global variable which can be accessed using $_SERVER['REMOTE_ADDR'] variable .


<?php 
 $ipaddress = '';

if($_SERVER['REMOTE_ADDR'])
      $ipaddress = $_SERVER['REMOTE_ADDR'];

echo  "\n Your IP Address is :\t".$ipaddress;

?> 


You Can view the Demo here : Codispatch Demo

How to extract Real IP address if the Visitor is using Proxy Server ?

Some times visitor can spoof or hide the actual IP address that is assigned to that user and use Proxy Server address instead. This is commonly done using Hidemyass Proxy List  . Now we can't get the actual IP address of the visitor using PHP but we do can detect if it is Proxy Server or not, this is done by



<?php 
$realipaddress = '';

if ( $_SERVER['HTTP_X_FORWARDED_FOR'] || $_SERVER['HTTP_X_FORWARDED'] || $_SERVER['HTTP_FORWARDED_FOR'] || $_SERVER['HTTP_CLIENT_IP'] || $_SERVER['HTTP_VIA'] || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554)) || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
{
     $realipaddress = "Proxy detected \t".$_SERVER['REMOTE_ADDR'];
  echo $realipaddress;
}
?> 


You can view the Demo here : Codispatch Demo

(Note that you must use or spoof some Proxy server address in-order to understand the above demo )

How to Extract the IP Address of the Visitor (Client) | PHP

Now you know how to extract the IP address of the Visitor even if the user is using Proxy Server .If you have any questions or suggestions please comment it below .

Also Read :  Login Password Protected Page using Sessions | PHP



7/19/15

Login Password Protected Page using Sessions | PHP

This Tutorial will teach you to control and protect the access of any web page using PHP Sessions. We basically store some reference or item in the web browser and it is used every time when the user navigates from one web page to other web page , both pages of the same website. So for the first time the user has to go through login and later the user have to login only if browser content is cleared or the user's session expires.

Login Password Protected Page using PHP Sessions


Agenda : 

  1. Set Session Global Variable in your PHP Login Page .
  2. Create checkSession() Function to Validate user is already logged in or not.
  3. PHP Script that is added to every Web Page that you want to Protect from unauthorized Access

Set Session Global Variable in your PHP Login Page .

Just go to your Login Page . Add session_start(); function before all of the other Codes . 

Login Password Protected Page using PHP Sessions

 Next we store item like username or email etc in the Global Session variable .

If your using MySQL Database or any Similar Database to check the Login credentials. Write a query to get username or email or any other item that you want to store in your Session.

For example : If I Want to Store Username in the Session Variable ,please see the below Code.

 $query_session = "SELECT username FROM Table_Name WHERE (email='".$email."' AND password='".$password."')";
 $result = mysql_query($query_session);
 $result_session = mysql_fetch_array($result);
 //Assign the result of this query to SESSION Global Variable named username
 $_SESSION['username']=$result_session['username'];


Session Global Variable $_SESSION['username'] or $_SESSION['email'] is used to Store with Database retrieved Data .

Now save your Login Page as .php file .Any other format will not work or render properly . Don't Worry if it is in .html format or any other format ,the (PHP) Server will render html format or any other format as-well .

Create checkSession() Function to Validate user is already logged-in or not 

<?php
// This is a Generic Session Function to check Session username or Email or variable
function checkSession()
{
if(!isset($_SESSION)){ session_start(); }

         $username=$_SESSION['username'];
         
         if(empty($username))
         {
            return true;
         }
         return false;
}
?>

Save the Above Code as Session.php . If  $_SESSION['username'] or $_SESSION['email'] or any other reference or item that you've store in the step 1 is empty  then return true or else return false.

PHP Script that is added to every Web Page that you want to Protect from unauthorized Access


<?PHP
require_once("session.php");
if(checkSession())
{
    header("Location: http://your_Login-in_page.php");
    exit;
}
?>

Above Code must be added to first Line of any Web Page that you want to protect it from unauthorized access. The checkSession() will return true if $_SESSION['username']; is empty which means the user is not logged-in ,So send that user to Log-in Page . If checkSession() functions returns false then the user is logged-in which means $_SESSION['username']; Global Session Variable is not empty . Please See the Image below .

Login Password Protected Page using PHP Sessions

Please note :Save your file as .PHP format.

All done .Now any Web Page which has checkSession() PHP script installed is protected from unauthorized access .

Updated :

Disclaimer: Storing username & password directly as plain-text is not good practice and may lead to security threats , so MD5 (encrypt) them then store it .
This is just a plain simple concept of using sessions with PHP .


Also Read :  How to Extract the IP Address of the Visitor (Client)