Tag Archives: learn php online

Php 5 String Functions Reference


Php 5 String Functions Referencee : Here is the list of Php 5 String Functions


Php 5 String Functions Reference

[table caption=”Php 5 String FUnctions” width=”100%” colwidth=”20|100|200|200″ colalign=”left|left|left|left|left”]
no,Function,Description,Detail,Demo
1,addcslashes(),It Adds the backslash before the specified string,More Detail & Demo», Demo »
2,addslashes(),It adds backslash(\) before each single quote(‘) and double quote(“) in string,More Detail & Demo», Demo »
3,bin2hex(),bin2hex() converts the binary string to hexadecimal string,More Detail & Demo», Demo »
4,chop(),used to remove the whitespaces or predefined character from right,More Detail & Demo», Demo »
5,chr(),is used to convert an ASCII number to character,More Detail & Demo», Demo »
6,chunk_split(),chunk_split() Function splits the string in series of smaller parts.,More Detail & Demo», Demo »
7,convert_cyr_string(),Is Used to convert one character set to another character set.,More Detail & Demo», Demo »
8,convert_uuencode(),convert_uuencode() is used to encode a string using the uuencode algorithm.,More Detail & Demo», Demo »
9,convert_uudecode(),It is used to decode a string using the uudecode algorithm.,More Detail & Demo», Demo »
10,count_chars(),count_chars() Function splits the string in series of smaller parts.,More Detail & Demo», Demo »
11,crc32(),crc32() It creates the 32-Bit Cyclic redundancy checksum of a string.,More Detail & Demo», Demo »
12,crypt(),crypt() It encrypts the string using the DES Blowfish or MD5 algorithms.,More Detail & Demo», Demo »
13,echo(),echo() It Echo function is used to print the strings in php..,More Detail & Demo», Demo »
14,explode(),explode() converts string to array.,More Detail & Demo», Demo »
15,html_entity_decode(),html_entity_decode() It converts the html entities to its applicable characters,More Detail & Demo», Demo »
16,htmlspecialchars_decode(),htmlspecialchars_decode() It converts Some HTML entities to its characters equivalent.,More Detail & Demo», Demo »
17,htmlspecialchars(),htmlspecialchars() It converts Special Characters to HTML entities.,More Detail & Demo», Demo »
18,Implode(),htmlspecialchars_decode() It converts array into string.,More Detail & Demo», Demo »
19,number_format(),This function is used to format a number with grouped thousand.,More Detail & Demo», Demo »
20,number_format(),Is used to pad a string to new length with another string.,More Detail & Demo», Demo »
[/table]

Php json decode array example


Php json decode array example


Php json decode array example

$json = '["apple","orange","banana","mango"]';
$array = json_decode($json);
foreach($array as $item){

echo $item."
"; }

which will produce the following result;

// apple
// orange
// banana
// mango

Php implode array by newline


Php implode array by newline : You can use PHP_EOL to implode array by line break.


Php implode array by newline break

$array = implode(PHP_EOL, $array);

Which will break the string at the break line.

Php explode array at line break Example

$array = array('a','b','c');
$string = explode(PHP_EOL, $array);
echo $string;
// will produce 
// a
// b
// c

Php explode string by newline


Php explode string by newline : You can use PHP_EOL to explode string at line break.


Php explode string by newline break

$array = explode(PHP_EOL, $string);

Which will break the string at the break line.

Php explode array at line break Example

$string = " str1 
            str2
            str3";
$array = explode(PHP_EOL, $string);
print_r($array);
array('0'=>'str1','1'=>'str2','2'=>'str3');

Facebook style cover image reposition in php jquery

Facebook style cover image reposition in php jquery : In this post we are going to explain the functionality implemented just like facbook style cover image repostion in php and jquery.

Jquery Ui : Jquery ui is used to enable the draggable functionality for the selected image.

Php : We are using php on sever side to resize and crop the image on co-ordinates provided. Co-ordinates are passed to the server selected by the user.

Jquery Ui Draggable : Provides the draggable functionality on element. Event is triggered when we move mouse on the
element ie image in this case.
Jquery Function used for draggable functionality.

Facebook style cover image in PHP with Syntax

Jquery Ui : Draggable

function initUi(){
     
     
    $(function(){
    $(".coverimage").css('cursor','s-resize');
    var y1 = $('.imagecontainer').height();
    var y2 = $('.coverimage').height();
    $(".coverimage").draggable({
       scroll: false,
       axis: "y",
       drag: function(event, ui) {
             if(ui.position.top >= 0)
             {   
                                         
               ui.position.top = 0;
                                          
              }
              else if(ui.position.top <= y1 - y2)
              {
               ui.position.top = y1 - y2;
                                          
               }
    
            },
            stop: function(event, ui) {
            //####          
            $("#top").val(ui.position.top);
           
        }
        });                    
});
 }

Main page with above code and main layout : index.php

Javascript Code to handle the drag and save event.





  
  
  
  
  
  
  
  


    
  

PHP Code On Server Side : functions.php

Php code to Resize And Crop the image to Fit on container

 $h) {
      $imageHeight = floor(($h/$w)*$width);
      $imageWidth  = $width;
    } else {
      $imageWidth  = floor(($w/$h)*$height);
      $imageHeight = $height;
    }
    $x = 0;
  
  $new = imagecreatetruecolor($imageWidth, $imageHeight);
  // preserve transparency
  if($type == "gif" or $type == "png"){
    imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
    imagealphablending($new, false);
    imagesavealpha($new, true);
  }
  imagecopyresampled($new, $img, 0, 0, $x, 0, $imageWidth, $imageHeight, $w, $h);
  switch($type){
    case 'bmp': imagewbmp($new, $dst); break;
    case 'gif': imagegif($new, $dst); break;
    case 'jpg': imagejpeg($new, $dst); break;
    case 'png': imagepng($new, $dst); break;
  }
  return true;
}
function crop($source,$destination,$destinationWidth,$destinationHeight,$x1,$y1){
     if(!list($w, $h) = getimagesize($source)) return "Unsupported picture type!";
     $type = strtolower(substr(strrchr($source,"."),1));
      if($type == 'jpeg') $type = 'jpg';
      switch($type){
        case 'bmp': $copy = imagecreatefromwbmp($source); break;
        case 'gif': $copy = imagecreatefromgif($source); break;
        case 'jpg': $copy = imagecreatefromjpeg($source); break;
        case 'png': $copy = imagecreatefrompng($source); break;
        default : return "Unsupported picture type!";
      }
      // this is taken because of maintaining the aspect ratio for the croping to the exact height and width.
      $w = $destinationWidth;
      $h = $destinationHeight; 
      $new = imagecreatetruecolor($destinationWidth, $destinationHeight);
      imagecopyresampled($new, $copy, 0, 0, $x1, $y1, $destinationWidth, $destinationHeight, $w, $h);
       switch($type){
        case 'bmp': imagewbmp($new, $destination); break;
        case 'gif': imagegif($new, $destination); break;
        case 'jpg': imagejpeg($new, $destination); break;
        case 'png': imagepng($new, $destination); break;
      }
    return true;
}
?>

Main crop.php handling the complete server process :

Javascript Code to handle the drag and save event.

';

?>

Demo »

DemoDownload

Php ini_set display_errors

Php ini_set display_errors
You can eanble error reporting in php as below :
Add the following code in the top of your file.

How to create thumbnail image in php

How to create thumbnail image in php using ajax

For image upload we are going to use the ajax image upload plugin. We will add thumbnail creation in the ajax image upload plugin described in the post – http://tutorialsplane.com/ajax-image-upload-using-php-and-jquery-demo/.

We are going to modify and add the thumbnail function in the post : http://tutorialsplane.com/ajax-image-upload-using-php-and-jquery-demo/

The below function is called and the required parameters are passed to create the thumbnail of the the uploaded image.

Example

<?php

function createThumbs($pathToImages,$fname, $pathToThumbs, $thumbWidth ,$thumbHeight)
{
$srcFile = $pathToImages.$fname;
$thumbFile = $pathToThumbs.$fname;
if(!empty($fname))
{
try {
$type = strtolower(substr( $fname , strrpos( $fname , '.' )+1 ));

$thumbnail_width=$thumbWidth;
$thumbnail_height=$thumbHeight;

switch( $type ){
case 'jpg' : case 'jpeg' :
try{
$src = imagecreatefromjpeg( $srcFile ); break;
}
catch(Exception $e) {

echo $e->getMessage();
exit;
}
///$src = imagecreatefromjpeg( $srcFile ); break;
case 'jpeg' : case 'jpeg' :
try{
$src = imagecreatefromjpeg( $srcFile ); break;
}
catch(Exception $e) {
echo $e->getMessage();
exit;
}
case 'png' :

$src = imagecreatefrompng( $srcFile ); break;
case 'gif' :

$src = imagecreatefromgif( $srcFile ); break;
}
list($width_orig, $height_orig) = getimagesize($srcFile);
$ratio_orig = $width_orig/$height_orig;

if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}

$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle

$process = imagecreatetruecolor(round($new_width), round($new_height));

imagecopyresampled($process, $src, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$dest_img = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($dest_img, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

switch( $type ){
case 'jpg' : case 'jpeg' :
$src = imagejpeg( $dest_img , $thumbFile ); break;
case 'png' :
$src = imagepng( $dest_img , $thumbFile ); break;
case 'gif' :
$src = imagegif( $dest_img , $thumbFile ); break;
}
}catch(Exception $e) {
echo $e->getMessage();
exit;
}

}else{
echo "<p style='color:red'> Thumbnail Creation Error : Thumbnail name can't be empty please add the thumbnail name.</p>";
exit;
}

}

?>

DemoDownload

Ajax Image Upload PHP and jQuery Script Download Demo

Ajax Image Upload PHP and jQuery Script Download Demo : It is very simple to upload an image using jquery & php. In this script are going to use jQuery at client side and PHP at server side to upload an image without reloading or refreshing the page. You can try online demo and download the full script.

Ajax Image Upload PHP and jQuery Script Download Demo

Here are the steps to upload image in php using jquery. Let us go step by step.


Step 1

first create the form to select and upload the image.

Note : For Design we are using bootstrap.css

Create file upload-ajax-image.php

Create Image From

 <div class="col-sm-12"><div id="uploadedimage"></div>
<form role="form"  id="uploadImageForm" enctype= "multipart/form-data"  action="javascript:void(0)" onsubmit="uploadimage(this);">
<div class="form-group">
<label for="file">Select Image</label>
<input type="file" name="uploadImage" class="form-control" id="uploadImage"
placeholder="select file">
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>


Step 2

Create imageupload.js

Create Js File

function uploadimage(this){
$.ajax({
url: "uploadimageajax.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#uploadedimage").html(data);
}
});
}

Step 3

Create uploadimage.php

Which will upload the posted image by the jquery and ajax and will move in a folder ie. target folder in which you want to store images on the server.

Create upload php file

$target_dir = "uploads/";
$upload = 1;
$target_file = $target_dir . basename($_FILES["uploadImage"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Invalid Format.Only JPG, JPEG, PNG & GIF files are allowed.";
$upload = 0;
exit;
}if ($_FILES["uploadImage"]["size"] > 200000) {
echo "Sorry, your file is very large.";
$upload = 0;

exit;
}
if($upload == '1'){
$str = '';
if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $target_file)) {
$str .= "The file ". basename( $_FILES["uploadImage"]["name"]). " has been uploaded.";
$str .= "<img src='uploads/".$_FILES["uploadImage"]["name"]."'>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

Ajax Image Upload PHP and jQuery Script Download Demo


You can run demo to see the upload functionality online or you can directly download and unzip the file to run the demo on your machine.

DemoDownload

Ajax Image Upload PHP and jQuery Script Download Demo

Ajax image upload in php