Thursday 29 September 2016

Watermark an uploaded Image with PHP

Watermarking is a popular method to protect digital photos from being copied by the picture thieves on the net. Using PHP we can do the same. Here we use a transparent PNG image as Watermark template, we then merge it with image to create a permanent watermark.

In most scenarios people want to resize uploaded image using HTML form and then watermark it on the fly. So in this article, we will do the same. We upload an image, resize it and then watermark it with our PNG file.



If you look at my previous resize snippet, you’ll realize that I have made a slight modification to the code. This snippet typically does the same thing, it resizes uploaded image. But after modification, now it adds a watermark to all resized images. Let’s create an upload page using HTML below.
<!DOCTYPE HTML>
<html>

<head>
    <style type="text/css">
        #upload-form {
            padding: 20px;
            background: #F7F7F7;
            border: 1px solid #CCC;
            margin-left: auto;
            margin-right: auto;
            width: 400px;
        }
        
        #upload-form input[type=file] {
            border: 1px solid #ddd;
            padding: 4px;
        }
        
        #upload-form input[type=submit] {
            height: 30px;
        }
    </style>
</head>

<body>

    <form action="" id="upload-form" method="post" enctype="multipart/form-data">
        <input type="file" name="image_file" />
        <input type="submit" value="Send Image" />
    </form>

</body>


</html>



Complete snippet (Re-size and Watermark)


If you are clear on the example above, take a look at the complete PHP code below, we call PHP imagecopy() function after the image is resized, but before saving the image.

<?php

if(isset($_FILES['image_file']))
{
$max_size = 800; //max image size in Pixels
$destination_folder = 'M:/xampp/htdocs/demo/php-watermark-sample-file';
$watermark_png_file = 'watermark.png'; //watermark png file

$image_name = $_FILES['image_file']['name']; //file name
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_type = $_FILES['image_file']['type']; //file type

switch(strtolower($image_type)){ //determine uploaded image type 
//Create new image from file
case 'image/png': 
$image_resource =  imagecreatefrompng($image_temp);
break;
case 'image/gif':
$image_resource =  imagecreatefromgif($image_temp);
break;          
case 'image/jpeg': case 'image/pjpeg':
$image_resource = imagecreatefromjpeg($image_temp);
break;
default:
$image_resource = false;
}

if($image_resource){
//Copy and resize part of an image with resampling
list($img_width, $img_height) = getimagesize($image_temp);

   //Construct a proportional size of new image
$image_scale        = min($max_size / $img_width, $max_size / $img_height); 
$new_image_width    = ceil($image_scale * $img_width);
$new_image_height   = ceil($image_scale * $img_height);
$new_canvas         = imagecreatetruecolor($new_image_width , $new_image_height);

if(imagecopyresampled($new_canvas, $image_resource , 0, 0, 0, 0, $new_image_width, $new_image_height, $img_width, $img_height))
{

if(!is_dir($destination_folder)){ 
mkdir($destination_folder);//create dir if it doesn't exist
}

//center watermark
$watermark_left = ($new_image_width/2)-(300/2); //watermark left
$watermark_bottom = ($new_image_height/2)-(100/2); //watermark bottom

$watermark = imagecreatefrompng($watermark_png_file); //watermark image
imagecopy($new_canvas, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 100); //merge image

//output image direcly on the browser.
header('Content-Type: image/jpeg');
imagejpeg($new_canvas, NULL , 90);

//Or Save image to the folder
//imagejpeg($new_canvas, $destination_folder.'/'.$image_name , 90);

//free up memory
imagedestroy($new_canvas); 
imagedestroy($image_resource);
die();
}
}
}
?>


Watermark an uploaded Image with PHP

Tuesday 27 September 2016

Bootstrap Datepicker viewmode Only Month show

<div class="input-append date">

 <input  type="text" readonly="readonly" name="date"  id="datepicker">    
 
</div>      
$("#datepicker").datepicker( {
    format: "mm",
    viewMode: "months", 
    minViewMode: "months"
});

Bootstrap Datepicker viewmode  Only Month show

Bootstrap Datepicker viewmode Years Only show

<div class="input-append date">

 <input  type="text" readonly="readonly" name="date" id="datepicker">    
  
</div>      
$("#datepicker").datepicker( {
    format: "yyyy",
    viewMode: "years", 
    minViewMode: "years"
});



Bootstrap Datepicker viewmode  Years Only show

Sunday 25 September 2016

PHP Date Format to Month Name and Year

You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.





PHP Date Format to Month Name and Year

Saturday 24 September 2016

Import Excel/CSV file to MySQL Database Using PHP


VIDEO   Subscribe this channel










In this tutorial in going to show you how to create n application that can be used to import CSV/Excel file using PHP. To start with this project create a Database in your phpmyadmin name “exceltest” then execute this SQL query to create a new table called subject.


CREATE TABLE IF NOT EXISTS `subject` (
`SUBJ_ID` INT(11) NOT NULL AUTO_INCREMENT,
`SUBJ_CODE` VARCHAR(30) NOT NULL,
`SUBJ_DESCRIPTION` VARCHAR(255) NOT NULL,
`UNIT` INT(2) NOT NULL,
`PRE_REQUISITE` VARCHAR(30) NOT NULL DEFAULT 'None',
`COURSE_ID` INT(11) NOT NULL,
`AY` VARCHAR(30) NOT NULL,
`SEMESTER` VARCHAR(20) NOT NULL,
PRIMARY KEY (`SUBJ_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=500 ;



Then inside you htdocs or document root folder create a new folder and name it as “excelTest”. Next we need to create a PHP file named “db.php” that will hold our database connection and here’s the following code:


<?php
     $conn= mysql_connect("localhost","root","") or die("Could not connect");
     mysql_select_db("studentdb",$conn) or die("could not connect database");
?>




Next create another PHP file named “index.php”,and this php file will be the first page that will load to our browser when we access the “excelTest” folder from our web directory. And this index.php will load all the list of subject if the subject table is not empty as well as this page will allow the user to import the CSV/Excel file and upload the data to MySQL Database. and it will look like as shown below.




And here’s the code for “index.php” file:

<!DOCTYPE html>
<?php 
include 'db.php';
?>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Import Excel To Mysql Database Using PHP </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="title" content="Hemant Vishwakarma">
<meta name="description" content="Import Excel File To MySql Database Using php">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>    
    <br><br>
        <div class="container">
            <div class="row">
            <div class="col-md-12 text-center"><h1>Visit My Blog www.hemant9807.blogspot.com</h1></div>
    <br>
                <div class="col-md-3 hidden-phone"></div>
                <div class="col-md-6" id="form-login">
                    <form class="well" action="import.php" method="post" name="upload_excel" enctype="multipart/form-data">
                        <fieldset>
                            <legend>Import CSV/Excel file</legend>
                            <div class="control-group">
                                <div class="control-label">
                                    <label>CSV/Excel File:</label>
                                </div>
                                <div class="controls form-group">
                                    <input type="file" name="file" id="file" class="input-large form-control">
                                </div>
                            </div>
                            
                            <div class="control-group">
                                <div class="controls">
                                <button type="submit" id="submit" name="Import" class="btn btn-success btn-flat btn-lg pull-right button-loading" data-loading-text="Loading...">Upload</button>
                                </div>
                            </div>
                        </fieldset>
                    </form>
                </div>
                <div class="col-md-3 hidden-phone"></div>
            </div>
            
    
            <table class="table table-bordered">
                <thead>
                        <tr>
                            <th>ID</th>
                            <th>Subject</th>
                            <th>Description</th>
                            <th>Unit</th>
                            <th>Semester</th>
                            
                     
                        </tr>
                      </thead>
                <?php
                    $SQLSELECT = "SELECT * FROM subject ";
                    $result_set =  mysql_query($SQLSELECT, $conn);
                    while($row = mysql_fetch_array($result_set))
                    {
                    ?>
                        <tr>
                            <td><?php echo $row['SUBJ_ID']; ?></td>
                            <td><?php echo $row['SUBJ_CODE']; ?></td>
                            <td><?php echo $row['SUBJ_DESCRIPTION']; ?></td>
                            <td><?php echo $row['UNIT']; ?></td>
                            <td><?php echo $row['SEMESTER']; ?></td>
                        </tr>
                    <?php
                    }
                ?>
            </table>
        </div>
</body>
</html>


Next, we’re going to create another PHP file named “import.php” that will used to process the data from CSV/Excel to MySQL Database. and here’s the following code:



<?php
include 'db.php';
if(isset($_POST["Import"])){

echo $filename=$_FILES["file"]["tmp_name"];

if($_FILES["file"]["size"] > 0)
{

$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{

//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into subject (`SUBJ_CODE`, `SUBJ_DESCRIPTION`, `UNIT`, `PRE_REQUISITE`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?> 




Import Excel/CSV file to MySQL Database Using PHP

Export Data to Excel in PHP Simple function code

Hello everybody now i will share to you all about export data table to excel file in PHP Simple function code
Okay, lets go.


This function is paste and run :

public function Exportexcel()
{
$Project  = 'select * from tbl_project'
$filename  = 'test- '.date('Y-m-d').' - hemant.xls';
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=".$filename);
echo '<table width="100%" border="1">
<thead>
<tr>
<th>Project Id</th>
<th>Project Name</th>
<th>Price</th>
<th>Type</th>
<th>Project Description</th>
<th>Address</th>
<th>Amenities</th>
<th>Total Area</th>
<th>Covered Area</th>
<th>Open to Air Area</th>
<th>Roof top Accessibility</th>
<th>Total no. of tower</th>
<th>Total no. of Flats</th>
<th>Banner</th>
</tr>
</thead>';
foreach($Project as $prj){
echo ' 
<tr>
<td>'.$prj->id.'</td>
<td>'.$prj->project_name.'</td>
<td>Min '.$prj->min_price.' - Max '. $prj->max_price.'</td>
<td>type</td>
<td>'.$prj->content.'</td>
<td>'.$prj->address.'</td>
<td>'.$prj->amenities.'</td>
<td>'.$prj->projectfacts->total_area.'</td>
<td>'.$prj->projectfacts->covered_area.'</td>
<td>'.$prj->projectfacts->open_to_air_area.'</td>
<td>'.$prj->projectfacts->roof_top_accessibility.'</td>
<td>'.$prj->projectfacts->no_of_tower.'</td>
<td>'.$prj->projectfacts->no_of_flat.'</td>
<td> <img src="'. $prj->banner_image;'." /></td>
</tr>
';
}
echo '</table>';
}

Result of export excel.






Export Data to Excel PHP Simple function 

Export Data to Excel Without Extension in Yii2 Export in Excel yii2

Hello everybody now i will share to you all about export data table to excel file without extension in yii2.
Okay, lets go.
This function is paste in controller and run :

public function actionExportexcel()
{
$Project = Project::find()->all();
$filename = 'test- '.date('Y-m-d').' - hemant.xls';
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=".$filename);
echo '<table width="100%" border="1">
<thead>
<tr>
<th>Project Id</th>
<th>Project Name</th>
<th>Price</th>
<th>Type</th>
<th>Project Description</th>
<th>Address</th>
<th>Amenities</th>
<th>Total Area</th>
<th>Covered Area</th>
<th>Open to Air Area</th>
<th>Roof top Accessibility</th>
<th>Total no. of tower</th>
<th>Total no. of Flats</th>
<th>Banner</th>
</tr>
</thead>';
foreach($Project as $prj){
echo ' 
<tr>
<td>'.$prj->id.'</td>
<td>'.$prj->project_name.'</td>
<td>Min '.$prj->min_price.' - Max '. $prj->max_price.'</td>
<td>type</td>
<td>'.$prj->content.'</td>
<td>'.$prj->address.'</td>
<td>'.$prj->amenities.'</td>
<td>'.$prj->projectfacts->total_area.'</td>
<td>'.$prj->projectfacts->covered_area.'</td>
<td>'.$prj->projectfacts->open_to_air_area.'</td>
<td>'.$prj->projectfacts->roof_top_accessibility.'</td>
<td>'.$prj->projectfacts->no_of_tower.'</td>
<td>'.$prj->projectfacts->no_of_flat.'</td>
<td> <img src="'. $prj->banner_image;'." /></td>
</tr>
';
}
echo '</table>';
}

Result of export excel.



Export Data to Excel Without Extension on Yii2 Export in Excel yii2

Saturday 17 September 2016

yii2 logout method not allowed (#405) while logout user error

BEFORE

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

AFTER CHANGE 

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'logout' => ['post'],
                ],
            ],
        ];
    }