Month: January 2018

How to download any type of file,image,pdf using PHP Script?

If you want to add a download link. When click this link then any type of file,image, pdf will be download.You can do this using a simple php script. Yon can follow this code

First Create a simple html file where you want to add download link.

<a href="download.php?file=techpark_photo.jpg">Download</a>

i want to download a picture name “techpark_photo.jpg” so parameter is file name “techpark_photo.jpg”.

Then create a php file name “download.php” which you use in above file.

<?php
$file = $_GET["file"];
 
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?

Important thing is that picture and script same folder if you change this then you can use your folder directory.

If you face any problem then please inform me, i will try to help you.

Comment

get all images from a specified directory then display them using php

If you want to get all image from a folder then display then in your website or other place using php then you can use this code .
1. Suppose your image folder name “images” then put some image in this folder.
2. Copy this code and paste it your in editor then you can see image list from images folder. This is php code which also check image type cause in your folder if have pdf type or other type

<?php
     $files = glob("images/*.*");
     for ($i=0; $i<count($files); $i++)
      {
        $image = $files[$i];
        $supported_file = array(
                'gif',
                'jpg',
                'jpeg',
                'png'
         );

         $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
         if (in_array($ext, $supported_file)) {
            echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
             echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
            } else {
                continue;
            }
          }
       ?>

then run this file in your browser then you can see image and if you do not check image type then this is change code

<?php
$files = glob("images/*.*");
for ($i = 0; $i < count($files); $i++) {
    $image = $files[$i];
    echo basename($image) . "<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="' . $image . '" alt="Random image" />' . "<br /><br />";

}
?>
View 2 Comments

How to check div is hide or show using jQuery?

If you want to check that div is block(visible) or none then you can do this very easily . Suppose your div id = “test” -> for testing purpose if you use class = “test” then need to update code For checking Block or visible then use this for your select test is ID . This is simple code

1. if ($('#test').is(':visible')) {}

2. if ($('#test').css('display') == 'block'){}

3. if ($('#test').not(':hidden')){}

if you want to check this using class name

1. if ($('.test').is(':visible')) {}
2. if ($(your_element).is(':visible')) {}

This is other option for checking none or hide then use this code if your selector is id

1. if ($('#test').not(':visible')){}

2. if (!$('#test').is(':visible')){}

3. if ($('#test').css('display') == 'none'){}

4. if ($('#test').is(':hidden')){}

if you use class name then code is

1. if ($('.test').not(':visible')){}
2. if ($(your_element).not(':visible')){}

hop e it will help you. if you have face any problem then inform me.

Comment

Mobile phone validation using javascript or jQuery

For mobile number validation you can use regular expression which give you best output . This is javascript code which check mobile number valid or not.

<html>
<head>
    <title>Mobile number validation using regex</title>
    <script type="text/javascript">
        function validate() {
            var mobile = document.getElementById("mobile").value;
            var pattern = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
            if (pattern.test(mobile)) {
                alert("Your mobile number : "+mobile);
                return true;
            }
            alert("It is not valid mobile number");
            return false;

        }
    </script>

</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

and you can also jQuery for mobile number validation , this is simple code

<html>
<head>

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <title>Mobile number validation using regex</title>
    <script type="text/javascript">
        function validate() {
            var mobile = $("#mobile").val();
            var pattern = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
            if (pattern.test(mobile)) {
                alert("Your mobile number : " + mobile);
                return true;
            }
            alert("It is not valid mobile number");
            return false;

        }
    </script>

</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile"/>
<input type="submit" value="Check" onclick="validate();"/>
</body>
</html>

If you face any problem then please inform me.

Comment

How to sum array values using php?

If you get all value from php array then you can use foreach. This is simple code which sum all value then give final result and also get average value .

<?php
// as of PHP 5.4
$ratings = [
    0 => ['rating' => 5],
    1 => ['rating' => 10],
    2 => ['rating' => 15],
    3 => ['rating' => 20],
    4 => ['rating' => 25],
];

$array_length = count($ratings); // array length
$final_result = 0;
$sum = 0; // this is store all sum value so first assign 0
foreach ($ratings as $ratingss) {
    $sum += $ratingss['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo "Total Sum:".$sum ."<br>"; // this is final value
echo "Average:".$final_result = $sum / $array_length; // this is your desire result

?>

this is simple procedure got get all sum from php array.If you face any problem then please inform me.

Comment

How to update session variable from dropdown change?

If you want to update your value like when drop down change then this value will set in php session in this case you can use ajax which help you lot. This is simple code which update session value when change drop down change .

This is total html and php code which need to update and browse data

<?php
session_start(); // for show your session value 
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">

    <table>
        <tr>
            <td style="width:272px;">
                <select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
                    <option value="0">select a listing type</option>
                    <option value="10">Premium Listings</option>
                    <option value="20">Premium Blogs</option>
                    <option value="30">1 week sticky</option>
                </select></td>

            <td style="text-align:left;color:gray;">
                <span style="color:crimson;">*
            </span>Select a listing type
            </td>
        </tr>
    </table>
    <input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">

</form>

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {

            }
        });
    }

</script>

Then create php file which update session value

<?php
session_start();
if( isset($_POST['select_amount']) ) {
    // save values from other page to session
    $_SESSION['amount'] = $_POST['select_amount'];

}
?>

For test you can refresh the page and check output or ajax function update this code

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {
 window.location.reload;
            }
        });
    }

</script>

if you face any problem then please inform me, I will try to help you

Comment

How to add and remove attribute with jquery?

If you want to add and remove attribute using jquery then you can check this code. It will remove id and then when click remove then this id will remove. I also add css for understanding it.

This is html and css code


<div id="page_navigation1" style="border: 2px solid #ccc;height: 70px;width: 300px">Main Content</div>
<button id="add">Add</button>
<button id="remove">Remove</button>

This is css code

<style>
    #page_navigation1 {
        color: red;
    }
</style>

This is jQuery code which add and remove attribute

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#page_navigation1").addClass("page_navigation");

        $("#add").click(function(){
            $(".page_navigation").attr("id","page_navigation1");
        });
        $("#remove").click(function(){
            $(".page_navigation").removeAttr("id");
        });
    });
</script>

When run this code you will see this effect, If you find any problem then please inform me.

Comment

How to read child elements of XML using php?

If you want to get child elements from xml using php then you can use this code which help you to get child elements and some other options. This is simple demo code which help you. In this code first get child elements data then also child of child data. Just parse data using php simplexml_load_string function.

<?php
$string = <<<XML
<ORDERSTATUS>
    <DATE>23/01/18</DATE>
    <INVOICE>Test Data</INVOICE>
    <INVTOTAL Tax="25.00" Freight="28" SubTotal="80.00">100.0</INVTOTAL>
</ORDERSTATUS>
XML;

$xml = simplexml_load_string($string);

echo "DATE:".$xml->DATE."<br>";
echo "INVOICE:".$xml->INVOICE ."<br>";
echo "INVTOTAL:".$xml->INVTOTAL ."<br>";
echo  "Tax:".$xml->INVTOTAL->attributes()->Tax."<br>";
echo  "Freight:".$xml->INVTOTAL->attributes()->Freight."<br>";
echo  "SubTotal:".$xml->INVTOTAL->attributes()->SubTotal."<br>";

this code give you first child elements then also child of child elements . This is output this code

DATE:23/01/18
INVOICE:Test Data
INVTOTAL:100.0
Tax:25.00
Freight:28
SubTotal:80.00

If you face any problem then please inform me. I will try to help you.

Comment

How to rotate image and save new image using PHP ?

If you want to rotate image then save rotate image then you can use this simple php code.

<?php
$image = 'test.jpg';
 
// The file you are rotating
 
//How many degrees you wish to rotate
$degrees = 180;
 
// This sets the image type to .jpg but can be changed to png or gif
header('Content-type: image/jpeg') ;
 
// Create the canvas
$src = $image;
$system = explode(".", $src);
 
if (preg_match("/jpg|jpeg/", $system[1]))
{
$src_img=imagecreatefromjpeg($src);
}
if (preg_match("/png/", $system[1]))
{
$src_img = imagecreatefrompng($src);
}
if (preg_match("/gif/", $system[1]))
{
$src_img = imagecreatefromgif($src);
}
 
// Rotates the image
$rotate = imagerotate($src_img, $degrees, 0) ;
 
// Outputs a jpg image, you could change this to gif or png if needed
if (preg_match("/png/", $system[1]))
{
imagepng($rotate,$image);
}
else if (preg_match("/gif/", $system[1]))
{
imagegif($rotate, $image);
}
else
{
imagejpeg($rotate, $image);
}
 
imagedestroy($rotate);
imagedestroy($src_img);
 
?>

If you face any problem then please inform me. I will try to help you.

Comment

How to check if all inputs are not empty with jQuery?

If you want to check that all input fields not empty or any field empty then give error and show error message. You can do this easily using jQuery . This is simple code you can test it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
    textarea{height:auto;}
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
    select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
    select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
    .uneditable-textarea{width:auto;height:auto;}
    #country{height: 30px;}
	.highlight
	{
		border: 1px solid red !important;
	}
</style>
<script>
function test()
{
 var isFormValid = true;

    $(".bs-example input").each(function(){
        if ($.trim($(this).val()).length == 0){
		    $(this).addClass("highlight");
            isFormValid = false;
			$(this).focus();
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) { 
		alert("Please fill in all the required fields (indicated by *)");
	}

    return isFormValid;
}	
</script>
</head>
<body>
<div class="bs-example">
    <form onsubmit="return test()">
        <div class="form-group">
            <label for="inputEmail">Email</label>
            <input type="text" class="form-control" id="inputEmail" placeholder="Email">
        </div>
        <div class="form-group">
            <label for="inputPassword">Password</label>
            <input type="password" class="form-control" id="inputPassword" placeholder="Password">
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
    </form>
</div>
</body>
</html>   

If you face any problem then please inform me.

Comment