Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Download file with speed limit using PHP

Here we are explaining about how to limit speed for the file download operation.


<?php
// File form server
$local_file = 'user.php';

// filename that the user gets as default
$download_file = 'myFile.php';

// set the download rate limit (=> 10 kb/s)
$download_rate = 10;

if(file_exists($local_file) && is_file($local_file)) {

    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();

    // open file stream
    $file = fopen($local_file, "r");

    while (!feof($file)) {

        // send the current file part to the browser
        print fread($file, round($download_rate * 10));

        // flush the content to the browser
        flush();

        // sleep one second
        sleep(1);
    }

    // close file stream
    fclose($file);
}
else {
    die('Error: The file '.$local_file.' does not exist!');
}
?>

For more:

Unknown Features
Beautiful Designs
Security Features

Create tables dynamically from user input using PHP

In this tutorial we are going to learn about how to generate table columns and rows dynamically from user input. 

Very simple code generate dynamic table.


Here is the code.

PHP code get requested number of columns and rows through loops and then simply display the table.

You always can make it more attractive by adding CSS styles.   



<?php
 
$createtable = '';
if ($_POST){

        $createtable .= '<table border="1">';
for ($i = 0; $i < $_POST['line']; $i++) {

$createtable .= '<tr>';
for ($j = 0; $j < $_POST['colunn']; $j++) {

$createtable .= '<td width="50">&nbsp;</td>';
}

$createtable .= '</tr>';
}

$createtable .= '</table>';
}

?>

<form action="" method="post">

<table border="0" width="200">

<tr>
<td width="80"><label>Column:</label></td>
<td width="120"><input type="text" name="colunn"></td>
</tr>

<tr>
<td><label>Line:</label></td>
<td><input type="text" name="line"></td>
</tr>

<tr>
<td colspan="2" align="right">
<input type="submit" value="Create Table">
</td>
</tr>

</table>

</form>

<?php

echo $createtable;

 ?>



For any queries or any new code requests comment below in the comment section.

How to force downloading a file using PHP.

Here we are providing a simple code of explaining how to make a user to download file forcefully.

Normally, you don't necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file. 

<a href="demo.jpg">Download</a>

Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.

download.php
<?PHP
function force_download($file)  
{
       if ((isset($file))&&(file_exists($file))) {  
            header("Content-length: ".filesize($file));  
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $file . '"'); 
            readfile("$file");
       } else {  
            echo "No file selected";  
       }
}

index.php
<?php
include('download.php');
$file = 'demo.jpg'; 
force_download($file);
?>


HTTP header fields

The Content-Length entity-header field indicates the size of the entity-body,
in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
method, the size of the entity-body that would have been sent had the request
been a GET. 

The text/html content type is an Internet Media Type as well as a MIME content type. Using HTML in MIME messages allows the full richness of Web pages to be available in e-mail. text/plain[RFC1521] The text/plain content type is the generic subtype for plain text.

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.


List of HTTP header fields
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

Similarly, you can force download other files formats like word doc, pdf files, etc.

PHP Errors

Different kind of error events may occur in PHP. These errors are classified based on the time of occurrences and whether it is recoverable or not. And this classification is made with respect to how it is triggered to send an error message to the browser. It might be triggered automatically while executing an improper line of code.
  1. Fatal error
  2. Parse error
  3. Warning
  4. Notices

How to enable errors in PHP
error_reporting(E_ALL);
ini_set('display_errors', '1');

Fatal Error

In computing, a fatal error or fatal exception error is an error that causes a program to abort and may, therefore, return the user to the operating system. When this happens, data that the program was processing may be lost. fatal errors are classified as,
  • Startup fatal error – This will occur when the code cannot be executed with the PHP environment due to the fault that occurred at the time of installation.
  • Compile time fatal error – This kind of error will occur when we attempt to use nonexistent data like file, class, function and etc.
  • Runtime fatal error – This will occur during execution. It is similar to compile time fatal error, except Compile time fatal error is generated by the Zend engine based on the time of occurrence.

Example: PHP Fatal Error

Let us call a non-existing function myFunction() in the following PHP program.

<?php
myFunction();
echo "PHPJavaScript.com!"
?>
This program will raise the following fatal error at the time of execution which will stop executing a further line that is the echo statement.

( ! ) Fatal error: Call to undefined function myFunction() in C:\xampp\htdocs\demo\today\demo.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0010130016{main}( )...\demo.php:0

Parse Error

Parse errors are generated only at compile time which is also called as a syntax error. If anything wrong with PHP syntax, for example, missing semi-colon for the end of the line, will trigger this type of errors to be displayed to the browser.

<?php
echo "http://www.phpjavascript.com/"
echo "<br/>error";
?>
This program sends parse error to the browser as follows due to the lack of semicolon(;) at the end of the line.

( ! ) Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in C:\xampp\htdocs\demo\today\demo.php on line 3


Warning

PHP will create warning message for sending them to the user without halting the execution. An example for warning messages to be created is the divide by zero problem that is as shown in the following program.

<?php
$numberOne = 0;
$NumberTwo = 10;
$result = $NumberTwo/$numberOne;
echo $result;
?>
In the above program, since $numberOne has the value 0 and any number divided by zero is undefined, the line on which the division is made will create the following warning notices followed by the string returned by the echo statement with an empty value for $result variable. Meaning that, even after the occurrence of the warning error, the echo statement is executed.

( ! ) Warning: Division by zero in C:\xampp\htdocs\demo\today\demo.php on line 4
Call Stack
#TimeMemoryFunctionLocation
10.0000129832{main}( )...\demo.php:0

Notice

Like other PHP error messages, notice message can be created automatically or by the user by using the PHP trigger_error() function.It is used to send messages to the browser to make the user know about the problem of the code is any, which might cause an error.

For example, the following program starts with incrementing an uninitialized variable $result to print the incremented value to the browser. Since $result is not initialized, it will automatically trigger the notice error on executing this script.

<?php
$result += 5;
echo "RESULT: ". $result;
?>
( ! ) Notice: Undefined variable: result in C:\xampp\htdocs\demo\today\demo.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0000129672{main}( )...\demo.php:0

RESULT: 5

But program execution will not be terminated because of this PHP notice. Rather, the notice message will be sent to the browser and the echo statement will print the incremented $result value subsequently.

Useful

E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
.E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings

Simple login form using PHP and MySQL.

The login form is very much essential in every kind of web application so here we are explaining a simple and best way of doing login system. which mainly includes 
1. Connecting to Database
2. Login(Session Start)
3. Logout(Session End)
4. Session Check
5. Login Form
6. CSS

1. Connecting to Database

$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}



2. Login

session_start();
if (isset($_POST['username']) and isset($_POST['password'])) {
   
    $Username = $_POST['username'];
    $Password = $_POST['password'];
    $query = "SELECT * FROM `user` WHERE FirstName='$Username' and Password='$Password'";
    $result = mysqli_query($Connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {
        $_SESSION['username'] = $
Username;
    } else {
        $fmsg = "Invalid Login Credentials.";
    }
}


3. Logout

session_start();
session_destroy();
header('Location: login.php');


4. Session Check

if (isset($_SESSION['username'])) {
    
    echo "<div class='session-box'>";
    echo 'Welcome Mr.'.$Username = $_SESSION['username'];
    echo "<br><a href='logout.php'>Logout</a>";
    echo "</div>";
}else{
    
    echo "<div class='session-box'>";
    echo "You are logged out.";
    echo "</div>";

}

5. Login Form

<form method="POST" class="login-box">

    <div class="form-header">Please Login</div>

    <div class="col-md-12">  
        <label>Username</label>
        <input type="text" name="username" class="form-control" placeholder="Username" required>
    </div>

    <div class="col-md-12">
        <label>Password</label>
        <input type="password" name="password" class="form-control" placeholder="Password" required>
    </div>

    <div class="col-md-6">
        <button class="btn btn-primary" type="submit">Login</button>
    </div>

</form>

6.CSS

 <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <style>
            .login-box{
                position: absolute;
                width: 300px;
                height: 270px;
                z-index: 15;
                top: 50%;
                left: 50%;
                margin: -100px 0 0 -150px;
                border: 1px solid #8080804a;
                border-radius: 5px;
                background: #8080804a;
            }
            .session-box{
                position: absolute;
                width: 300px;
                height: 100px;
                z-index: 15;
                top: 10%;
                left: 50%;
                margin: 0px 0 0 -150px;
                border: 1px solid #8080804a;
                border-radius: 5px;
                background: #8080804a;
                padding: 30px;
            }
            .form-control{
                padding: 10px;
                margin-top: 5px;
            }
            .btn-primary{
                margin-top: 20px;
            }
            .form-header{
                width: 299px;
                height:40px;
                background: #004f61;
                color:white;
                text-align: center;
                font-size: 20px;
                margin-bottom: 20px;
                padding: 5px;
            }
        </style>

    </head>

Create Database Table

CREATE TABLE `user` (
  `UserID` int(12) NOT NULL,
  `FirstName` varchar(48) NOT NULL,
  `LastName` varchar(48) NOT NULL,
  `Email` varchar(128) NOT NULL,
  `Password` varchar(20) NOT NULL,
  `City` varchar(48) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul@zzz.xxx', 'Rahul@123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh@xxx.xxx', 'Mahesh@123', 'Delhi');







Result




Google Pie Charts with PHP and MySQL

Populating pie charts with google api is one of the simplest way to do. here we are showing 
you a simple example to generate pie chart with real time data. fetching data from database table.
<?php
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, 
    $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$selectsql = "SELECT * FROM graph";
$result = mysqli_query($Connection, $selectsql);
?>

<html>
<head>
    <script type="text/javascript" 
            src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {

          var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          <?php while($row = mysqli_fetch_array($result)){  ?>
             ["<?php echo $row['name']; ?>", <?php echo $row['count']; ?>],
          <?php } ?>
          ]);

         var options = {
           title: 'My Daily Activities'
            };

         var chart = new google.visualization.PieChart
         (document.getElementById('piechart'));

         chart.draw(data, options);
        }
    </script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Run these queries in your database.
//Table structure for table `graph`
CREATE TABLE `graph` (
  `id` int(2) NOT NULL,
  `name` varchar(34) NOT NULL,
  `count` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

//Dumping data for table `graph`

INSERT INTO `graph` (`id`, `name`, `count`) VALUES
(1, 'Work', 11),
(2, 'Eat', 2),
(4, 'Commute', 2),
(5, 'Watch TV', 2),
(6, 'Sleep', 7);
Result:

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts