Home Blog Page 2

Get user’s current location based on IP

0
Get user current location based on IP

Welcome back to shortlearner.com, in this post today we will see how to find user’s location with having their IP address. so most of the time we need to access the user’s location to analysis the location wise client base.
In the below PHP script first of all we will fetch the user’s IP address by using pre-defined PHP function and store the IP address in a $ip_address variable.


so simply we will pass this IP address to our third party platform that will return as a JSON array that having country, country code, state, city , zip, time zone, longitude and latitude as well.
here we are performing this task with the help of curl functionality.

Get user current location based on IP
<?php
$ip_address = $_SERVER['REMOTE_ADDR'];
$url = "http://ip-api.com/json/$ip_address";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$arr_result = json_decode($response);
echo($response);
 ?>

so we got this JSON response.

 {"status":"success",
 "country":"United States",
 "countryCode":"US",
 "region":"MA",
 "regionName":"Massachusetts",
 "city":"Boston",
 "zip":"02110",
 "lat":42.358,
 "lon":-71.0526,
 "timezone":"America/New_York",
 "isp":"Leaseweb USA",
 "org":"Cooley, Manion, Moore \u0026 Jones, LLP","as":"AS30633 Leaseweb USA, Inc.",
 "query":"207.244.89.166"
}

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript

how to Calculate age from dob using php

0
calculate age from dob

Welcome back to shortlearner.com , today in this post we will see how to find the age of the user on the basis of their date of birth.
so we are going to write a program in php that will help us to calculate age.

calculate age from dob
<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>

in the below program we are declared a variable $birthDate with having a date in mm/dd/yyyy format. after that we are using predefined php function explode(), so with the help of that function we will explode the date to get month ,date and year as well. after that we will calculate the age of user on the basis of user’s date of birth and current date.

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript

How to use CKEditor as form input?

0
ckeditor complete code

Welcome back to shortlearner.com, today in this post we will see how to integrate ckeditor in our web based projects.
so before start the integration we should take an small overview and knowing the amazing benefits and features of CKeditor.
most of the time we need an editor that will help us to bold, italic and underline the paragraph and also help us to upload multiple images with in the paragraph.

ckeditor complete code

Amazing Features

  • Applying Styles to Editor Content
  • Applying Block-Level Text Formats
  • Basic Text Styles: Bold, Italic and More
  • HTML Output Formatting
  • Inserting Code Snippets
  • Pasting Content from Microsoft Word
  • Removing Text Formatting
  • Setting Text and Background Color
  • Source Code Editing
  • Table Creation
  • Using the Copy Formatting Feature

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to Integrate

It is very easy to implement the features of CK Editor in our web application.
just follow the below steps

step1
Add this CKeditor JavaScript file at head section of our web page

<script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>

Step2
Now we will add our textarea tag and a small lines of JavaScript code.

<textarea name="editor1"></textarea>
 <script>
     CKEDITOR.replace( 'editor1' );
 </script>

Complete Code


 <html>
     <head>
   <meta charset="utf-8">
    <title>CKEditor Tutorial by shortlearner.com</title>
  <script src="https://cdn.ckeditor.com/4.8.0/standard/ckeditor.js"></script>
    </head>
   <body>
  <textarea name="editor1"></textarea>

  <script>
    CKEDITOR.replace( 'editor1' );
  </script>
   </body>
</html>

Demo

Whatsapp down: WhatsApp,instagram are down

0
Whatsapp down news

Many are unable to log in or use the series of apps.

Website, Down Dectector shows issues with all the apps around the world

A number of problems have been reported with the apps.

Instagram is showing a server error while Facebook also has an error for users trying to login. 

How to upload form data and image file using Ajax

0
upload image with ajax php

Welcome back to shortlearner.com, today in this post we will see how to store user information and photo into MySQL database using Ajax JQuery and PHP. in our previous post we learn how to force fully download a file from the server with the help of php.

upload image with ajax php

so before start this tutorial we should take an overview of the scenario of the post.
we are designing a responsive signup form with username, email and multiple file options with the help of HTML, CSS and Bootstrap.

<!DOCTYPE html>
<html>
<head>
  <title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Status message -->
<div class="statusMsg"></div>

<!-- File upload form -->
<div class="col-lg-12">
    <form id="fupForm" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
        </div>
        <div class="form-group">
            <label for="file">Files</label>
            <input type="file" class="form-control" id="file" name="files[]" multiple />
        </div>
        <input type="submit" name="submit" class="btn btn-success submitBtn" value="SUBMIT"/>
    </form>
</div>
</body>
</html>


after submission of the form we will call a AJAX request with the help of JQuery, and we will send all the form information into our signup.php.

<script>
$(document).ready(function(){
    // Submit form data via Ajax
    $("#fupForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'signup.php',
            data: new FormData(this),
            dataType: 'json',
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#fupForm').css("opacity",".5");
            },
            success: function(response){
              alert(response);
                $('.statusMsg').html('');
                if(response.status == 1){
                    $('#fupForm')[0].reset();
                    $('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
                }else{
                    $('.statusMsg').html('<p class="alert alert-danger">'+response.message+'</p>');
                }
                $('#fupForm').css("opacity","");
                $(".submitBtn").removeAttr("disabled");
            }
        });
    });
  
    // File type validation
    var match = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'image/jpeg', 'image/png', 'image/jpg'];
    $("#file").change(function() {
        for(i=0;i<this.files.length;i++){
            var file = this.files[i];
            var fileType = file.type;
      
            if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
                alert('Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.');
                $("#file").val('');
                return false;
            }
        }
    });
});
</script>

in signup.php we will creating a database connection and also validate the form data and file’s extension as well.

if file extension will pdf,JPG,JPEG and png than it will allow for further request otherwise the error will show on the user’s screen.

<?php 
$db = mysqli_connect("localhost","root","rootroot","rk200");
$uploadDir = 'img/'; 
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png','PNG', 'jpeg'); 
$response = array( 
    'status' => 0, 
    'message' => 'Form submission failed, please try again.' 
); 
// If form is submitted 
$errMsg = ''; 
$valid = 1; 
if(isset($_POST['name']) || isset($_POST['email']) || isset($_POST['files'])){ 
    // Get the submitted form data 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $filesArr = $_FILES["files"]; 
     
      $uploadStatus = 1; 
        $fileNames = array_filter($filesArr['name']); 
         
        // Upload file 
        $uploadedFile = ''; 
        if(!empty($fileNames)){  
            foreach($filesArr['name'] as $key=>$val){  
                // File upload path  
                $fileName = rand(5000,6000).basename($filesArr['name'][$key]);  
                $targetFilePath = $uploadDir . $fileName;  
                  
                // Check whether file type is valid  
                $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);  
                if(in_array($fileType, $allowTypes)){  
                    // Upload file to server  
                    if(move_uploaded_file($filesArr["tmp_name"][$key], $targetFilePath)){  
                        $uploadedFile .= $fileName.','; 
                    }else{  
                        $uploadStatus = 0; 
                        $response['message'] = 'Sorry, there was an error uploading your file.'; 
                    }  
                }else{  
                    $uploadStatus = 0; 
                    $response['message'] = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.'; 
                }  
            }  
        } 
         
        if($uploadStatus == 1){ 
            // Include the database config file 
            // Insert form data in the database 
            $uploadedFileStr = trim($uploadedFile, ','); 
            $insert = $db->query("INSERT INTO user2 (username,email,password,img) VALUES ('".$name."','123456','".$email."', '".$uploadedFileStr."')"); 
             
            if($insert){ 
                $response['status'] = 1; 
                $response['message'] = 'Form data submitted successfully!'; 
            } 
        } 
} 
 
// Return response 
echo json_encode($response);
?>

If user upload multiple files than we use foreach loop and check extension of each and every file and convert there into a unique name via using predefined PHP rand() function.

now after that process we will simply move all the files into our defined path and Insert all the data into database applying insert query and store all the data into our user table.

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript