article

Showing posts with label web-development (PHP). Show all posts
Showing posts with label web-development (PHP). Show all posts

Tuesday, August 19, 2014

Creating a RESTful Web Service in PHP

Creating a RESTful Web Service in PHP
<?
// process client request via url
header("Content-Type:application/json");
if (!empty($_GET['name'])) {
 
 $name = $_GET['name'];
 $price = get_price($name);
 
 if (empty($name))
  deliver_response(200,"book not found", null);
 else
  deliver_response(200,"book found", $price);
}else{
 deliver_response(400,"Invalid request", null);
}

function deliver_response($status,$status_message,$data)
{
 header("HTTP/1.1 $status $status_message");
 $response['status'] = $status;
 $response['status_message'] = $status_message;
 $response['data']=$data;

 $json_response = json_encode($response); 
 echo $json_response;
}
function get_price($find) {
 $books=array(
  "java" =>299,
  "c" =>348,
  "php" =>267
 );

 foreach ($books as $book=>$price){
 if ($book==$find) {
  return $price;
  break;
 }
 }
}
?>
//.htaccess file
# Turn on the rewrite engin
Options +FollowSymLinks
RewriteEngine On

#request routing
RewriteRule ^([a-zA-Z]*)$ index.php?name=$1 [nc,qsa]

Sunday, May 11, 2014

Ajax Contact Form with an Attachment (jQuery & PHP)

Ajax Contact Form with an Attachment (jQuery and  PHP)
//index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Ajax Contact Form</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //get input field values
  
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_phone      = $('input[name=phone]').val();
  var attach_file     = $('input[name=file_attach]')[0].files[0];
        var user_message    = $('textarea[name=message]').val();
        
        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
   $(".loading-img").show(); //show loading image
   $(".submit_btn").hide(); //hide submit button
   
   //data to be sent to server   
   var post_data = new FormData();    
   post_data.append( 'userName', user_name );
   post_data.append( 'userEmail', user_email );
   post_data.append( 'userPhone', user_phone );
   post_data.append( 'userMessage',user_message);
   post_data.append( 'file_attach', attach_file );
   
   //instead of $.post() we are using $.ajax()
   //that's because $.ajax() has more options and can be used more flexibly.
   $.ajax({
     url: 'contact_me.php',
     data: post_data,
     processData: false,
     contentType: false,
     type: 'POST',
     dataType:'json',
     success: function(data){
     //load json data from server and output message     
     if(data.type == 'error')
     {
      output = '<div class="error">'+data.text+'</div>';
     }else{
      output = '<div class="success">'+data.text+'</div>';
      
      //reset values in all input fields
      $('#contact_form input').val(''); 
      $('#contact_form textarea').val(''); 
     }
     
     $("#result").hide().html(output).slideDown(); //show results from server
     $(".loading-img").hide(); //hide loading image
     $(".submit_btn").show(); //show submit button
     }
   });

        }
    });
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<fieldset id="contact_form">
<legend>Contact Form</legend>
    <div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>
    
    <label for="email"><span>Email Address</span>
    <input type="email" name="email" id="email" placeholder="Enter Your Email" />
    </label>
    
    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" placeholder="Phone Number" />
    </label>
    
    <label for="phone"><span>Attachment</span>
    <input type="file" name="file_attach" id="file_attach" />
    </label>
    
    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>
    
    <label><span> </span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    <img src="ajax-loader.gif" class="loading-img" style="display:none">
    </label>
</fieldset>
</body>
</html>
//style.css
#contact_form{
 width:350px;
 padding:20px;
 border: 1px solid #DDD;
 border-radius: 5px;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 11px;
 font-weight: bold;
 color: #666666;
 background:#FAFAFA;
 margin-right: auto;
 margin-left: auto;
}
#contact_form legend{
 font-size: 15px;
 color: #C9C9C9;
}
#contact_form label{
 display: block;
 margin-bottom:5px;
}
#contact_form label span{
 float:left;
 width:100px;
 color:#666666;
}
#contact_form input{
 height: 25px;
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
#contact_form textarea{
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 height:100px;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
.submit_btn {
 border: 1px solid #D8D8D8;
 padding: 5px 15px 5px 15px;
 color: #8D8D8D;
 text-shadow: 1px 1px 1px #FFF;
 border-radius: 3px;
 background: #F8F8F8;
}
.submit_btn:hover 
{
 background: #ECECEC;
}
.success{
 background: #CFFFF5;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #B9ECCE;
 border-radius: 5px;
 font-weight: normal;
}
.error{
 background: #FFDFDF;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #FFCACA;
 border-radius: 5px;
 font-weight: normal;
}
//contact_me.php
<?php
if($_POST)
{
 $to_Email    = "recipient_email@yourdomain.com"; //Replace with recipient email address
 $subject        = 'contact form'; //Subject line for emails
 
 //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 
  //exit script outputting json data
  $output = json_encode(
  array(
   'type'=>'error', 
   'text' => 'Request must come from Ajax'
  ));
  
  die($output);
    } 
 
 //check $_POST vars are set, exit if any missing
 if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
  die($output);
 }

 //Sanitize input data using PHP filter_var().
 $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
 $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
 $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
 $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
 
 //additional php validation
 if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
  die($output);
 }
 if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
  die($output);
 }
 if(!is_numeric($user_Phone)) //check entered data is numbers
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
  die($output);
 }
 if(strlen($user_Message)<5) //check emtpy message
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
  die($output);
 }
 
 ### Attachment Preparation ###
 $file_attached = false; //initially file is not attached
 
 if(isset($_FILES['file_attach'])) //check uploaded file
 {
  //get file details we need
  $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
  $file_name     = $_FILES['file_attach']['name'];
  $file_size     = $_FILES['file_attach']['size'];
  $file_type     = $_FILES['file_attach']['type'];
  $file_error    = $_FILES['file_attach']['error'];
  
  //exit script and output error if we encounter any
  if($file_error>0)
  {
   $mymsg = array( 
   1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
   2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
   3=>"The uploaded file was only partially uploaded", 
   4=>"No file was uploaded", 
   6=>"Missing a temporary folder" ); 
   
   $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
   die($output); 
  }
 
  //read from the uploaded file & base64_encode content for the mail
  $handle = fopen($file_tmp_name, "r");
  $content = fread($handle, $file_size);
  fclose($handle);
  $encoded_content = chunk_split(base64_encode($content));
  
  //now we know we have the file for attachment, set $file_attached to true
  $file_attached = true;
 }

 if($file_attached) //continue if we have the file
 {
  # Mail headers should work with most clients (including thunderbird)
  $headers = "MIME-Version: 1.0\r\n";
  $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
  $headers .= "From:".$user_Email."\r\n";
  $headers .= "Subject:".$subject."\r\n";
  $headers .= "Reply-To: ".$user_Email."" . "\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
 
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";
  
  $headers .= "--".md5('boundary2')."\r\n";
  $headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
  $headers .= $user_Message."\r\n\r\n";
 
  $headers .= "--".md5('boundary2')."--\r\n";
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type:  ".$file_type."; ";
  $headers .= "name=\"".$file_name."\"\r\n";
  $headers .= "Content-Transfer-Encoding:base64\r\n";
  $headers .= "Content-Disposition:attachment; ";
  $headers .= "filename=\"".$file_name."\"\r\n";
  $headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
  $headers .= $encoded_content."\r\n";
  $headers .= "--".md5('boundary1')."--"; 
 }else{
  # Mail headers for plain text mail
  $headers = 'From: '.$user_Email.'' . "\r\n" .
  'Reply-To: '.$user_Email.'' . "\r\n" .
  'X-Mailer: PHP/' . phpversion();
 }
 
 //send the mail
 $sentMail = @mail($to_Email, $subject, $user_Message, $headers);
 
 if(!$sentMail) //output success or failure messages
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
  die($output);
 }else{
  $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
  die($output);
 }
}
?>

Sunday, March 23, 2014

Making AJAX request with JSON

Making AJAX request with JSON


 testjson.js
 
$.post("http://localhost/demo/controller/function", {'name1' : value1, 'name2' : value2}, //name1 is the name of the parameter that send, something similar to name1=val1&name2=val2
    function(data)
    {
        $.each(data.items, function(i,item){
            alert("value: "+item.value+" name: "+item.name); //item.value e item.name because in the data object the information is set in this way: [{value:name},{value:name}...]
        });
    }, "json"
 );

Controller
 
function funcion()
 {
   $data["my_data"] = $this->example_model->get_examples($this->input->post('name1'),$this->input->post('name2'));
   //$data["my_data"] will contain an array like Array("0" => Array("value" => value1, "name" => name1), "1" => Array("value" => value2, "name" => name2)...)
   $this->load->view('json/json_example_view',$data);
 }

View
 
<?php echo json_encode($datos); ?>

Saturday, March 22, 2014

Upload file in yiiframework

Upload file in yiiframework


Create table t_users
 id_user varchar(30)
profile_picture varchar(100)
name varchar(50)

Form
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'tuser-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">
 Fields with <span class="required">*</span> are required.
</p>
 
<?php echo $form->errorSummary($model); ?>
 <div class="row">
  <?php echo $form->labelEx($model,'profile_picture'); ?>
  <?php echo $form->fileField($model,'profile_picture',array('size'=>60,'maxlength'=>200)); ?>
  <?php echo $form->error($model,'title'); ?>
 </div>
 
Controller 
$model->attributes=$_POST['TUser'];
 $model->profile_picture=CUploadedFile::getInstance($model, 'profile_picture');
 if($model->save()){
  if(strlen($model->profile_picture)>0)
   $model->profile_picture->saveAs(Yii::app()->basePath.'/../upload/'.$model->profile_picture);
  $this->redirect(array('view','id'=>$model->id_user));
 }
 
 filter files use the rules in your model
 public function rules()
    {
        return array(
            array('picture_profile', 'file', 'types'=>'jpg, gif, png'),
           ...
        );
    }

Make dropdownlist in yii framework

Make dropdownlist in yii framework

Create table tbl_country

 country_name  | id
 Philippines       | 1
 USA               | 2

<div class="row">
 <?php echo $form->dropDownList($model,'country_id',
  CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
  array('empty'=>'Select Country'))?>
</div>

Make checkbox using ajax load in yiiframework

Make checkbox using ajax load in yiiframework


 
<?php echo CHtml::checkBox("load_ajax",false,array('id'=>'load_risk_all'));echo "Load All Risk Child";
$url=CController::createUrl('project/vieweach',array('project_id'=>$model->project_id));
Yii::app()->clientScript->registerScript("check",
           '$("#load_risk_all").change(function(){
             if($(this).is(":checked")){
              $("#load_risk").load("'.$url.'");
              $("#load_risk").fadeIn();
             }else{
              $("#load_risk").html("");
             }
             })
          ',
           CClientScript::POS_READY);
 
?>
<div id="load_risk">
</div>

load() function in jQuery for loading the ajax content using $.ajax functions
$this->renderPartial('/risk/view_each',array('provider'=>$provider),false,true);

onChange event in checkbox htmlOption for supporting your own javascript model 
<?php echo CHtml::checkbox("load risk",false,array("onChange"=>"js:yourcustomfunction()")); ?> 

Using CMaskField in your yii framework

Using CMaskField in your yii framework


 
<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '(999) 999-9999? x99999',
'htmlOptions' => array('size' => 6)
));
?>

<?php
$this->widget('CMaskedTextField', array(
'model' => $model,
'attribute' => 'aluguel',
'mask' => '9.999,99',
'charMap' => array('.'=>'[\.]' , ','=>'[,]'),
'htmlOptions' => array('size' => 6)));
?>

How to make CGridview with dropdown filter

How to make CGridview with dropdown filter


 
$this-<widget('zii.widgets.grid.CGridView',array(
   'dataProvider'=<$model-<search(),
   'id'=<'risk-id',
   'filter'=<$model,
   'columns'=<array(
   array(
      'name'=<'No',
      'type'=<'raw',
      'value'=<'$this-<grid-<dataProvider-<pagination-<currentPage*$this-<grid-<dataProvider-<pagination-<pageSize + $row+1',//this for the auto page number of cgridview
      'filter'=<''//without filtering 
   ),
   array(
      'name'=<'name',
      'type'=<'raw',
      'value'=<'Chtml::link(Chtml::encode($data["name"]),array("risk/view","id"=<$data["risk_id"]))',
      'filter'=<CHtml::listData(Risk::model()-<findAll(
                  array(
                   'select'=<array('name'),
                   'distinct'=<true
                    
                  )),"name","name")//this is the focus of your code
       
   ),
   array(
      'name'=<'date_identified',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<date_identified)'
   ),
   array(
      'name'=<'description',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<description)'
   ),
   array(
      'name'=<'type',
      'type'=<'raw',
      'value'=<'Chtml::encode($data-<type)',
       
   ),
   array(
      'name'=<'link',
      'type'=<'raw',
      'value'=<'$data-<link'
   ),
    
 
)
));

Alternative Way to make Dropdown menu in yii

Alternative Way to make Dropdown menu in yii


 
<div class="row">
  <?php echo $form->dropDownList($model,'country_id',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
Or other option
<div class="row">
  <?php echo CHtml::dropDownList('Users[country_id'],'',
   CHtml::listData(Country::model()->findAll(), 'id', 'country_name'),
   array('empty'=>'Select Country'))?>
 </div>
 

Wednesday, October 9, 2013

Uploading using jquery ajax

Uploading using jquery ajax
//index.html
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Uploading using jquery ajax</title>
    <link rel="stylesheet" href="style.css" />
</head>
<body>
 <div id="main">
  <h1>Upload Your Images</h1>
  <form method="post" enctype="multipart/form-data"  action="upload.php">
      <input type="file" name="images" id="images" multiple />
      <button type="submit" id="btn">Upload Files!</button>
     </form>

   <div id="response"></div>
  <ul id="image-list">

  </ul>
 </div>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script src="upload.js"></script>
</body>
</html>
//upload.js
(function () {
 var input = document.getElementById("images"), 
  formdata = false;

 function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
     li   = document.createElement("li"),
     img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
  list.appendChild(li);
 }   

 if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
 }
 
  input.addEventListener("change", function (evt) {
   document.getElementById("response").innerHTML = "Uploading . . ."
   var i = 0, len = this.files.length, img, reader, file;
 
  for ( ; i < len; i++ ) {
   file = this.files[i];
 
   if (!!file.type.match(/image.*/)) {
    if ( window.FileReader ) {
     reader = new FileReader();
     reader.onloadend = function (e) { 
      showUploadedItem(e.target.result, file.fileName);
     };
     reader.readAsDataURL(file);
    }
    if (formdata) {
     formdata.append("images[]", file);
    }
   } 
  }
 
  if (formdata) {
   $.ajax({
    url: "upload.php",
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    success: function (res) {
     document.getElementById("response").innerHTML = res; 
    }
   });
  }
 }, false);
}());
//upload.php
//create uploads folder root directory
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $name = $_FILES["images"]["name"][$key];
        move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
    }
}
echo "<h2>Successfully Uploaded Images</h2>";
//style.css
body {
 font: 14px/1.5 helvetica-neue, helvetica, arial, san-serif;
 padding:10px;
}
h1 {
 margin-top:0;
}
#main {
 width: 300px;
 margin:auto;
 background: #ececec;
 padding: 20px;
 border: 1px solid #ccc;
}
#image-list {
 list-style:none;
 margin:0;
 padding:0;
}
#image-list li {
 background: #fff;
 border: 1px solid #ccc;
 text-align:center;
 padding:20px;
 margin-bottom:19px;
}
#image-list li img {
 width: 258px;
 vertical-align: middle;
 border:1px solid #474747;
}

Saturday, September 7, 2013

File Upload using php

File Upload using php
index.html
<html> 
<body>
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form> 
</body> 
</html>
//upload.php
<?php
//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
 ($_FILES["uploaded_file"]["size"] <350000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/upload/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

Pagenation using php class

Pagenation using php class
<?php
class paginate{
var $current;
var $rows;
var $start_row;
var $total_data;
 function paginate($current_page,$totaldata,$rows_page = 10){
  $this->rows = $rows_page;
  $this->total_data = $totaldata;
  if($current_page < 1 or $current_page > $this->getTotalPage()){
   $this->current = 1;
  }
  else{
   $this->current = $current_page;
  }
 }
 function getTotalPage(){
  $total = ceil($this->total_data / $this->rows);
  return $total;
 }
 function getLimit(){
  if($this->current <= 1){
   $this->start_row = 0;
  }
  else{
   $this->start_row = $this->rows*($this->current-1);
  }
  return ' LIMIT '.$this->start_row.','.$this->rows;
 }
 function getNext(){
  if($this->current < $this->getTotalPage()){
   return $this->current + 1;
  }
 }
 function getPrevious(){
  if($this->current > 1){
   return $this->current - 1;
  }
 }
 function getPages(){
  $first = false; $last = false;
  if($this->getTotalPage() == 0){
   return false;
  }
  elseif($this->getTotalPage() > 10){
   for($i=1; $i<=$this->getTotalPage();$i++){
    if($i == $this->current){
     $page[] = array(
      'link' => false,
      'page' => $i
     );
    }
    elseif($i < $this->current-3 and $i > 3 and $i < $this->current+5 ){
     if(!$first){
      $page[] = array(
       'link' => false,
       'page' => '...',
      );
     }
     $first = true;
    }
    elseif($i < $this->getTotalPage()-3 and $i > $this->current+5){
     if(!$last){
      $page[] = array(
       'link' => false,
       'page' => '...',
      );
     }
     $last = true;
    }
    else{
     $page[] = array(
      'link' => true,
      'page' => $i
     );
    }
   }
  }
  else{
   for($i=1; $i<= $this->getTotalPage();$i++){
    if($i == $this->current){
     $page[] = array(
      'link' => false,
      'page' => $i
     );
    }
    else{
     $page[] = array(
      'link' => true,
      'page' => $i
     );
    }
   }
  }
  return $page;
 }
 function navigation($url=null,$attr=array()){
  $parm = '';
  if(is_array($attr)){
   foreach($attr as $name => $val){
    $parm .= ' '.$name.'="'.$val.'"';
   }
  }
  $nav = null;
  if($this->getPrevious()){
   $nav .= '<a href="'.$url.'&page='.$this->getPrevious().'" '.$parm.'>Previous</a> | ';
  }
  if($this->getPages()){
   foreach($this->getPages() as $name => $val){
    if($val['page'] != 1){
     $nav .= ', ';
    }
    if($val['link']){
     $nav .= '<a href="'.$url.'&page='.$val['page'].'" '.$parm.'>'.$val['page'].'</a>';
    }
    else{
     $nav .= '<b>'.$val['page'].'</b>';
    }
   }
  }
  if($this->getNext()){
   $nav .= ' | <a href="'.$url.'&page='.$this->getNext().'" '.$parm.'>Next</a>';
  }
  return $nav;
 }
}


/** example **/
if(isset($_GET['page'])){
 $page = $_GET['page'];
}
else{
 $page = 1;
}
$totaldata = 200;
$row_per_page = 10;
$paginate = new paginate($page,$totaldata,$row_per_page);

echo 'Limit for Query: SELECT * FROM `table`'.$paginate->getLimit();
echo '<br/>';
echo 'Current Page: '.$paginate->current;
echo '<br/>';
echo 'Pages Navigation: '.$paginate->navigation('index.php?',array('id' => 'page'));
echo '<br/>';
echo 'Total Page: '.$paginate->getTotalPage();
?>

Sunday, August 25, 2013

Creating simple class php interest Calculator

Creating simple class php interest Calculator 

<?php
//Creating class interestCalculator
class interestCalculator
{
public $rate;
public $duration;
public $capital;
public function calculateInterest()
{
return ($this->rate*$this->duration*$this->capital)/100;
}
}
//Creating  various object of class interestCalculator to calculate interest on various amount
$cls1 = new interestCalculator();
$cls2 = new $cls1;
$cls1->rate =2;
$cls1->duration =3;
$cls1->capital = 300;

$cls2->capital = 400;

$interest1 = $cls1->calculateInterest();
$interest2  = $cls2->calculateInterest();
echo "$interest1 -- $interest2";

Thursday, August 15, 2013

Simple Class login using php

Simple Class login using php 
 
<?
class UserAuth {
 var $user;
 var $pass;
 function isUserValid($user, $pass) {
  $sql = "select uid, first_name from $users_tb where user_name='$user' and password='$pass'";
  $result = mysql_query($sql);
  $rows   = mysql_num_rows($result);
  if($rows == 1) {
   $result_row = mysql_fetch_row($result);
   return $result_row;
  }
  else {
   return "0";
  }
 }
}
$userauth = new UserAuth;

session_start();
$user = $_POST['uname'];
$pass = $_POST['password'];
$val = $userauth->isUserValid($user, $pass);
if($val == "0") {
 header("Location: login.php");
}
else {
 $_SESSION['uid'] = $val[0];
 $_SESSION['fname'] = $val[1];
 $_SESSION['uname'] = $user;
 header("Location: SchedulerMain.php");
}
?>
<form name="scheduler_login" method="post" action="UserAuthController.php">
User name<input type=text size=15 name=uname>
Password<input type=password size=15 name=password>
<input type=submit name=submit value="Submit"> 
</form>

Saturday, August 3, 2013

Defining and Using Functions in PHP

Defining and Using Functions in PHP 

A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable


<?php
//Defining a Function
//syntax for defining a function
function addNumbers($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}
$total = addNumbers(5, 10); 
//echo $total; //result 15

//Organizing Functions
function hello() {
    echo "<h1>HELLO!</h1>";
    echo "<p>Welcome to my web site</p>";
}

function printBreak($text) {
    echo "$text<br>";
}

function addNumbers($num1, $num2) {
     return $num1 + $num2;
}

echo hello();
echo printBreak("This is a line");
echo addNumbers(3.75, 5.645); //9.39536.75

//Accepting a Variable Number of Arguments
function calcAverage() {
    // initialize value to be used in calculation
    $total = 0;       

    // find out how many arguments were given
    $arguments = func_num_args();      

    // loop to process each argument separately
    for ($i = 0; $i < $arguments; $i++) {
        // add the value in the current argument to the total
        $total += func_get_arg($i);
    }

    // after adding all arguments, calculate the average
    $average = $total / $arguments;  

    // return the average
    return $average;
}

// invoke the function with 5 arguments
//echo calcAverage(44, 55, 66, 77, 88); //output 66   

// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75

Friday, August 2, 2013

Passing array of checkbox values to php through jQuery

Passing array of checkbox values to php through jQuery 
 
//index.hmtl
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
                function doit() {
                        var p=[];
                        $('input.cb').each( function() {
                                if($(this).attr('checked')) {
                                        p.push($(this).attr('rel'));
                                }
                        } );
                        $.ajax( {
                                url:'process.php',
                                type:'POST',
                                data: {list:p},
                                success: function(res) {
                                        alert(res);
                                }
                        });
                }
        </script>

        <input type="checkbox" class="cb" rel="1"></input>Test 1<br />
        <input type="checkbox" class="cb" rel="2"></input>Test 2<br />
        <input type="checkbox" class="cb" rel="3"></input>Test 3<br />
        <a href="javascript:void(0)" onclick="doit()">Click</a>
//process.php
<?php
print_r(@$_POST['list']);
?>

Tuesday, July 30, 2013

PHP Tutorial: Classes and OOP

PHP Tutorial: Classes and OOP 

 
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();

//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();

//Ex. more functions
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced

//final version
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();

echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>

Friday, July 26, 2013

Username availability check using PHP and jQuery

Username availability check using PHP and jQuery
 
<?php

/* CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100)  NOT NULL',
PRIMARY KEY (`id`)
) */
//Username availability check using PHP and jQuery
//if we got something through $_POST
if (isset($_POST['user'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $username = mysql_real_escape_string($_POST['user']);
    // build your query to the database
    $sql = "SELECT count(*) as num FROM users WHERE username = " . $username;
    // get results
    $row = $db->select_single($sql);
    if($row['num'] == 0) {
        echo 'Username <em>'.$username.'</em> is available!';
    } else {
        echo 'Username <em>'.$username.'</em> is already taken!';
    }
}
?>
<script>
$(function() {
$("#sub").click(function() {
    // getting the value that user typed
    var checkString    = $("#username_box").val();
    // forming the queryString
    var data            = 'user='+ checkString;
 
    // if checkString is not empty
    if(checkString) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "do_check.php",
            data: data,
            beforeSend: function(html) { // this happen before actual call
                $("#results").html('');
            },
            success: function(html){ // this happen after we get result
                $("#results").show();
                $("#results").append(html);
            }
        });
}
return false;
});
});
</script>
<form action="do_check.php" method="post">
    <input id="username_box" class="search_box" name="username" type="text" />
    <input id="sub" type="submit" value="Check" />
</form>

Thursday, July 25, 2013

PHP Multiple Atachment Send

PHP Multiple Atachment Send 


E-mail with Attachment
 <?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   // we'll begin by assigning the To address and message subject
   $to="somebody@example.com";
   $subject="E-mail with attachment";

   // get the sender's name and email address
   // we'll just plug them a variable to be used later
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message="This is an example";

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary 
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
  
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
  
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
  
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
  
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the 
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" 
   enctype="multipart/form-data" name="form1">
   <p>From name: <input type="text" name="fromname"></p>
   <p>From e-mail: <input type="text" name="fromemail"></p>
   <p>File: <input type="file" name="file1"></p>
   <p>File: <input type="file" name="file2"></p>
   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>

Sanitize Input Form

Sanitize Input Form

 
<?php
include('connect.php');
$conn = db_connect();
 
 function cleanInput($input) {
  $search = array(
   '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
   '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
   '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
   '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
 );
  $output = preg_replace($search, '', $input);
  return $output;
 }

?>
<?
if(isset($_POST["submit"]))
{
 $_username = cleanInput($_POST["_username"]);
 $_password = md5($_POST["_password"]);  
 $sql_insert = "INSERT INTO tbl_admin(_username, _password) VALUES ('$_username', '$_password')";
 $result = mysql_query($sql_insert);
 echo "records save"; 
 //echo "<script>
 //   window.location='index.php';
 //    </script>";
 //
}
?>
<div style="padding-left:50px; font-weight:bold; font-size:18px; margin-bottom:20px; color:#ffffff">
 ADD NEW Users
</div>
<form name="subjadd" action="" method="post">
 <table width="96%" border="0" cellspacing="3" cellpadding="4">
  <tr>
   <th>User name:</th>
   <td><input name="_username" type="text" size="40"></td>
  </tr>
  <tr>
   <th>Password</th>
   <td><input name="_password" type="text" size="40"></td>
  </tr>
  <tr>
   <th></th>
   <td>
    <input type="submit" name="submit" value="Add New!">
</td>
  </tr>
 </table>
</form>

Related Post