File Download

/* download.php */

<?php

if (isset($_GET['file_name'])) {
    $filename = $_GET['file_name'];
} else {
    $filename = NULL;
}

$err = "Sorry, the file you are requesting is unavailable";

if (!$filename) {
    echo $err;
} else {
    $path = 'uploads/' . $filename;
    if (file_exists($path) && is_readable($path)) {
        $size = filesize($path);
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . $size);
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: binary');

        $file = @fopen($path, 'rb');
        if ($file) {
            fpassthru($file);
            exit;
        } else {
            echo $err;
        }
    }
}
?>

Advertisements

File upload & Delete

<?php
$conn = mysqli_connect("localhost", "root", "", "fresh");

/* This is for delete file */
/*
if (isset($_REQUEST['file_name'])) {
    $filename = $_REQUEST['file_name'];
    $query = mysqli_query($conn, "DELETE FROM user WHERE profile_image='$filename'");
    if (mysqli_affected_rows($conn) > 0) {
        @ unlink("uploads/$filename");
        echo "Your file succefully delete";
    } else {
        echo "Your file not delete";
    }
}
 * */



/* file upload from this here */
if (isset($_FILES['filefield'])) {

    $name = $_REQUEST['name'];
    $file = $_FILES['filefield'];
    //echo "<pre>";
    //print_r($file);

    $upload_directory = "uploads/";

    $allowed_extensions = array("gif", "jpg", "jpeg", "mp3", "mp4", "tiff", "bmp", "doc", "docx", "ppt", "pptx", "txt", "pdf");
    $ext = substr($file['name'], strrpos($file['name'], '.') + 1);
    if (!in_array($ext, $allowed_extensions)) {
        die('only "gif", "jpg", "jpeg", "mp3", "tiff", "bmp", "doc", "docx", "ppt", "pptx", "txt", "pdf" files allowed to upload');
    }

    $max_file_size = 10485760;
    if ($file['size'] >= $max_file_size) {
        echo "Only the file size less than $max_file_size mb allowed";
    }

    $path = md5(microtime()) . '.' . $ext;

    if (move_uploaded_file($file['tmp_name'], $upload_directory . $path)) {

        // This query file name insert in to the database
        $query = mysqli_query($conn, "INSERT INTO user SET name='$name', profile_image='$path' ");

        //if (move_uploaded_file($file['tmp_name'], $upload_directory . $file['name'])) {
        echo "Your file successfully uploaded";
    } else {
        echo "The file can't moved";
    }
}
?>
/* file upload finished */

<form action="" method="post" enctype="multipart/form-data">
    <label>Name
        <input id="name" type="input" name="name" />
    </label>

    <label>Upload File
        <input id="filefield" type="file" name="filefield" />
    </label>

    <label>
        <input id="Upload" type="submit" name="Upload" value="Submit" />
    </label>



    <!-- This part is file name fetch from database and show up table -->

    <table width="700" border="1">
        <tr>
            <td>Name</td>
            <td>File Name</td>
            <td>Image</td>
        </tr>

        <?php
        /*
        $query = mysqli_query($conn, "SELECT name, profile_image FROM user");
        $hold = mysqli_fetch_all($query, MYSQLI_ASSOC);
        //echo "<pre>";
        //print_r($show);
        foreach ($hold as $data) {
            extract($data);
            ?>     
            <tr>
                <td><?php echo $name; ?></td>
                <td><?php echo $profile_image; ?></td>
                <!--<td><img src="uploads/<?php //echo $profile_image;?> "/></td>-->
                <td>
                    <?php
                    $file_ext = substr($profile_image, strrpos($profile_image, '.') + 1);
                    if ($file_ext == 'jpg') {
                        ?>
                        <img src = "uploads/<?php echo $profile_image; ?>" width = "100" />
                        <?php
                    }

                    if ($file_ext == 'pdf') {
                        ?>
                        <a href="uploads/<?php echo $profile_image; ?>"><img src = "uploads/pdf.jpg" width = "100" /></a>
                        <?php
                    }
                    if ($file_ext == 'docx') {
                        ?>
                        <a href="uploads/<?php echo $profile_image; ?>"><img src = "uploads/docx.jpg" width = "100" /></a>
                        <?php
                    }
                    ?>
                    <a href="download.php?file_name=<?php echo $profile_image; ?>"><input type="button" value="Download" name="download"></a>
                    <a href="upload.php?file_name=<?php echo $profile_image; ?>"><input type="button" value="Delete" name="delete" /></a>     
                </td>

            </tr>
            <?php
        }
        
        */
        ?>
    </table>

</form>

strpos, strrpos, substr


$string = "search the position of the first, search the position of the last inside the string";
$search = "position";
$pos = strpos($string, $search);
echo $pos;
echo "<br>";
echo "<br>";

$pos2 = strrpos($string, $search);
echo $pos2;
echo "<br>";
echo "<br>";

$return = substr($string, $pos);
echo $return;

echo "<br>";
echo "<br>";
$return2 = substr($string, $pos2);
echo $return2;

echo "<br>";
echo "<br>";
//Find the position of the last occurrence of "php" inside the string:
echo strrpos("I love php, I love php too!","php");

echo "<br>";
echo "<br>";

//Find the position of the first occurrence of "php" inside the string:
echo strpos("I love php, I love php too!","php");

Normal OOP Registration

1.Method Create

<?php

class Crud {

	public $conn;

	public function __construct() {
		$this->conn = mysqli_connect( "localhost", "root", "", "fresh" );
		if ( mysqli_connect() ) {
			//echo "Connect Successfully";
		} else {
			die( "connection error" );
		}
		session_start();
	}

	/* registration insert */

	public function regiInsert( $table, $firstname, $lastname, $username, $email, $password, $phone, $gender, $address ) {
		$query = mysqli_query( $this->conn, "INSERT INTO $table SET firstname='$firstname', lastname='$lastname', username='$username', email='$email', password='$password', phone='$phone', gender='$gender', address='$address' " );
		if ( mysqli_affected_rows( $this->conn ) > 0 ) {
			return true;
		} else {
			return false;
		}
	}


}

$obj = new Crud();

2.registration.php

<?php
include_once('../crud.php');
if (isset($_REQUEST['save'])) {
    //echo "<pre>";
    //print_r($_REQUEST);
    extract($_REQUEST);
    if ($obj->regiInsert("registration", $firstname, $lastname, $username, $email, sha1($password), $phone, $gender, $address)) {
        $err_msg = "Successfully You Registered, Please Sign in";
    } else {
        $err_msg = "Your registration not include";
    }
}
if(isset($_SESSION['username'])){
	header('location:home.php');
}
?>



<!doctype html>
<html>
    <head>
        <title>Registration Form</title>
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css"/>

        <!-- BootstrapValidator CSS -->
        <link rel="stylesheet" href="../bootstrap/css/bootstrapValidator.min.css"/>

        <!-- jQuery and Bootstrap JS -->
        <script type="text/javascript" src="../bootstrap/js/jquery-1.11.3.min.js"></script>
        <script type="text/javascript" src="../bootstrap/js/bootstrap.min.js"></script>

        <!-- BootstrapValidator JS -->
        <script type="text/javascript" src="../bootstrap/js/bootstrapValidator.min.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div style="border: 1px solid #ddd; padding: 0 0 15px;" class="col-md-8 col-md-offset-2">
                    <div class="page-header">
                        <h2 style="text-align: center; font-family: initial;">Sign up</h2>
                        <p style="text-align:center; color: #4D73E4;">
                            <?php
                            echo isset($err_msg) ? $err_msg : "";
                            ?>
                        </p>
                    </div>

                    <form action="registration.php" id="registrationForm" method="post" class="form-horizontal">

                        <div class="form-group">
                            <label class="col-xs-3 control-label">Full name</label>
                            <div class="col-xs-4">
                                <input type="text" class="form-control" name="firstname" placeholder="First name" />
                            </div>
                            <div class="col-xs-4">
                                <input type="text" class="form-control" name="lastname" placeholder="Last name" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">Username</label>
                            <div class="col-sm-5">
                                <input type="text" class="form-control" name="username" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">Email address</label>
                            <div class="col-sm-5">
                                <input type="text" class="form-control" name="email" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">Password</label>
                            <div class="col-sm-5">
                                <input type="password" class="form-control" name="password" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-xs-3 control-label">Phone number</label>
                            <div class="col-xs-5">
                                <input type="text" class="form-control" name="phone" placeholder="Phone Number" />
                            </div>
                        </div>	

                        <div class="form-group">
                            <label class="col-sm-3 control-label">Gender</label>
                            <div class="col-sm-5">
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="gender" value="male" /> Male
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="gender" value="female" /> Female
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="gender" value="other" /> Other
                                    </label>
                                </div>
                            </div>
                        </div>
                        <!-- 
                        <div class="form-group">
                             <label class="col-sm-3 control-label">Date of birth</label>
                             <div class="col-sm-5">
                                 <input type="date" class="form-control" name="date"  placeholder="YYYY/MM/DD" />
                             </div>
                         </div>-->

                        <div class="form-group">
                            <label class="col-sm-3 control-label">Address</label>
                            <div class="col-sm-5">
                                <textarea name="address" class="form-control" rows="5" cols="25"></textarea>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-9 col-sm-offset-3">
                                <!-- Do NOT use name="submit" or id="submit" for the Submit button -->
                                <button type="submit" name="save" value="submit" class="btn btn-default">Sign up</button>
                                <a class="btn btn-default" href="http://127.0.0.1/ibcs/fresh/template/admin/">Sign In</a>
                            </div>
                            
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
            $(document).ready(function () {
                $('#registrationForm').bootstrapValidator({
                    // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        firstname: {
                            row: '.col-xs-4',
                            validators: {
                                notEmpty: {
                                    message: 'The first name is required'
                                }
                            }
                        },
                        lastname: {
                            row: '.col-xs-4',
                            validators: {
                                notEmpty: {
                                    message: 'The last name is required'
                                }
                            }
                        },
                        username: {
                            message: 'The username is not valid',
                            validators: {
                                notEmpty: {
                                    message: 'The username is required and cannot be empty'
                                },
                                stringLength: {
                                    min: 6,
                                    max: 30,
                                    message: 'The username must be more than 6 and less than 30 characters long'
                                },
                                regexp: {
                                    regexp: /^[a-zA-Z0-9]+$/,
                                    message: 'The username can only consist of alphabetical and number'
                                },
                                different: {
                                    field: 'password',
                                    message: 'The username and password cannot be the same as each other'
                                }
                            }
                        },
                        email: {
                            validators: {
                                notEmpty: {
                                    message: 'The email address is required and cannot be empty'
                                },
                                emailAddress: {
                                    message: 'The email address is not a valid'
                                }
                            }
                        },
                        password: {
                            validators: {
                                notEmpty: {
                                    message: 'The password is required and cannot be empty'
                                },
                                different: {
                                    field: 'username',
                                    message: 'The password cannot be the same as username'
                                },
                                stringLength: {
                                    min: 8,
                                    message: 'The password must have at least 8 characters'
                                }
                            }
                        },
                        phone: {
                            row: '.col-xs-5',
                            validators: {
                                notEmpty: {
                                    message: 'The cell phone number is required'
                                }
                            }
                        },
                        birthday: {
                            validators: {
                                notEmpty: {
                                    message: 'The date of birth is required'
                                },
                                date: {
                                    format: 'YYYY/MM/DD',
                                    message: 'The date of birth is not valid'
                                }
                            }
                        },
                        gender: {
                            validators: {
                                notEmpty: {
                                    message: 'The gender is required'
                                }
                            }
                        }
                        ,
                        address: {
                            validators: {
                                notEmpty: {
                                    message: 'Please input your valid address'
                                }
                            }
                        }
                    }
                });
            });
        </script>
    </body>
</html>

3.looking like this
registration

20. Session

What is a PHP Session?
The web server does not know who you are or what you do, because the HTTP address doesn’t maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Start a PHP Session
A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Example:

<?php
	session_start();
	$_SESSION['name']="Username";

	echo isset($_SESSION['name'])?$_SESSION['name']." is available":"The user not Exist";
	
?>

Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
	session_start();
	$_SESSION['name1']="Unsername";
	session_unset();
	session_destroy();
	echo isset($_SESSION['name1'])?$_SESSION['name1']." is available":"The user not Exist";
	
?>

3. Readmore Menu Content and Readmore Category Article

1.crud.php

<?php

class Crud {

    public $conn;

    public function __construct() {
        $this->conn = mysqli_connect("localhost", "root", "", "fresh");
        if (mysqli_connect()) {
            //echo "Connect Successfully";
        } else {
            die("connection error");
        }
    }

    /* This is for readmore menu content */
    public function readMenuContent($table, $id) {
        $query = mysqli_query($this->conn, "SELECT * FROM $table WHERE menu_id=$id AND status= 1");
        if (mysqli_num_rows($query) > 0) {
            return mysqli_fetch_assoc($query);
        } else {
            return false;
        }
    }
    
    /* This is for readmore Article */
    public function readArticle($table, $id) {
        $query = mysqli_query($this->conn, "SELECT * FROM $table WHERE art_id=$id AND status = 1");
        if (mysqli_num_rows($query)) {
            return mysqli_fetch_assoc($query);
        } else {
            return false;
        }
    }

}

$obj = new Crud();

2.content.php

<div class="content1">
    <div class="content1_box1 flt_lt">

        <?php
        /* This is for menu content */
        if (isset($_REQUEST['menu_id'])) {
            $content = $obj->MenuContent("menus", $_REQUEST['menu_id']);
            //echo $content["menu_content"];

            /* Start from this here for Readmore content */
            extract($content);
            $convert_array = explode(' ', $menu_content);
            //print_r($convert_array);
            if (count($convert_array) <= 210) {
                echo "<p>$menu_content</p>";
            } else {
                $slice = array_slice($convert_array, 0, 209);
                echo "<p>" . implode(' ', $slice) . "<a style=text-decoration:none;color:red; href=index.php?id=$menu_id>&nbsp;&nbsp;Read More</a> </p>";
            }
        } elseif (isset($_REQUEST['id'])) {
            $readmore = $obj->readMenuContent("menus", $_REQUEST['id']);
            //print_r($readmore);
            echo $readmore['menu_content'];
        } /* finish line Readmore content */



        /* This is for category articles */
        if (isset($_REQUEST['cat_id']) ? $_GET['cat_id'] : null) {
            $articles = $obj->CatArticle("articles", $_REQUEST['cat_id']);
            //echo "<pre>";
            //print_r($articles);
            foreach ($articles as $article) {
                extract($article);
                echo "<h2>" . $article["art_title"] . "</h2>";
                //echo "<p>" . $article["art_content"] . "</p>";

                /* Start from this here for Readmore Article */
                $art_convert_array = explode(' ', $art_content);
                //print_r($art_convert_array);
                if (count($art_convert_array) <= 160) {
                    echo "<p>" . $art_convert_array["art_content"] . "</p>";
                    //echo "<p>$art_content</p>";
                } else {
                    $art_slice = array_slice($art_convert_array, 0, 159);
                    echo "<p>" . implode(' ', $art_slice) . "<a style=text-decoration:none;color:red; href=index.php?art_id=$art_id>&nbsp;&nbsp;Read More</a> </p>";
                }
            }
        } elseif (isset($_REQUEST['art_id'])) {
            $artReadmore = $obj->readArticle("articles", $_REQUEST['art_id']);
            echo "<h2>" . $artReadmore['art_title'] . "</h2>";
            echo "<p>" . $artReadmore['art_content'] . "</p>";
        } /* finish line Readmore Article */
        ?>

        <br/>
    </div>

Output:
readmore

2. Dynamic Category and Category Articles show

1.Create Database Table articles

article

2.Crud.php file

<?php

class Crud {

    public $conn;

    public function __construct() {
        $this->conn = mysqli_connect("localhost", "root", "", "fresh");
        if (mysqli_connect()) {
            //echo "Connect Successfully";
        } else {
            die ("connection error");
            
        }
    }
   
    /* This is for category show */
    public function categories($table){
        $query = mysqli_query($this->conn, " SELECT * FROM $table");
        if(mysqli_num_rows($query)>0){
            return mysqli_fetch_all($query, MYSQL_ASSOC);
        } else{
            return false;
        }
    }
    
    /* This is for Category Article show*/
    public function CatArticle($table,$id){
        $query = mysqli_query($this->conn, "SELECT * FROM $table WHERE cat_id=$id");
        if(mysqli_num_rows($query)>0){
            return mysqli_fetch_all($query,MYSQL_ASSOC);
        } else{
            return false;
        }
    }

}

$obj = new Crud();

3.sidebar.php

<div class="content1_box2 flt_lt">
    <h2>Latest work</h2>
    <div class="content1_box2_img"><a href="#"><img src="images/img.jpg" width="300" height="135" alt="img" /></a></div>
    <p>Pellentesque diam ligula, egestas eget rhoncus vel, hendrerit in sem. Viva mus laoreet erat sit amet ante ullamcorper vestibulum. <a href="#">Read More</a></p>
    <h2>Categories</h2>
    <ul>
        <?php
        $categories = $obj->categories("categories");
        foreach ($categories as $category) {
            extract($category);
            ?> <li><a href="index.php?cat_id=<?php echo $cat_id; ?>"><?php echo $cat_name; ?></a></li>
            <?php
        }
        ?>
    </ul>
    <div class="clear"></div>
</div>

4.content.php

<div class="content1">
    <div class="content1_box1 flt_lt">

        <?php
        /* This is for category articles */
        if (isset($_REQUEST['cat_id'])) {
            $articles = $obj->CatArticle("articles", $_REQUEST['cat_id']);
            //echo "<pre>";
            //print_r($articles);
            foreach ($articles as $article) {
                echo "<h2>" . $article["art_title"] . "</h2>";
                echo "<p>" . $article["art_content"] . "</p>";
            }
        }
        ?>

        <br/>
    </div>

Output like following screenshot
category