Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, 19 July 2017

Create Your Own URL Shortening Service Using PHP jQuery

Create Your Own URL Shortening Service Using PHP jQuery


I made a URL shortening service a year back using PHP & jQuery. It was pretty simple. You should know the concept of URL Shortening. The concept is simple. When a user sends a request to short a URL, PHP will check if the URL is valid. If its valid then PHP will make a string of 5 or 6 characters. A folder is created with the name of this string and an index.php file with header function code is created in this folder. This will make the folder redirect to the URL the user requested. Since its a folder no extensions will be seen ! So You can make up some pretty good URLs.
Here is the form for URL Shortening :
<form id="subinsbshorter">
  <center>
   <input type="text" id="url" name="url" autocomplete="off" placeholder="Your URL here..."/><br/>
   <input type="submit" value="Short URL !"/><br/>
   Type in a <b>URL</b> and click on <b>Short URL !</b> to start shorting.
  </center>
  <div id="loader" style="display:none;">
   <center><img src="../cdn/load.gif" /></center>
  </div>
  <div id="successDiv" style="display:none;">
   <h2 style="color:green;">Shorting Successful</h2>
   Here is Your Shorted URL : <a href=""></a>
  </div>
  <div id="errorDiv" style="display:none;">
   <h2 style="color:red;">Invalid URL</h2>
  </div>
 </form>
 <style>
  #url{font-family: Droid Sans, Arial;font-size: 15px;font-weight: normal;border-width: 0px;padding: 5px;color: #999999;width: 405px;outline-style: none; outline-width: 0px;
 </style>
We also added a loader div, success div and an error div in the <form> tag. The jQuery code plays a vital role in this process because we are not adding any action attributes in the form, so if jQuery fail to load then the conversion wont work. Here is the jQuery code :
<script>
$(document).ready(function(){
 function isValidUrl(aUrl){var urlregex=new RegExp("^(http://|https://|ftp://){1}([0-9A-Za-z]+.)");return urlregex.test(aUrl);}
 function ser(u){$("#errorDiv,#successDiv,#loader").hide();$("#errorDiv h2").text(u);$("#errorDiv").show();}
 function slo(){$("#errorDiv,#successDiv,#loader").hide();$("#loader").show();}
 function sss(v,s){$("#errorDiv,#successDiv,#loader").hide();$("#successDiv").show();$("#successDiv a").attr("href",v);$("#successDiv a").html("<blockquote>"+v+"</blockquote>");}
 $("#subinsbshorter").on(submit,function(){
  v=$(this).find("#url").val();
  slo();
  if(isValidUrl(v)){
   $.post(add.php,$(this).serialize(),function(d){
   d=JSON.parse(d);
   if(d.stat==1){
    sss(d.url,d.name);
   }else{
    ser("Failed To Short");
   }
   }).error(function(){ser("Failed To Short");});
  }else{
   ser("Invalid URL");
  }
  return false;
 });
});
</script>
Insert the above code anywhere you like. The jQuery will check if the URL is valid and will send a POST request to add.php when user submits the form. If the URL is not valid, then jQuery will show the error div. Here is the add.php file :
<?
header(Content-Type: text/html);
function rantext($length){$chars="abcdefghijklmnopqrstuvwxyzsubinsblogABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";$size=strlen($chars);for($i=0;$i<$length;$i++){$str.=$chars[rand(0,$size-1)];}return $str;}
$dir="/urls/";/*Directory to store URLs. If main folder use "/" */
$url=$_POST[url];
if(!preg_match("/^(http://|https://|ftp://){1}([0-9A-Za-z]+.)/",$url)){
 die({"stat":"0"});
}
$name = rantext(5);
if (file_exists($name)){
 $name = rantext(6);
}else{
 mkdir(..$dir.$name);
 $subinsbshort = fopen(..$dir.$name./index.php, x) or die({"stat":"0"});
}
if(fwrite($subinsbshort,<?header("Location:.$url.");?>)){
 echo {"stat":"1","url":"//demos.subinsb.com/url-shortener.$dir.$name.","name":".$name."};
}else{
 die({"stat":"0"});
}
fclose($subinsbshort);
?>
We also added the Random String Function to the add.php available from here. The Function will generate a string of 5 characters. If the string created is already used, then the script will generate another string of 6 characters. Then the add.php will create a folder with the name of random string. The add.php returns a JSON data to jQuery. jQuery will process the data and if everything is OK, then jQuery will show a success message with the new shorted URL.
If you have any suggestions/problems/feedback say it out in the comments, I will help you.
And Happy Birthday Google.
{ Read More }


Friday, 30 June 2017

Create Simple Login Form Using PHP Basic

Create Simple Login Form Using PHP Basic


Hello...
How are you.....

The post before, the writter has sharing How to Create Simple Comment Form Using PHP. That posting has been implemented the lesson of input output using PHP MySQL. For the next lesson, the writter will be share how to Create Simple Login Form Using PHP. This lesson is basic of login method in website.

Okay, prepare in this lesson is, Web Server and MySQL, you can use XAMPP on this condition.

Lets go to the Lesson,

First, you could create a Database on MySQL and one table. There are 3 field on the table. Follow this tutorial for simple Lesson.
Now, the writter create a Database with name is blog. Than create table with the name is user. Next, there are 3 fields on the user table, it is a id_user as Primary Key,  username char(32), and password char(32). For detail, look at below.


Thats a structure of Fields on the user table. After you create a Database, Table, And Fields. Now you must fiil the Fields. For expample look at below.


Okay, now we just need a 2 (Two) Pages, 1 (one) for Login Page, dan 1 (one) again for Checking Page.

Lets create a Login Page, this page we will give the name is login.html. Below is the simple script on login page.

<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<br>
<form method="POST" action="check.php">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="user" size="20"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" size="20"</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" value="Login">&nbsp;<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
And than, create the checking page with the name is check.php. Below is the simple script on checking page.

<?php

##### Connection to database #####
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "blog";
$link = mysql_connect($hostname,$username,$password) or die("Error Connection");
mysql_select_db($dbname,$link);
##### End #####

##### Receive Input #####
$user = $_POST[user];
$pass = $_POST[pass];
##### End #####

##### Checking input in table within database #####
$sql = "select * from user where username = $user AND password = $pass";
$hasil = mysql_query($sql) or die("wrong");
$row = mysql_fetch_array($hasil);
if($row == "0") {
echo "<h2>Sorry, username and password does not match</h2>";
}
elseif($row != "0"){
echo "<h2>Login is Successful....</h2>";
}
##### End #####

?>
If all scripts was created. The simple login form was already to use.
The explain of that script is below.

$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "blog";
$link = mysql_connect($hostname,$username,$password) or die("Error Connection");
mysql_select_db($dbname,$link);

its script, are use to create connection between page to database.

$user = $_POST[user];
$pass = $_POST[pass];
its use to receive a input from html page (input username and password). After receive, the value will be include in the variables ($user and $pass).

$sql = "select * from user where username = $user AND password = $pass";
$hasil = mysql_query($sql) or die("wrong");
$row = mysql_fetch_array($hasil);
its use to checking value of $user and $pass on the Database. The basic of this process is on the query syntax. And than the query is executed with mysql_query(); syntax. And than will processed with mysql_fetch_array(); syntax. The result of it will be included on the $row variable. The value of the $row variable is one or zero.


if($row == "0") {
echo "<h2>Sorry, username and password does not match</h2>";
}
elseif($row != "0"){
echo "<h2>Login is Successful....</h2>";
}

Its to use to checking a value of the $row variable, is the value zero or one. If zero means username and password does not match. And if one means username and password does match.



Lets try it.
First. open the login.html page.

Than, fill username and password, than click "Login"
If, success you will look like below


if username and password does not match, you will look at below

Okay, that is Basic of Login Form Using PHP.
On the next time, the writter will share for Advanced Login Form Using PHP.

Happy Paper 4share !!
{ Read More }


Saturday, 27 May 2017

Create MySQL Injection free Secure Login System in PHP

Create MySQL Injection free Secure Login System in PHP


There were a lot of people who created tutorials to create a PHP Login System. But they were all vulnerable to MySQL Injection. In this post Im going to demonstrate a login system free of this vulnerability. There are mysqli and PDO in PHP to escape these injections. We are going to use PDO PHP Data Objects ).
First of all create a file named login.php, home.php, logout.php

Step - 1 - Create table users.
For storing user information you have to create a table named users. Here is the SQL code to create the table.
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` text NOT NULL,
  `password` text NOT NULL,
  `psalt` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  1. The column username is to store the e-mail of the user. This e-mail is used as the username.
  2. The column password is to store users password which will be heavily encrypted using SHA256.
  3. The column psalt contains a random text to check if password is true.
Now we should add a user to the table. Execute the following SQL code to create a user.
INSERT INTO `users` (`id`, `username`, `password`, `psalt`) VALUES (NULL, subins2000@gmail.com, 4f8ee01c497c8a7d6f44334dc15bd44fe5acea9aed07f67e34a22ec490cfced1, s*vl%/?s8b*b4}b/w%w4);
The user is inserted with the following values:
Step 2 - login.php
Create a login form :
<form method="POST" action="login.php" style="border:1px solid black;display:table;margin:0px auto;padding-left:10px;padding-bottom:5px;">
<table width="300" cellpadding="4" cellspacing="1">
<tr><td><td colspan="3"><strong>User Login</strong></td></tr>
<tr><td width="78">E-Mail</td><td width="6">:</td><td width="294"><input size="25" name="mail" type="text"></td></tr>
<tr><td>Password</td><td>:</td><td><input name="pass" size="25" type="password"></td></tr>
<tr><td></td><td></td><td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
Login System provided by <a target="_blank" href=http://sag-3.blogspot.com/2013/08/secure-injection-free-login-system-php.html>Subins</a>
</form>
Now we should add the PHP code to check whether the username and password is correct.
You should add the PHP code before </form> we just added in login.php.
<?
session_start();
if($_SESSION[user]!=){header("Location:home.php");}
$dbh=new PDO(mysql:dbname=db;host=127.0.0.1, username, password);/*Change The Credentials to connect to database.*/
$email=$_POST[mail];
$password=$_POST[pass];
if(isset($_POST) && $email!= && $password!=){
 $sql=$dbh->prepare("SELECT * FROM users WHERE username=?");
 $sql->execute(array($email));
 while($r=$sql->fetch()){
  $p=$r[password];
  $p_salt=$r[psalt];
  $id=$r[id];
 }
 $site_salt="subinsblogsalt";/*Common Salt used for password storing on site. You cant change it. If you want to change it, change it when you register a user.*/
 $salted_hash = hash(sha256,$password.$site_salt.$p_salt);
 if($p==$salted_hash){
  $_SESSION[user]=$id;
  header("Location:home.php");
 }else{
  echo "<h2>Username/Password is Incorrect.</h2>";
 }
}
?>
Step - 3 - home.php
<html><head></head>
<body>
<?
session_start();
if($_SESSION[user]==){
 header("Location:login.php");
}else{
 $dbh=new PDO(mysql:dbname=db;host=127.0.0.1, root, backstreetboys);
 $sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
 $sql->execute(array($_SESSION[user]));
 while($r=$sql->fetch()){
  echo "<center><h2>Hello, ".$r[username]."</h2></center>";
 }
}
?>
</body>
</html>
Step - 4 logout.php
This file is simple. Just add the following :
<?
session_start();
session_destroy();
?>
Now login using username as subins2000@gmail.com and password as subinsiby. You will be redirected to home.php and it will say the following:
This login system is totally 99% secure. Its very hard to crack for a hacker and its completely MySQL Injection free. It took me less than 1 hour to create this system and create this post. Happy Logging.
If you have any problems/suggestions/feedbacks just comment. I will help you if I can. Im 13 and I have school. I would rather spend my time on blog than school. :P
{ Read More }


Friday, 14 April 2017

Create Facebook Like System with Jquery MySQL PDO In PHP

Create Facebook Like System with Jquery MySQL PDO In PHP


Want to get a Facebook Like system in your site ? Youre at the right place. This technic is used in my social network, Friendshood. See the demo there in the social network. But you have to signup.
You should create a user table with users data including user idusernamepasswordemail etc...
The table should be like this:


Lets start by creating a likes table.

CREATE TABLE `fdlikes` (
`idint(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`pid` int NOT NULL PRIMARY KEY ,
`user` varchar(25) NOT NULL UNIQUE
); 
The pid field is for the post id. The user field is for the user id.


Create a post table to insert posts created by users.
CREATE TABLE `fdposts` (
`idint(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user` varchar(25) NOT NULL,
`message` varchar(200) NOT NULL,
`likes` int(11) DEFAULT NULL,
`posted` varchar(200) NOT NULL,
);
The id field is an auto increment field which decides the post id. User field is the users id and likes field contains number of users who liked the post. Posted field contains the date and time in which the post was created.
First of all create a config file that will connect to database. We are going to use PDO.

config.php

$dbh = new PDO(mysql:dbname=database;host=127.0.0.1, username, password);

Showing Like/Unlike Button

<?
include("config.php");

$pid=1; //Post id - Post is "Hi everybody"
$uid=1; //User id - User is "Subin Siby"
$sql=$dbh->query("SELECT * FROM fdlikes WHERE pid=$pid and user=$uid");
if($sql->rowCount()==1){
 echo <a href="#" class="like" id=".$pid." title="Unlike">Unlike</a>;
else
 echo <a href="#" class="like" id=".$pid." title="Like">Like</a>;
}
?>

jQuery code to post like/unlike action


$(".like").on(click, function(){
 if($(this).attr(title)==Like){
  $.post(action.php,{pid:$(this).attr(id),action:like},function(){
   $(this).text(Unlike);
   $(this).attr(title,Unlike);
  });
 }else{
  if($(this).attr(title)==Unlike){
   $.post(action.php,{pid:$(this).attr(id),action:unlike},function(){
    $(this).text(Like);
    $(this).attr(title,Like);
   });
  }
 }
});

PHP code to like/unlike in which jQuery sends request

This file is action.php
<?
include("config.php");
$pid=$_POST[pid];
$user=$_COOKIE[user];
$action=$_POST[action];
if ($action==like){
 $sql=$dbh->prepare("SELECT * FROM fdlikes WHERE pid=? and user=?");
 $sql->execute(array($pid,$user));
 $matches=$sql->rowCount();
 if($matches==0){
  $sql=$dbh->prepare("INSERT INTO fdlikes (pid, user) VALUES(?, ?)");
  $sql->execute(array($pid,$user));
  $sql=$dbh->prepare("UPDATE fdposts SET likes=likes+1 WHERE id=?");
  $sql->execute(array($pid));
 }else{
  die("There is No Post With That ID");
 }
}
if($action==unlike){
 $sql=$dbh->prepare("SELECT * FROM fdlikes WHERE pid=? and user=?");
 $sql->execute(array($pid,$user));
 $matches=$sql->rowCount();
 if ($matches!=0){
  $sql=$dbh->prepare("DELETE FROM fdlikes WHERE pid=? AND user=?");
  $sql->execute(array($pid,$user));
  $sql=$dbh->prepare("UPDATE fdposts SET likes=likes-1 WHERE id=?");
  $sql->execute(array($pid));
 }
}
?>
Thats it. Try it out. If theres any bugs, problems or questions feel free to comment below on DisQus.
{ Read More }


Sunday, 9 April 2017

Create Simple Form Using PHP

Create Simple Form Using PHP


Now, writter invite you to study hoe to create Simple Fom PHP.
Form example, we will a Comment Form, in the Comment Form, user will insert a name, email, and comment. For easy on this project, we will devide into 3 parts of pages, the pages is  comment_form.html, process.php, view.php, and connection.php.

Before you create that pages, writter suggest to create a Database first. 
Okay, the name of Database who created by writter is blog and the name of table is guest. Tha guest table are having 4 Field, there are id_guest, name, email, and comment. For detail of Fields, look at Below


After you create a Database, Table, and Field. Now, you create a connection.php page. That script like at below
<?
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "blog";

mysql_connect($hostname,$username,$password) or die ("Error connection...");

mysql_select_db($dbname);
?> 
And than, you create a comment_form.html page. That script like at below


<html>
<head>
<title>Comment Form</title>
</head>
<body>
<h1>Comment Form</h1>
<br>
<form method="post" action="process.php">
<table border="0" width="400">
<tr>
<td width="100">Name</td>
<td width="2">:</td>
<td width="298"><input type="text" name="name_guest" size="30"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" name="email_guest" size="30"></td>
</tr>
<tr>
<td>Comment</td>
<td>:</td>
<td><textarea name="comment_guest" cols="24" rows="5"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="send" value="Comment">&nbsp;<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
<br>
</body>
</html>


Than, you can create a process.php page. That script look at below
<?php
require("connection.php");
$name_guest = $_POST[name_guest];
$email_guest = $_POST[email_guest];
$comment = $_POST[comment_guest];
$sql = "insert into guest(id_guest,name,email,comment) values (,$name_guest,$email_guest,$comment)";
mysql_query($sql) or die ("error SQL query...!!!");
?>
<h3>Your Comment is Successfully....</h3>

And the last page is vew.php. Look at below


<html>
<head>
<title>View Comment</title>
</head>
<body>
<h2>View Comment</h2>
<?php
require("connection.php");
$sql = "select * from guest";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$name = $row[name];
$email = $row[email];
$comment = $row[comment];
echo "Name : <b>$name</b><br>";
echo "Email : <b>$email</b><br>";
echo "Comment : <b>$comment</b><br>";
echo "<hr>";
}
?>
</body>
</html>


Finish, if you want to try it,

First, open the comment_form.html page. And complate the form, look at below


Second, Klik Comment,  if successfully, the this display like at below


Third, view all comment was inserted with open the view.php page. Look at below...

Okay, finish...
if you have any problems, you can leave your ask into comment at below.

Happy Paper 4Share !!!
{ Read More }