Category: PHP

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

     $files = glob("images/*.*");
     for ($i=0; $i<count($files); $i++)
        $image = $files[$i];
        $supported_file = array(

         $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 {

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

$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.

$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>";

this code will give this output :

    [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 .

// 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.


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.

$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));

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.


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.


//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


select rows and ignore row if column value is blank or null in MySQL

For many case we need to select all row value and ignore if column value is null or empty in MYSQL , in this case you can do this easily . This is simple code which help you.

Option 1 :

You need to check that column value empty or null

SELECT * FROM your_table where column_name IS NOT NULL or column_name != ''; // column_name is your field name

Option 2 :

You could use COALESCE() to treat blank (empty string) and NULL as the same thing:

SELECT * FROM your_table WHERE COALESCE(column_name, '') != '';

you can also do this in your php code section .

Option 3 :

$column_name = $row_Recordset1['column_name'];
if($column_name == '' || $column_name === null || is_null($column_name)){

if you need any help then please inform me, i will try to help you


Get first key from associative array ?

If you need to get first index or key from array then you can use simple php function key. This is simple code which give you first key from array.

$data = array(
    14 => "Test14",
    11 => "Test11",
    4 => "Test4",
    12 => "Test12",
    13 => "Test13");
echo "<pre>";
reset($data); // reset — Set the internal pointer of an array to its first element
$first_key = key($data); //key — Fetch a key from an array
echo "First Key: ".$first_key;

then result is:

    [14] => Test14
    [11] => Test11
    [4] => Test4
    [12] => Test12
    [13] => Test13
First Key: 14

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


php intval sometime decrease result

If you want to divide value need result as int then normally we use intval function but some case it give wrong result. This is simple code which result wrong

echo  intval(69.6  / .1);

Then final result is :

 Result :695 // which is wrong 
 Result will be : 696

so in this case first we need to make round value result then convert int, this is demo code which will work

echo  intval(round(69.6  / .1),2);

then the result is :

Result is : 696 // which is correct

So if you divide something then need result as int then use round function


How to get next immediate same date using php?

Suppose you need some condition for get next date like
1. Current date is 13-02-2018 , in this case you need to get immediate date like if you select date is 10 then output will be 10-03-2018 cause select date already passed
2. if you select 15 then output will be 15-02-2018 cause this date future date
3. final if you select previous date of current month then output will be next month same date and if you select future date of current month then output will be same month.

This is simple php code which give you correct result

$input = 12;
$day = date("d");

if ($input > $day){
    $date = date("Y-m-"). str_pad($input,2,"0", STR_PAD_LEFT);

    $date = date("Y-m-",strtotime("+1 month")). str_pad($input,2,"0", STR_PAD_LEFT);

echo $date;

If you run this code then output is :

then result is : 2018-03-12 cause you select date which already passed
if you set $input = 15; then result is: 2018-02-15 cause you select future date which not pass

Create simple pagination using PHP and MySQLi

In your website page when we want to show data list then maximum time we need pagination for better understand. We can do that using php and mysqli. For this case just follow this instruction. First we need to create a table so first create database name “pagination” then run this sql in your phpmyadmin.

  `userid` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `username` varchar(30) NOT NULL

INSERT INTO `user` (`userid`, `firstname`, `lastname`, `username`) VALUES
(1, 'First1', 'Last1', 'test1'),
(2, 'First2', 'Last2', 'test2'),
(3, 'First3', 'Last3', 'test3'),
(4, 'First4', 'Last4', 'test4'),
(5, 'First5', 'Last5', 'test5'),
(6, 'First6', 'Last6', 'test6'),
(7, 'First7', 'Last7', 'test7'),
(8, 'First8', 'Last8', 'test8'),
(9, 'First9', 'Last9', 'test9'),
(10, 'First10', 'Last10', 'test10'),
(11, 'First11', 'Last11', 'test11'),
(12, 'First12', 'Last12', 'test12'),
(13, 'First13', 'Last13', 'test13'),
(14, 'First14', 'Last14', 'test14');

  ADD PRIMARY KEY (`userid`);


I just add some demo data for list . Then create a database connection file name “db.php“. Add this code in db.php


$conn = mysqli_connect("localhost","root","","pagination");
if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());

then create main page index.php which page show content

<?php include('pagination.php'); ?>
<!DOCTYPE html>
	<link rel="stylesheet" href="" />
	<script src=""></script>
<div class="container">
	<div style="height: 20px;"></div>
	<div class="row">
	<div class="col-lg-2">
	<div class="col-lg-8">
	<table width="80%" class="table table-striped table-bordered table-hover">
			while($crow = mysqli_fetch_array($nquery)){
					<td><?php echo $crow['userid']; ?></td>
					<td><?php echo $crow['firstname']; ?></td>
					<td><?php echo $crow['lastname']; ?></td>
					<td><?php echo $crow['username']; ?></td>
	<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
	<div class="col-lg-2">

then this is pagination page which manage pagination list .


	$query=mysqli_query($conn,"select count(userid) from `user`");
	$row = mysqli_fetch_row($query);

	$rows = $row[0];
	$page_rows = 5; // change how many row show every page

	$last = ceil($rows/$page_rows);

	if($last < 1){
		$last = 1;

	$pagenum = 1;

		$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);

	if ($pagenum < 1) { 
		$pagenum = 1; 
	else if ($pagenum > $last) { 
		$pagenum = $last; 

	$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
	$nquery=mysqli_query($conn,"select * from `user` $limit");

	$paginationCtrls = '';

	if($last != 1){
	if ($pagenum > 1) {
        $previous = $pagenum - 1;
		$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'" class="btn btn-default">Pre</a> &nbsp; &nbsp; ';
		for($i = $pagenum-4; $i < $pagenum; $i++){
			if($i > 0){
		        $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
	$paginationCtrls .= ''.$pagenum.' &nbsp; ';
	for($i = $pagenum+1; $i <= $last; $i++){
		$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
		if($i >= $pagenum+4){

    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= ' &nbsp; &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'" class="btn btn-default">Next</a> ';


then browse your index.php page then you will show list using pagination. This is simple demo content

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

Credit :