How to upload image using PHP?

Uploading images can be broken down into the three following steps.
  • An HTML form with a browse button to allow the client to choose which file to upload
  • A script to process the upload, validate the file, name it and place it in the file system
  • Lastly, a page to advise the client the upload was a success
Also, we are providing the solution to another most frequently asked question reviewing image before uploading into the folder by javascript.

HTML Code:

<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <style>
            .container{
                position: absolute;
                width: 500px;
                height: 400px;
                top: 30%;
                left: 50%;
                margin: -100px 0 0 -150px;
                background: #80808061;
                color: white;
                border-radius:5px;
            }
            .container-header{
                width: 500px;
                margin-left: -15px;
                height: 40px;
                background: #464646;
                color:white;
                padding:5px;
                font-size:20px;
                text-align:center;
                margin-bottom:40px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }
            #output{
                width:100px;
                height:auto;
                margin-top:20px;
            }
            .btn{
                margin-top:20px;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div class="container-header">
                Select image to upload
            </div>
            <form action="upload.php" method="post" enctype="multipart/form-data" id="form1" runat="server">
                <div class="col-md-12">
                    <input type='file' id="imgInp" name="fileToUpload" accept="image/*" onchange="loadFile(event)" class="form-control"/>
                    <img id="output"/>
                </div>
                <div class="col-md-12">
                    <input type="submit" value="Upload Image" name="submit" class="btn">
                </div>
            </form>
        </div>
    </body>
    <script>
        var loadFile = function (event) {
            var reader = new FileReader();
            reader.onload = function () {
                var output = document.getElementById('output');
                output.src = reader.result;
            };
            reader.readAsDataURL(event.target.files[0]);
        };
    </script>
</html>

PHP Code:
upload.php
<?php

$directory = "uploads/";
$target_file = $directory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image using getimagesize function
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists by using file name
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
Result:
Note:
To access the file you uploaded, you need to store the path of the file in the database table which is very simple to do with basic knowledge.
$target_file is the path variable, you can store this variable value directly in the database by normal insertion query. 

Also, you need to create uploads folder in the root directory.


Simple login form using PHP and MySQL.

The login form is very much essential in every kind of web application so here we are explaining a simple and best way of doing login system. which mainly includes 
1. Connecting to Database
2. Login(Session Start)
3. Logout(Session End)
4. Session Check
5. Login Form
6. CSS

1. Connecting to Database

$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}



2. Login

session_start();
if (isset($_POST['username']) and isset($_POST['password'])) {
   
    $Username = $_POST['username'];
    $Password = $_POST['password'];
    $query = "SELECT * FROM `user` WHERE FirstName='$Username' and Password='$Password'";
    $result = mysqli_query($Connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {
        $_SESSION['username'] = $
Username;
    } else {
        $fmsg = "Invalid Login Credentials.";
    }
}


3. Logout

session_start();
session_destroy();
header('Location: login.php');


4. Session Check

if (isset($_SESSION['username'])) {
    
    echo "<div class='session-box'>";
    echo 'Welcome Mr.'.$Username = $_SESSION['username'];
    echo "<br><a href='logout.php'>Logout</a>";
    echo "</div>";
}else{
    
    echo "<div class='session-box'>";
    echo "You are logged out.";
    echo "</div>";

}

5. Login Form

<form method="POST" class="login-box">

    <div class="form-header">Please Login</div>

    <div class="col-md-12">  
        <label>Username</label>
        <input type="text" name="username" class="form-control" placeholder="Username" required>
    </div>

    <div class="col-md-12">
        <label>Password</label>
        <input type="password" name="password" class="form-control" placeholder="Password" required>
    </div>

    <div class="col-md-6">
        <button class="btn btn-primary" type="submit">Login</button>
    </div>

</form>

6.CSS

 <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <style>
            .login-box{
                position: absolute;
                width: 300px;
                height: 270px;
                z-index: 15;
                top: 50%;
                left: 50%;
                margin: -100px 0 0 -150px;
                border: 1px solid #8080804a;
                border-radius: 5px;
                background: #8080804a;
            }
            .session-box{
                position: absolute;
                width: 300px;
                height: 100px;
                z-index: 15;
                top: 10%;
                left: 50%;
                margin: 0px 0 0 -150px;
                border: 1px solid #8080804a;
                border-radius: 5px;
                background: #8080804a;
                padding: 30px;
            }
            .form-control{
                padding: 10px;
                margin-top: 5px;
            }
            .btn-primary{
                margin-top: 20px;
            }
            .form-header{
                width: 299px;
                height:40px;
                background: #004f61;
                color:white;
                text-align: center;
                font-size: 20px;
                margin-bottom: 20px;
                padding: 5px;
            }
        </style>

    </head>

Create Database Table

CREATE TABLE `user` (
  `UserID` int(12) NOT NULL,
  `FirstName` varchar(48) NOT NULL,
  `LastName` varchar(48) NOT NULL,
  `Email` varchar(128) NOT NULL,
  `Password` varchar(20) NOT NULL,
  `City` varchar(48) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul@zzz.xxx', 'Rahul@123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh@xxx.xxx', 'Mahesh@123', 'Delhi');







Result




How to create a watermark on image using PHP?

Creating a watermark on image using imagecopy function by the PHP

imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )

dst_im
Destination image link resource.
src_im
Source image link resource.
dst_x
x-coordinate of destination point.
dst_y
y-coordinate of destination point.
src_x
x-coordinate of source point.
src_y
y-coordinate of source point.
src_w
Source width.
src_h
Source height.
Sample Code:

<?php
// Load the stamp and the photo to apply the watermark to
//watermark image that you want to see on top of the other image
//image format can be jpeg,png,gif but png is recomnded
$stamp = imagecreatefrompng('stamp.png');
//Base image
$im = imagecreatefromjpeg('test.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_left = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);


// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_left, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/gif');
imagepng($im);
imagedestroy($im);
?>

Images used:





Result:

How to remove class styles dynamically from div?

A simple button to remove class styles from div dynamically.


<!DOCTYPE html>
<html>
<head>
    <style>
        .remStyle {
            width: 50%;
            padding: 25px;
            background-color: #50ff5d;
            color: black;
            font-size: 25px;
            box-sizing: border-box;
        }

        button {
            background-color: #ff7600; 
            border: none;
            color: black;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
        }
    </style>
</head>
<body>

<!--test my blog-->

<button><a href='http://phpjavascript.com'>Try it</a></button>
<button><a href='http://phpjavascript.com'>Home</a></button>

<!--test-->
<button onclick="myFunction()">Try it</button>

<div id="remDIV" class="remStyle">
    Hello World.
</div>

<script>
    function myFunction() {
        var element = document.getElementById("remDIV");
        element.classList.remove("remStyle");
    }
</script>

</body>
</html>

Result



How To Create a Modal Popup Box with HTML, CSS and JavaScript ?

Making a popup is an exceptionally basic expansion to any site page. In this instructional exercise, I will demonstrate to you industry standards to make a popup utilizing essential HTML, Javascript and CSS. You can trigger popup on every time for example mouseover or keypress.

Here is the CSS code, place it in your head section of HTML code.
       
 <!DOCTYPE html>
<html>
<head>
    <style>
        button {
            background-color: #ff7600; 
            border: none;
            color: black;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
        }

        body {
            margin: auto;
            width: 100%;
            padding: 10%;
        }

        .modal {
            display: none; 
            position: fixed; 
            z-index: 1; 
            padding-top: 10%;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }

        .modal-content {
            background-color: #00ffff;
            margin: auto;
            padding: 20px;
            width: 50%;
            height: 30%;
            box-shadow: 3px 5px #88888882;
        }

        .modal-text {
            padding: 80px;
            font-size: 22px;
        }

        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body>

<!-- Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
        <span class="close">&times;</span>
        <div class="modal-text">
            <p>Hello World! Fallow PHPJavascript.com.</p>
        </div>
    </div>

</div>

<script>
var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function () {
modal.style.display = "block";
    }

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
    }

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
        }
    }
</script>

</body>
</html>
Result:



Google Stacked column charts

You can create a stacked column chart by setting isStacked option true in the normal column chart code. 
Here we are explaining the simple example.

Html Code

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses', 'Profit'],
          ['2014', 1000, 400, 200],
          ['2015', 1170, 460, 250],
          ['2016', 660, 1120, 300],
        ]);

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
          },
          isStacked:true,
  colors:['orange'],
        };

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    </script>
  </head>
  <body>
    <div id="columnchart_material" style="width: 800px; height: 500px;"></div>
  </body>
</html>

Result

Google Column Charts with PHP and MySQL

Populating column charts with google api is one of the simplest way to do. here we are showing 
you a simple example to generate column chart with real time data. fetching data from database table.

Here is the sample code.
PHP Code: Includes connecting to database and fetching data from database table.
<?php 
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$selectsql = "SELECT * FROM graph";
$result = mysqli_query($Connection, $selectsql);    
?>
HTML and Javascript code uses the data from database fetched by php code and google api
to populate column chart
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses', 'Profit'],
    <?php while($row = mysqli_fetch_array($result)){ ?>
          ['<?php echo $row['name'];?>', 
    <?php echo $row['value1'];?>, 
    <?php echo $row['value2'];?>, 
    <?php echo $row['value3'];?>],
    <?php } ?>
        ]);

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
          },
      
        };

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    </script>
  </head>
  <body>
    <div id="columnchart_material" style="width: 800px; height: 500px;"></div>
  </body>
</html>

Run these queries in your database.
CREATE TABLE `graph` (
  `id` int(2) NOT NULL,
  `name` varchar(34) NOT NULL,
  `value1` int(12) NOT NULL,
  `value2` int(12) NOT NULL,
  `value3` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `graph` (`id`, `name`, `value1`, `value2`, `value3`) VALUES
(1, '2014', 11, 2, 7),
(2, '2015', 2, 5, 9),
(4, '2016', 20, 9, 15),
(5, '2017', 14, 21, 5),
(6, '2018', 7, 17, 6);
Result

Everything about column chart


Google Pie Charts with PHP and MySQL
Everything about google pie chart

Everything about google column chart

column chart is a graphical representation of data. Where column chart displays data as vertical bars. Here we are showing a simple example of column chart with the help of Google API.

The below column chart represents the company performance in the last five years. Representing years on the x-axis and performance count on the y-axis.

Here is the sample code

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses', 'Profit'],
          ['2014', 1000, 400, 200],
          ['2015', 1170, 460, 250],
          ['2016', 660, 1120, 300],
          ['2017', 1030, 540, 350],
          ['2018', 1000, 500, 300]
        ]);

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
          }
        };

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    </script>
  </head>
  <body>
    <div id="columnchart_material" style="width: 800px; height: 500px;"></div>
  </body>
</html>

Add these lines to your options variable

1. For 3D model pie chart.
is3D: true,

2. Adding background to pie chart
backgroundColor: 'skyblue',

3. Change title text color and size
titleTextStyle: { color: 'red', fontSize:16},

4. Change colors of column bars
colors: ['#e0440e', '#e6693e', '#ec8f6e'],

5. Change bar width
bar: {groupWidth: '50%'},

Result

Google Pie Charts with PHP and MySQL

Populating pie charts with google api is one of the simplest way to do. here we are showing 
you a simple example to generate pie chart with real time data. fetching data from database table.
<?php
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, 
    $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$selectsql = "SELECT * FROM graph";
$result = mysqli_query($Connection, $selectsql);
?>

<html>
<head>
    <script type="text/javascript" 
            src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {

          var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          <?php while($row = mysqli_fetch_array($result)){  ?>
             ["<?php echo $row['name']; ?>", <?php echo $row['count']; ?>],
          <?php } ?>
          ]);

         var options = {
           title: 'My Daily Activities'
            };

         var chart = new google.visualization.PieChart
         (document.getElementById('piechart'));

         chart.draw(data, options);
        }
    </script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Run these queries in your database.
//Table structure for table `graph`
CREATE TABLE `graph` (
  `id` int(2) NOT NULL,
  `name` varchar(34) NOT NULL,
  `count` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

//Dumping data for table `graph`

INSERT INTO `graph` (`id`, `name`, `count`) VALUES
(1, 'Work', 11),
(2, 'Eat', 2),
(4, 'Commute', 2),
(5, 'Watch TV', 2),
(6, 'Sleep', 7);
Result:

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts