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

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

if you need any help 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

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

<?php
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

<?php
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

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 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 change the style of alert box?

Now we want to change website more style so normal alert box is not good to see so in this case we want to change it.
There are some library which help you a lot. This is some link which you can use

Option 1: You can use

There are lot of option to customize it. hope you will like it

Option 2 : you can also use

This is very cool and more option to customize

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

Comment