Category: PHP

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);
}else{

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

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.


CREATE TABLE `user` (
  `userid` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `username` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


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


ALTER TABLE `user`
  ADD PRIMARY KEY (`userid`);


ALTER TABLE `user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;


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

<?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>
<html>
<head>
	<link rel="stylesheet" href="http://techparkbd.com/subdomain/source_file/bootstrap.min.css" />
	<script src="http://techparkbd.com/subdomain/source_file/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<div style="height: 20px;"></div>
	<div class="row">
	<div class="col-lg-2">
	</div>
	<div class="col-lg-8">
	<table width="80%" class="table table-striped table-bordered table-hover">
		<thead>
			<th>UserID</th>
			<th>Firstname</th>
			<th>Lastname</th>
			<th>Username</th>
		</thead>
		<tbody>
		<?php
			while($crow = mysqli_fetch_array($nquery)){
			?>
				<tr>
					<td><?php echo $crow['userid']; ?></td>
					<td><?php echo $crow['firstname']; ?></td>
					<td><?php echo $crow['lastname']; ?></td>
					<td><?php echo $crow['username']; ?></td>
				</tr>
			<?php
			}		
		?>
		</tbody>
	</table>
	<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
	</div>
	<div class="col-lg-2">
	</div>
	</div>
</div>
</body>
</html>

then this is pagination page which manage pagination list .

<?php

	include("db.php");
	
	$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;

	if(isset($_GET['pn'])){
		$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){
			break;
		}
	}

    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 : https://www.sourcecodester.com/

Comment

How to create a simple Captcha using php

Captcha is very important for form validation and other related type. This tutorial teaches you how to create and add a simple but powerful Anti-Spam Captcha to your system or application using PHP.

A good way to avoid automatic form submissions when creating a web form or to prevent automated web robot tools and spammers from taking advantage of your forms and scripts is to use some kind of verification process.

This is simple php code which create Captcha . First create a view file where form will be show

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-7">
    <input  type="text" placeholder="Enter Code" id="captcha"
           name="captcha"  value="" style="vertical-align: super;">
    <img src="http://localhost/captcha.php" class="imgcaptcha" alt="captcha" style="vertical-align: bottom"/>
    <img src="http://techparkbd.com/subdomain/source_file/refresh.png" alt="reload" class="refresh"/>
</div>

<script>
    $(".refresh").click(function () {
        $(".imgcaptcha").attr("src", "http://localhost/captcha.php?_=" + ((new Date()).getTime()));

    });

</script>

After this create a php file which generate captcha.

<?php
	
session_start();

function getRandomWord($len = 5) {
    $word = array_merge(range('0', '9'), range('A', 'Z'));
    shuffle($word);
    return substr(implode($word), 0, $len);
}

$ranStr = !empty($_SESSION["vercode_signup"]) ? $_SESSION["vercode_signup"] : getRandomWord();
$_SESSION["vercode"] = $ranStr;
unset($_SESSION["vercode_signup"]);

$height = 35; //CAPTCHA image height
$width = 150; //CAPTCHA image width
$font_size = 24; 

$image_p = imagecreate($width, $height);
$graybg = imagecolorallocate($image_p, 245, 245, 245);
$textcolor = imagecolorallocate($image_p, 34, 34, 34);

imagefttext($image_p, $font_size, -2, 15, 26, $textcolor, 'http://techparkbd.com/subdomain/source_file/mono.ttf', $ranStr);
//imagestring($image_p, $font_size, 5, 3, $ranStr, $white);
imagepng($image_p);

	
?>

It will show captcha and when refresh then generate new code. If you face any problem then please inform me.

Comment

Dynamic Drag and Drop using PHP & mysql and jQuery

This is very common feature that items list need to drag and drop and save it. Drag’n drop generally looks hard-to-apply but it is definitely not by using JavaScript frameworks. In this article i will show how the drag’n drop & saving the new positions to the database Will be working”. This is very simple process you can apply it. This is simple code which you can check

First create a simple database Suppose “drag” . Here is the code for create a table then run this code in mysql

CREATE TABLE `records` (
 `recordID` int(11) NOT NULL auto_increment,
 `recordText` varchar(255) default NULL,
 `recordListingID` int(11) default NULL,
 PRIMARY KEY (`recordID`)
 );
 
INSERT INTO `records` VALUES ('1', 'Once dropped, an Ajax query is activated', '3');
 INSERT INTO `records` VALUES ('2', 'Dragging changes the opacity of the item', '2');
 INSERT INTO `records` VALUES ('3', 'Returned array can be found at the right', '1');
 INSERT INTO `records` VALUES ('4', 'It is very very easy', '4');

The most important column in the database is recordListingID which shows us the order of the records.

Then create a php page which ready mysql connect .

<?php
/*
* Author : Ali Aboussebaba
* Email : bewebdeveloper@gmail.com
* Website : http://www.bewebdeveloper.com
* Subject : Dynamic Drag and Drop with jQuery and PHP
*/

// PDO connect *********
function connect() {
	$host = 'localhost';
	$db_name = 'drag';
	$db_user = 'root';
	$db_password = '';
    return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
?>

Then create index.php which is the main page to view list

<!DOCTYPE>
<html>
<?php
include('config.php');
$pdo = connect();
$sql = 'SELECT * FROM records ORDER BY recordListingID ASC';
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();

?>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery Dynamic Drag'n Drop</title>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-ui-1.10.4.custom.min.js"></script>

    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            margin-top: 10px;
        }

        ul {
            margin: 0;
        }

        #contentWrap {
            width: 700px;
            margin: 0 auto;
            height: auto;
            overflow: hidden;
        }

        #contentTop {
            width: 600px;
            padding: 10px;
            margin-left: 30px;
        }

        #contentLeft {
            float: left;
            width: 400px;
        }

        #contentLeft li {
            list-style: none;
            margin: 0 0 4px 0;
            padding: 10px;
            background-color:#00CCCC;
            border: #CCCCCC solid 1px;
            color:#fff;
        }

        #contentRight {
            float: right;
            width: 260px;
            padding:10px;
            background-color:#336600;
            color:#FFFFFF;
        }

    </style>
    <script type="text/javascript">
        $(document).ready(function(){

            $(function() {
                $("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
                    var order = $(this).sortable("serialize");
                    $.ajax({
                        url: 'http://localhost/updatelist.php?action=updateRecordsListings',
                        type: 'POST',
                        data: order,
                        success: function (result) {
                            $("#contentRight").html(result);
                        }
                    });
                }
                });
            });

        });
    </script>

</head>
<body>

<div id="contentWrap">
    <div id="contentLeft">
        <ul>
            <?php
            foreach ($list as $rs) {
                ?>
                <li id="recordsArray_<?=$rs['recordID']?>"><?=$rs['recordText']?></li>
                <?php
            }
            ?>
        </ul>
    </div>

    <div id="contentRight">
        <p>New List will be displayed here.</p>
        <p>&nbsp; </p>
    </div>

</div>

</body>
</html>


After posting the array of “new order of the items” to updatelist.php, we must run a query to update our database that will reflect the last positions of every item:

<?php
include('config.php');
$pdo = connect();

$action = $_GET['action'];
$updateRecordsArray = $_POST['recordsArray'];

if ($action == "updateRecordsListings"){

    $listingCounter = 1;
    foreach ($updateRecordsArray as $recordIDValue) {

        $query = "UPDATE records SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
        $query = $pdo->prepare($query);
        $query->execute();
        $listingCounter = $listingCounter + 1;
    }

    echo '<pre>';
    print_r($updateRecordsArray);
    echo '</pre>';
    echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

all done so run index.php and drag list , it will automatically save drag list and after refresh it will show new list

This is example output


this is output

Comment

How to check port is open and not open using PHP?

Sometime this is need to know that some port is active or not cause a port is used to recognize a specific service which is being executed in a computer. To recognize a port and to send packets, 16 bit numbers known as port numbers are used. A port number along with IP address serves as a destination for packets to be sent.

Suppose domain name https://techparkbd.com/ so get this ip address so ip is 184.107.37.81. There are many website to know ip. Then check port that open or not.

<?php
$host_connection = '184.107.37.81'; // techparkbd
$ports_number = array(21, 25, 80, 81, 110,143, 443, 3306); //checking port number

foreach ($ports_number as $port)
{
    $connection_check = @fsockopen($host_connection, $port);

    if (is_resource($connection_check))
    {
        echo '<h5>' . $host_connection . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open now.</h5>' . "\n";

        fclose($connection_check);
    }

    else
    {
        echo '<h5 style="color: red">' . $host_connection . ':' . $port . ' is not open now.</h5>' . "\n";
    }
}

?>

when you run this code it will show result like this

184.107.37.81:21 (ftp) is open now.
184.107.37.81:25 (smtp) is open now.
184.107.37.81:80 (http) is open now.
184.107.37.81:81 is not open now.
184.107.37.81:110 (pop3) is open now.
184.107.37.81:143 (imap) is open now.
184.107.37.81:443 (https) is open now.
184.107.37.81:3306 () is open now.

This is very simple way to know port open or not. If you face any problem then please inform me.

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

json_encode not working uft8 content , solve by use extra parameter in json_encode

Sometime json_encode not working in uft8 content so this is very common problem , In this article it will solve this problem. This is simple code which help you.

<?php
$data = [
    'গুগলের ‘স্টাইল আইডিয়াস’',
    'ফেসবুকের নয়া উদ্যোগে'
];
echo "<pre>";
print_r($data);
echo "<br>";
echo json_encode($data); // normal json_encode
echo "<br>";
echo json_encode($data, JSON_UNESCAPED_UNICODE); // json_encode with extra parameter which Encode multibyte Unicode characters literally

Then output is :

This is array data:

print_r($data);
Array
(
    [0] => গুগলের ‘স্টাইল আইডিয়াস’
    [1] => ফেসবুকের নয়া উদ্যোগে
)

This is normal json_encode

echo json_encode($data);
output will be is:

["\u0997\u09c1\u0997\u09b2\u09c7\u09b0 \u2018\u09b8\u09cd\u099f\u09be\u0987\u09b2 \u0986\u0987\u09a1\u09bf\u09df\u09be\u09b8\u2019","\u09ab\u09c7\u09b8\u09ac\u09c1\u0995\u09c7\u09b0 \u09a8\u09df\u09be \u0989\u09a6\u09cd\u09af\u09cb\u0997\u09c7"]

json_encode with JSON_UNESCAPED_UNICODE

echo json_encode($data, JSON_UNESCAPED_UNICODE);
output will be: 

["গুগলের ‘স্টাইল আইডিয়াস’","ফেসবুকের নয়া উদ্যোগে"]

If you face this problem then use this code which help you, 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 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

Get information from the web server automatically

Server-sent events is a technology for where a browser gets automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5[1] by the W3C.

Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream. First create a simple html page which call php file and get result from this file

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>

<script>
    if(typeof(EventSource)!=="undefined")
    {
        var source=new EventSource("http://localhost/result.php");
        source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br>";
        };
    }
    else
    {
        document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
    }
</script>

</body>
</html>

then create result.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Then you can see the result, without page refresh time will update

This is simple demo result

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

Comment