Showing posts with label Crop Image in Core PHP. Show all posts
Showing posts with label Crop Image in Core PHP. Show all posts

Insert,Update,Delete PHP Using Ajax

Insert,Update,Delete PHP Using Ajax 


Hi Today Discussed Core PHP Insert,Update,Delete php using Ajax, Php insert view update delete without loading browser so data pasing ajax follows code.

Insert,Update,Delete PHP Using Ajax
Insert,Update,Delete PHP Using Ajax 

sql

CREATE TABLE IF NOT EXISTS `user_detail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

list.php

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="modify.js"></script>
</head>
<body>
<div id="wrapper">

<?php
$host="localhost";
$username="root";
$password="";
$databasename="ajaxphp";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$select =mysql_query("SELECT * FROM user_detail");
?>

<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<?php
while ($row=mysql_fetch_array($select)) 
{
 ?>
 <tr id="row<?php echo $row['id'];?>">
  <td id="name_val<?php echo $row['id'];?>"><?php echo $row['name'];?></td>
  <td id="age_val<?php echo $row['id'];?>"><?php echo $row['age'];?></td>
  <td>
   <input type='button' class="edit_button" id="edit_button<?php echo $row['id'];?>" value="edit" onclick="edit_row('<?php echo $row['id'];?>');">
   <input type='button' class="save_button" id="save_button<?php echo $row['id'];?>" value="save" onclick="save_row('<?php echo $row['id'];?>');">
   <input type='button' class="delete_button" id="delete_button<?php echo $row['id'];?>" value="delete" onclick="delete_row('<?php echo $row['id'];?>');">
  </td>
 </tr>
 <?php
}
?>

<tr id="new_row">
 <td><input type="text" id="new_name"></td>
 <td><input type="text" id="new_age"></td>
 <td><input type="button" value="Insert Row" onclick="insert_row();"></td>
</tr>
</table>

</div>
</body>
</html>
modify.js

function edit_row(id)
{
 var name=document.getElementById("name_val"+id).innerHTML;
 var age=document.getElementById("age_val"+id).innerHTML;

 document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
 document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
 
 document.getElementById("edit_button"+id).style.display="none";
 document.getElementById("save_button"+id).style.display="block";
}

function save_row(id)
{
 var name=document.getElementById("name_text"+id).value;
 var age=document.getElementById("age_text"+id).value;
 
 $.ajax
 ({
  type:'post',
  url:'modify_records.php',
  data:{
   edit_row:'edit_row',
   row_id:id,
   name_val:name,
   age_val:age
  },
  success:function(response) {
   if(response=="success")
   {
    document.getElementById("name_val"+id).innerHTML=name;
    document.getElementById("age_val"+id).innerHTML=age;
    document.getElementById("edit_button"+id).style.display="block";
    document.getElementById("save_button"+id).style.display="none";
   }
  }
 });
}

function delete_row(id)
{
 $.ajax
 ({
  type:'post',
  url:'modify_records.php',
  data:{
   delete_row:'delete_row',
   row_id:id,
  },
  success:function(response) {
   if(response=="success")
   {
    var row=document.getElementById("row"+id);
    row.parentNode.removeChild(row);
   }
  }
 });
}

function insert_row()
{
 var name=document.getElementById("new_name").value;
 var age=document.getElementById("new_age").value;

 $.ajax
 ({
  type:'post',
  url:'modify_records.php',
  data:{
   insert_row:'insert_row',
   name_val:name,
   age_val:age
  },
  success:function(response) {
   if(response!="")
   {
    var id=response;
    var table=document.getElementById("user_table");
    var table_len=(table.rows.length)-1;
    var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";

    document.getElementById("new_name").value="";
    document.getElementById("new_age").value="";
   }
  }
 });
}
modify_record.php

<?php
$host="localhost";
$username="root";
$password="";
$databasename="ajaxphp";

$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

if(isset($_POST['edit_row']))
{
 $row=$_POST['row_id'];
 $name=$_POST['name_val'];
 $age=$_POST['age_val'];

 mysql_query("update user_detail set name='$name',age='$age' where id='$row'");
 echo "success";
 exit();
}

if(isset($_POST['delete_row']))
{
 $row_no=$_POST['row_id'];
 mysql_query("delete from user_detail where id='$row_no'");
 echo "success";
 exit();
}

if(isset($_POST['insert_row']))
{
 $name=$_POST['name_val'];
 $age=$_POST['age_val'];
 mysql_query("insert into user_detail values('','$name','$age')");
 echo mysql_insert_id();
 exit();
}
?>

Automatically create cache file with php And Quickly Loaded in PHP Files

Automatically create cache file with php And Quickly Loaded in PHP Files


Hi Today Discussed Automatically create cache file with php and Quickly loaded in php files large number of data in mysql database is once run this file the data automatically create cache file and then quickly loaded this file follows briefly discussed.

Automatically create cache file with php And Quickly Loaded in PHP Files
Automatically create cache file with php And Quickly Loaded in PHP Files

Your php file quick load speed  increased your web site each every page loaded auto created cache file follows code.

<?php
function getUrl () {
    if (!isset($_SERVER['REQUEST_URI'])) {
    $url = $_SERVER['REQUEST_URI'];
    } else {
    $url = $_SERVER['SCRIPT_NAME'];
    $url .= (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER[ 'QUERY_STRING' ] : '';

    }
    return $url;
}

//getUrl gets the queried page with query string
function cache ($buffer) { //page's content is $buffer
    $url = getUrl();
    $filename = md5($url) . '.cache';
    $data = time() . '¦' . $buffer;
    $filew = fopen("cache/" . $filename, 'w');
    fwrite($filew, $data);
    fclose($filew);
    return $buffer;
}

function display () {
    $url = getUrl();
    $filename = md5($url) . '.cache';
    if (!file_exists("/cache/" . $filename)) {
    return false;
    }
    $filer = fopen("cache/" . $filename, 'r');
    $data = fread($filer, filesize("cache/" . $filename));
    fclose($filer);
    $content = explode('¦', $data, 2);
    if (count($content)!= 2 OR !is_numeric($content['0'])) {
        return false;
    }
    if (time()-(100) > $content['0']) { // 100 is the cache time here!!!
        return false;
    }
        echo $content['1'];
        die();
}

// Display cache (if any)
display();  // if it is displayed, die function will end the program here.

// if no cache, callback cache
ob_start ('cache');
?>

PHP Execute a HTTP POST Using PHP CURL

PHP Execute a HTTP POST Using PHP CURL

Today Discussed PHP Curl Post Means PHP Execute a HTTP POST Using PHP Curl.Well, there's a hurdle -- the information isn't going to be saved on the localhost database -- it needs to be stored in a remote database that I cannot connect directly to.

PHP Execute a HTTP POST Using PHP CURL
PHP Execute a HTTP POST Using PHP CURL

  1. User will submit the form, as usual.
  2. In the form processing PHP, I use cURL to execute a POST transmission to a PHP script on the customer's server.
  3. The remote script would do a MySQL INSERT query into the customer's private database.
This solution worked quite well so I thought I'd share it with you. Here's how you execute a POST using the PHP CURL library.


Curl Post Code Follows

//extract data from the post
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
 'lname' => urlencode($_POST['last_name']),
 'fname' => urlencode($_POST['first_name']),
 'title' => urlencode($_POST['title']),
 
);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

Abstract Classes and Interface in PHP

Abstract Classes and Interface in PHP

Today we discussed Abstract Classes and Interface in PHP Data abstraction first what is abstraction. As from name it seem like something that is hidden.  Yes nature of the abstract classes are same.Abstract classes are those classes which can not be directly initialized. Or in other word we can say that you can not create object of abstract classes.

Abstract Classes and Interface in PHP
Abstract Classes and Interface in PHP
  1. What is abstract classes.
  2. What is interface
  3. How to implement abstract classes in php
  4. How to implement interface in php
  5. Different between abstract classes and interface.
What is abstract Classes

 Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract. Abstract method are the method which is only defined but declared. This is not true definition as per my assumption. But your any class has at least one method abstract than your class is abstract class.Usually abstract class are also known as base class. We call it base class because abstract class are not the class which is available directly for creating object. It can only act as parent class of any normal class. You can use abstract class in class hierarchy. Mean one abstract class can inherit another abstract class also.



Abstract classes in PHP

Abstract Classes and Interface in PHP
Abstract Classes and Interface in PHP

Abstract classes in php are simillar like other oop languages. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.



abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php
abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();



Implementation of abstract method



abstract class abc

{

abstract protected function f1($a , $b);

}

class xyz extends abc

{

protected function f1($name , $address)

{

echo "$name , $address";

}

}

$a = new xyz();
abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();








Multiple document Attached Mail in PHP

Multiple document Attached Mail in PHP


Today Discussed Multiple document attached mail in PHP simple way. Normal core php form designed style css used and one or more file upload included form and most important once form tag include enctype="multipart/form-data" is type code and mail code follows .

Multiple document Attached Mail in PHP
Multiple document Attached Mail in PHP

  <form class="form-inline" role="form" method="post" enctype="multipart/form-data">
   <input type="file" value="" id="file1" name="file1" "> 
   <input type="file" value="" id="file2" name="file12" "> 
</form>

PHP Code:

 $folder = "fileupload/";
    $temp = explode(".", $_FILES["file1"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    $db_path = "$folder" . $newfilename;
    $listtype = array(
        '.doc' => 'application/msword',
        '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        '.rtf' => 'application/rtf',
        '.pdf' => 'application/pdf');
    if (is_uploaded_file($_FILES['file1']['tmp_name'])) {
        if ($key = array_search($_FILES['file1']['type'], $listtype))
            $file = move_uploaded_file($_FILES['file1'] ['tmp_name'], "$folder" . $newfilename);
    }
    else {
        //  echo "File Type Shosuld Be .Docx or .Pdf or .Rtf Or .Doc";
    }

Mail Function

  function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files) {

        $from = $senderName . " <" . $senderMail . ">";
        $headers = "From: $from";

        // boundary 
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

        // headers for attachment 
        $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

        // multipart boundary 
        $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

        // preparing attachments
        if (count($files) > 0) {
            for ($i = 0; $i < count($files); $i++) {
                if (is_file($files[$i])) {
                    $message .= "--{$mime_boundary}\n";
                    $fp = @fopen($files[$i], "rb");
                    $data = @fread($fp, filesize($files[$i]));
                    @fclose($fp);
                    $data = chunk_split(base64_encode($data));
                    $message .= "Content-Type: application/octet-stream; name=\"" . basename($files[$i]) . "\"\n" .
                            "Content-Description: " . basename($files[$i]) . "\n" .
                            "Content-Disposition: attachment;\n" . " filename=\"" . basename($files[$i]) . "\"; size=" . filesize($files[$i]) . ";\n" .
                            "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                }
            }
        }
        $message .= "--{$mime_boundary}--";
        $returnpath = "-f" . $senderMail;

        //send email
        $mail = @mail($to, $subject, $message, $headers, $returnpath);

        //function return true, if email sent, otherwise return fasle
        if ($mail) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

Crop Image in Core PHP

Crop Image in Core PHP

Today Discussed Crop Image in Core PHP. Image crop and create thumb image and upload save particular directory. crop this image and resize compressed image save a directory. code follow us. 
Crop Image in Core PHP
Crop Image in Core PHP
$upload_dir = "upload_pic";     // The directory for the images to be saved in
$upload_path = $upload_dir."/";    // The path to where the image will be saved
$large_image_prefix = "resize_";    // The prefix name to large image
$thumb_image_prefix = "thumbnail_";   // The prefix name to the thumb image
$large_image_name = $large_image_prefix.$_SESSION['random_key'];     // New name of the large image (append the timestamp to the filename)
$thumb_image_name = $thumb_image_prefix.$_SESSION['random_key'];     // New name of the thumbnail image (append the timestamp to the filename)
$max_file = "3";        // Maximum file size in MB
$max_width = "500";       // Max width allowed for the large image
$thumb_width = "100";      // Width of thumbnail image
$thumb_height = "100";      // Height of thumbnail image
// Only one of these image types should be allowed for upload
$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = ""; // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
    $image_ext.= strtoupper($ext)." ";
}

Image Resize Function


function resizeImage($image,$width,$height,$scale) {
 list($imagewidth, $imageheight, $imageType) = getimagesize($image);
 $imageType = image_type_to_mime_type($imageType);
 $newImageWidth = ceil($width * $scale);
 $newImageHeight = ceil($height * $scale);
 $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
 switch($imageType) {
  case "image/gif":
   $source=imagecreatefromgif($image); 
   break;
     case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
   $source=imagecreatefromjpeg($image); 
   break;
     case "image/png":
  case "image/x-png":
   $source=imagecreatefrompng($image); 
   break;
   }
 imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
 
 switch($imageType) {
  case "image/gif":
     imagegif($newImage,$image); 
   break;
       case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
     imagejpeg($newImage,$image,90); 
   break;
  case "image/png":
  case "image/x-png":
   imagepng($newImage,$image);  
   break;
    }
 
 chmod($image, 0777);
 return $image;
}
Resize Thumbnail Image Function

function resizeImage($image,$width,$height,$scale) {
 list($imagewidth, $imageheight, $imageType) = getimagesize($image);
 $imageType = image_type_to_mime_type($imageType);
 $newImageWidth = ceil($width * $scale);
 $newImageHeight = ceil($height * $scale);
 $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
 switch($imageType) {
  case "image/gif":
   $source=imagecreatefromgif($image); 
   break;
     case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
   $source=imagecreatefromjpeg($image); 
   break;
     case "image/png":
  case "image/x-png":
   $source=imagecreatefrompng($image); 
   break;
   }
 imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
 
 switch($imageType) {
  case "image/gif":
     imagegif($newImage,$image); 
   break;
       case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
     imagejpeg($newImage,$image,90); 
   break;
  case "image/png":
  case "image/x-png":
   imagepng($newImage,$image);  
   break;
    }
 
 chmod($image, 0777);
 return $image;
}
function getHeight($image) {
 $size = getimagesize($image);
 $height = $size[1];
 return $height;
}
//You do not need to alter these functions
function getWidth($image) {
 $size = getimagesize($image);
 $width = $size[0];
 return $width;
}

if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
 //Get the new coordinates to crop the image.
 $x1 = $_POST["x1"];
 $y1 = $_POST["y1"];
 $x2 = $_POST["x2"];
 $y2 = $_POST["y2"];
 $w = $_POST["w"];
 $h = $_POST["h"];
 //Scale the image to the thumb_width set above
 $scale = $thumb_width/$w;
 $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
 //Reload the page again to view the thumbnail
 header("location:".$_SERVER["PHP_SELF"]);
 exit();
}


if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
//get the file locations 
 $large_image_location = $upload_path.$large_image_prefix.$_GET['t'];
 $thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
 if (file_exists($large_image_location)) {
  unlink($large_image_location);
 }
 if (file_exists($thumb_image_location)) {
  unlink($thumb_image_location);
 }
 header("location:".$_SERVER["PHP_SELF"]);
 exit(); 
}
view.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <meta name="generator" content="WebMotionUK" />
 <title>WebMotionUK - PHP &amp; Jquery image upload &amp; crop</title>
 <script type="text/javascript" src="js/jquery-pack.js"></script>
 <script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>
</head>
<body>