Friday, 7 June 2024

Simple URL shortener in php

Create simple URL shortener for your own website in php.

table name : shortener

id int(11) auto_increament

email varchar 225

ip varchar 50

hash varchar 50

url text

status int(10)

view int(11) 

--------------------------------------------------------------------

 <?php

include "connect.php";

session_start();

if(isset($_SESSION['username']))

{

    $username = $_SESSION['username'];

}

else

{

//header('location:login.php');

}

?>

<?  $ip = $_SERVER['REMOTE_ADDR'];

$ip = str_replace(".","",$ip);

    $yourdomain = $_SERVER['HTTP_HOST'];

    $yourdomain = preg_replace('/^www\./' , '' , $yourdomain);

    ?>

<!DOCTYPE html>

<html class="no-js">

    <head>

        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4305348743992957"

     crossorigin="anonymous"></script>

        <meta charset="utf-8">

        <link rel='shortcut icon' href='adquash-logo.png' type='image/x-icon' />

<title>Free URL Shortener</title>

<meta name="description" content="Free URL Shortener is a tool to shorten a long link and create a short URL easy to share on sites, chat and emails. Track short URL traffic and manage your links.">

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="keywords" content="ShortURL,free ShortURL,URL Shortener,free URL Shortener">

 <meta property="og:image" content="https://adquash.com/adquash-logo.png">

       <link rel="stylesheet" href="3.css">

    </head>

   <body>

  <div class="wrapper">

    <?php include("header.php");?>

    </div>

    <div class="container">

        <div class="left-panel">

            <div class="content">

<div class="topad"><?php include ("banner.php"); ?></div>

<div class="col-md-12">

    <?php

if(isset($_POST["submit"])){

$url = $_POST["url"];

$email = $_POST["email"];

$ip = $_POST["ip"];

$status =1;

if(!empty($url )){

    function generateRandomHash($length = 5) {

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    $charactersLength = strlen($characters);

    $randomString = '';

    for ($i = 0; $i < $length; $i++) {

        $randomString .= $characters[rand(0, $charactersLength - 1)];

    }

    return $randomString;

}


function hashExists($connection, $hash) {

    $sql = "SELECT COUNT(*) AS count FROM shortener WHERE hash = ?";

    $stmt = $connection->prepare($sql);

    $stmt->bind_param("s", $hash);

    $stmt->execute();

    $result = $stmt->get_result();

    $row = $result->fetch_assoc();

    return $row['count'] > 0;

}


function storeHash($connection, $email,$ip,$status,$url,$hash) {

    $sql = "INSERT INTO shortener (email,ip,status,url,hash) VALUES (?,?,?,?,?)";

    $stmt = $connection->prepare($sql);

    $stmt->bind_param("sssss", $email,$ip,$status,$url,$hash);

    return $stmt->execute();

}



do {

    $hash = generateRandomHash();

} while (hashExists($connection, $hash));


if (storeHash($connection, $email,$ip,$status,$url,$hash)) {

    //echo "Hash generated and stored: " . $hash;

} else {

    echo "Error storing hash: " . $connection->error;

}


$sqlf = mysqli_fetch_assoc(mysqli_query($connection,"SELECT * FROM shortener WHERE hash = '$hash'"));

echo '     

<style>

        #confirmation {

            display: none;

            color: green;

            margin-top: 10px;

        }

    </style>

    <input type="text" id="myInput" style="width:100%;height:50px;" value="https://adquash.com/'.$sqlf["hash"].'">

    <button style="width:100%;height:50px;background-color:blue;color:white;" onclick="copyToClipboard()">Copy</button>

    <div id="confirmation">Copied to clipboard!</div>

    

    <br><br>

Copy the short link and share it in messages, texts, posts, websites and other locations.<br><br>

<b>Your shortened URL : https://adquash.com/'. $sqlf["hash"] .' <br><br>

Your Long URL: '.$sqlf["url"].' </b><br><br>


Total of clicks of your <a target="_blank" href="https://adquash.com/'. $sqlf["hash"] .'">short URL</a><br>

Shorten another URL<br>


* Short URLs that do not have at least one click per month are disabled<br>


Share it on social networks<br>


    <script>

        function copyToClipboard() {

            var input = document.getElementById("myInput");

            input.select();

            input.setSelectionRange(0, 99999); // For mobile devices


            navigator.clipboard.writeText(input.value).then(function() {

                var confirmation = document.getElementById("confirmation");

                confirmation.style.display = "block";

                setTimeout(function() {

                    confirmation.style.display = "none";

                }, 3000);

            }, function(err) {

                console.error("Could not copy text: ", err);

            });

        }

    </script>';}

} else { echo '

 <center><h1>Create a short URL Free</h1></center> 

<div class="col-md-12">

                  <center><h1>Paste the URL to be shortened</h1></center>

                  <form action="#" method="post">

                      <div class="form-group col-md-12">paste your url :<br>

                      <input type="url" name="url" style="width:100%;height:50px;" placeholder="paste your url" required/></div>

                      <div class="form-group col-md-12">

                        Email       :<br>  <input type="email" name="email" style="width:100%;height:50px;" placeholder="Email Address" id="emailInput" onkeyup="validateEmail()" required/><span id="emailError" style="color: red;"></span>

   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

                            <script>

  function validateEmail() {

    const emailInput = document.getElementById("emailInput");

    const emailError = document.getElementById("emailError");

    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;


    if (!emailPattern.test(emailInput.value)) {

      emailError.textContent = "Invalid email format";

      document.getElementById("hideDiv").style.display = "none";

    } else {

      emailError.textContent = "";

      document.getElementById("hideDiv").style.display = "block";

    }

    

  }

</script>

                         </div>

   <div class="form-group col-md-12"> Your IP Address :<br>                     

                      <input type="text" name="ip" style="width:100%;height:50px;" value="'.$ip.'" readonly></div>

        <div class="form-group col-md-12">

                         <div id="hideDiv"> <input type="submit" name="submit" style="width:100%;height:50px;background-color:blue;color:white;font-size:30px" value="shorten url"></div></div>

                  </form> ';} ?>

                        <p><br><br>Adquash Short URL service is a free tool to shorten URLs and generate short links

URL shortener allows to create a shortened link making it easy to share<br><br>


<h1>Simple and fast URL shortener!</h1><br>

Adquash Short URL service allows to shorten long links from Instagram, Facebook, YouTube, Twitter, Linked In, WhatsApp, TikTok, blogs and sites. Just paste the long URL and click the Shorten URL button. On the next page, copy the shortened URL and share it on sites, chat and emails. After shortening the URL, check how many clicks it received.


<h1>Shorten, share and track</h1><br>

Your shortened URLs can be used in publications, documents, advertisements, blogs, forums, instant messages, and other locations. Track statistics for your business and projects by monitoring the number of hits from your URL with our click counter.

</center>

<center>

    

<br>

</div>

<div class="col-md-12">

<?php include 'bottomad.php' ; ?>

</div>

            </div></div></div>

    <div class="right-panel"><?php include ("sidebar_right.php"); ?></div>

        <div style="clear:both"></div>

    <div class="footer"><?php include("footer.php");?></div>  

       </body>

    </html>



<---------------------------------------------------------->

<?php 

include "connect.php";

$url = $_SERVER['HTTP_HOST'];

$urlf = str_replace('/','',$_SERVER['REQUEST_URI']);

$hash = str_replace($url,'',$urlf);

$sql = mysqli_fetch_assoc(mysqli_query($connection,"select * from shortener where hash='$hash'"));

if($sql["hash"] == $hash){

    $sqlup = mysqli_query($connection,"UPDATE shortener SET view = view+1 where hash='$hash'");

    echo "<iframe data-aa='479877' src='//acceptable.a-ads.com/479877' style='border:1px solid blue; padding:0; width:100%; height:90px; overflow:hidden; background-color: transparent;'></iframe><br><br>

    <p style='font-size:20px;'>SOME URL NOT WORK IN IFRAME : <a href=".$sql["url"]." style='font-size:20px;background-color:blue;color:white;text-decoration:none;padding:3px;'>OPEN WITHOUT IFRAME</a></p>

    <p style='font-size:28px;font-weight: bold;color:blue;'>Total View : ".$sql["view"]." </p><hr style=height:5px;width:100%;background-color:blue;><br>";

    echo "<iframe src=".$sql["url"]." style='border:0px; padding:0; width:100%; height:100%; overflow:hidden; background-color: transparent;'></iframe>";

    

}else{ echo "link disable or removed";}

?>