New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home Blog Page 3

Whatsapp down: WhatsApp,instagram are down

0

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

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

How to force download file from server-PHP

0

Welcome back to shortlearner.com, today in this post we will see how to force fully download a file from the server with the help of php.
In out previous post we learn how to import csv file into mysql database using php.

download file using php

so first of we need to understand overall scenario before downloading file from the server.
so i was created a image folder in a root directory of my project. there is a image file inside img folder with the name of test.jpg.

now we are writing a code for downloading this test image from the server without showing our img path to our end user because if we show our img folder in url than user can view all our images or files from the directory.

In the below code i am crating a index.php file which having a download button. so whenever user click on that button our download script will run and file will downloaded.

index.php

<!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>
<form method="post" action="#">
<button type="submit" name="download" class="btn btn-sm btn-success">Download File</button>
</form>
</body>
</html>

after click on the submit button we use the below code to download file from remote server to our system.

<?php if(isset($_POST['download'])){
$file = 'img/404.png';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
  }
} ?>

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

Convert Html to PDF using JavaScript

0

Welcome back to shortleatner.com, today in this post we will see how to convert html to pdf with the help of JavaScript. in our last post we will see how to find first and last digit of a number without using any type of loop.

html to pdf

so most of the time we want to download a PDF file of our html view. like one of our reader is working on a POS system and he wants to print the html format bill to a PDF format.

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

Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

in the below code we add the bootstrap and jQuery maxcdn file at head section of our html page.
if you are looking for amazing html and bootstrap snippets than click on the below button for getting free amazing snippets.


Demo

find first and last digit of a number without using loop

0

Welcome back to shortlearner.com, in this post we will see how to write a program to find first and last digit of a number without using any type of loop.

so in the below program we are declaring a php variable $n which will takes the number.
here we are defining 2 php functions which will returns the first and last digit of our $n number.

find first and last digit of a number

the first function is firstNumber which will accept $n as a parameter than we use log10() function.

now we will take an short overview of log10() function. basically log10() is a mathematical function which is defined in math.h header file and it returns log base 10 value of the passed paramater.

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

Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

than we use pow() function. so basically pow() is a predefined function which will return the first number to the power of second number. in other words we can say that it compute power of a certain number. this function takes 2 parameter which are the base and exponent and returns the desired answer.

after using pow() function we will get first digit of our $n number. now we will declare our second function lastNumer which will help us to find out the last digit of $n number.

<?php 
function firstNumber($n) 
{ 
    // Find total number of digits - 1 
    $digits = (int)log10($n); 

    // Find first digit 
    $n = (int)($n / pow(10, $digits)); 

    // Return first digit 
    return $n; 
} 

// Find the last digit 
function lastNumer($n) 
{ 
    // return the last digit 
    return ($n % 10); 
} 

// Define numer  
$n = 58727; 
echo firstNumber($n) , " ", 
    lastNumer($n), "\n"; 

    // our out put is 5 and 7.
?> 

If these article helps you please share it with your developers buddy.
and if you are a web designer and looking for amazing snippets thank click on the below button.

Amazing Snippets

Keep Learning, Keep Coding