Month: February 2018

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

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.

<?php
$data = array(
    14 => "Test14",
    11 => "Test11",
    4 => "Test4",
    12 => "Test12",
    13 => "Test13");
echo "<pre>";
print_r($data);
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:

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

Comment

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 get content which div first class name using php preg_match function?

Suppose you want to get content using preg_match function for specific div class name or id. This is HTML

<div class="calss1 class2 class3">
    Content 1
</div>
<div class="class1 class2 class3">
    Content 2
</div>
<div class="class1 class2 class3">
    Content 3
</div>
<div class="class1 class2 class3">
    Content 4
</div>
<div class="class1 class2 class3">
    Content 5
</div>

then you want to get content using specific class name , not all class name like class name class1

then you can use this code which get all content which class name first class1

 if (preg_match('/<div class="class1(\s.*?)?">(.*?)<\/div>/is', $my_content, $result)) {
            print_r($result);
        }

This will get all result which you want, if you face any problem then please inform me.

View 2 Comments

get ip from domain name using php

If you need to know ip address from domain name then you can use php which is very simple. You can use gethostbyname. gethostbyname — Get the IPv4 address corresponding to a given Internet host name . This is simple code


<?php
$ip = gethostbyname('https://techparkbd.com/');

echo $ip;
?>

Then Output is :

184.107.37.81 

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

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

how to remove http:// or https:// from url using JavaScript?

In some case we need to remove https or http from url. We can do it using javascript. Here is simple code

   var url = "https://techparkbd.com/";
   url = url.replace(/^https?:\/\//,'');
   console.log(url);

This output :


techparkbd.com/

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

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

Get the max height from a set of elements using jQuery.

In various design section we need to match height for list for look better. In this case need to determine max height of some element and then set this height for all other element .In this case you can do it easily using normal jquery map function. Here is simple code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div class="testdiv">
        Line 1<br>
        Line 2
    </div>
    <div class="testdiv">
        Line 1<br>
        Line 2<br>
        Line 3<br>
        Line 4
    </div>
    <div class="testdiv">
        Line 1
    </div>
    <div class="testdiv">
        Line 1<br>
        Line 2
    </div>
</div>

From this element we need to determine max height then add some style . This is simle jQuery code

<script>
    var highest = null;
    var hi = 0;
    $(".testdiv").each(function () {
        var h = $(this).height();
        if (h > hi) {
            hi = h;

            highest = $(this);
        }
    });
    alert(hi)
    highest.css("background-color", "red");

</script>

In this case this code get max height then you can set other element same height and also some style

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

Comment