automatic close open HTML tags in a string using php

In sometime in your string close tag missing in this case it need to close tag. This function help you

<?php

function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    for ($i=0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            $html .= '</'.$openedtags[$i].'>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

$str = '<div>This is some text<p> and here is a <strong>bold text then the post stop here....';
echo closetags($str);

This is result :

Normal text with missing close tag :
<div>This is some text<p> and here is a <strong>bold text then the post stop here....

Then result is :
<div>This is some text<p> and here is a <strong>bold text then the post stop here....</strong></p></div>

so this function automatic close tag.

Resource from :
https://stackoverflow.com/questions/3810230/close-open-html-tags-in-a-string

if you face any problem then please inform me.

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

Multidimensional array sorting with key value using php

If you want to sorting multidimensional array using php then check this code , hope it will help you.

 <?php
$yourarray = array(
    0 => array(
        'bill_number' => 3,
        'amount' => 100
    ),
    1 => array(
        'bill_number' => 4,
        'amount' => 50
    ),
    2 => array(
        'bill_number' => 5,
        'amount' => 150
    ),
);
 
function sortByOrder($a, $b)
{
    return $a['amount'] - $b['amount'];
}
 
usort($yourarray, 'sortByOrder');
echo "<pre>";
print_r($yourarray);
?>

this code will give this output :

Array
(
    [0] => Array
        (
            [bill_number] => 4
            [amount] => 50
        )
 
    [1] => Array
        (
            [bill_number] => 3
            [amount] => 100
        )
 
    [2] => Array
        (
            [bill_number] => 5
            [amount] => 150
        )
 
)

View 1 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

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 reload page every 5 second or 10 second like this?

For auto reload your page using javascript or simple html and also clear cache when reload your page then you can do it easily using javascript setInterval function. Here is simple code which help you to auto reload your current page


$(document).ready(function() {
  setInterval(function() {
    cache_clear()
  }, 5000);
});

function cache_clear() {
  window.location.reload(true);
  // window.location.reload(); use this if you do not remove cache
}

This is html section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Auto reload page and clear cache</p>

just copy and paste this code your editor then run this in your browser , you can see that your page reload after 5 seconds , you can change value , 5 seconds = 5000ms.

you can also do this using html meta tag . this is also simple hmtl code which help you

<meta http-equiv="Refresh" content="5">
Comment

How to import large files in windows using MySQL’s source command?

There many way you can do that . i will give some options here to import large file using command.

Option 1. You can do this using single cmd. In this cmd D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this. This is for xampp .

 
D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql

This is for wampp

 
D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql

just change your folder and mysql version etc

Option 2. Suppose your current path is which is showing command prompt

 
C:\Users\shafiq;

then change directory using cd.. then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.

 
C:\xampp\mysql\bin;
C:\xampp\mysql\bin\mysql -u {username} -p {database password}.

then please enter when you see enter password in command prompt.
choose database using

 
mysql->use test (where database name test)

then put in source sql in bin folder.

then last command will be

 
mysql-> source test.sql (where test.sql is file name which need to import)

then press enter

This is full command

 
C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
mysql-> use test
mysql->source test.sql
Comment

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

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

Get first character from string php

If you get first character from string using php then you can use some option.

This is simple code which help you.

<?php

//Example string.
$text = "This is demo text for test";

// Option 1 get first character
$option1 = $text[0];

//Option 2 first character
$option2 = substr($text, 0, 1);

// sometime special character not work so use this for first character

$option3 = mb_substr($text, 0, 1);

echo "Result: ". $option1."==".$option2."==".$option3;

then result all is same :

Result: T==T==T

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

Comment