Latest Post
Tampilkan postingan dengan label php example. Tampilkan semua postingan
Tampilkan postingan dengan label php example. Tampilkan semua postingan

Concatenate html tags to string in php

Written By Unknown on Selasa, 29 Oktober 2013 | 23.07

To add html tags to string in php ... You have to concatenate html tags with string using htmlentities()
as shown below
$newstring="<u>".htmlentities("test")."</u>";
Here i have added <u> tag to my string test which is passed to htmlentities() function for concatenation.

For more details see the example
Example:

<?php
$mystring="Hello ... This is my test string . I am testing it for htmlentities()";
echo "This is string before adding html tags"."</br>";
echo "</br>";
echo $mystring;
echo "</br>";
echo "</br>";
$newstring="<u>".htmlentities("test")."</u>";
$finalstring=str_replace("test",$newstring,$mystring);
echo "This is string after add html tags"."</br>";
echo "</br>";
echo $finalstring;
?>


htmlentities

PHP cURL simple tutorial

Written By Unknown on Selasa, 22 Oktober 2013 | 06.19

CURL is a reflective object-oriented programming language for interactive web applications whose goal is to provide a smoother transition between formatting and programming. It makes it possible to embed complex objects in simple documents without needing to switch between programming languages or development platforms.

The strong point of cURL is the number of data transfer protocols it supports. It supports FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, FILE and LDAP.

PHP cURL allows you to read websites, upload files, upload data, fetch data and lots of more stuff ... Now its the time to see what we can do we PHP cURL...

PHP cURL example-1 :

<?php
$ch = curl_init ("http://www.alexa.com");             /** Initialise curl with url of alexa.com **/


curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);    /** Tell php curl that we want the data returned to us **/


$data = curl_exec ($ch);                            /** Execution of curl and result will be stored in $data **/

echo "<pre>";
print_r($data); /**preview result**/
?>


To understand more about cURL defination visit : PHP cURL

Upload and save image with thumbnail in php

Written By Unknown on Senin, 07 Oktober 2013 | 05.39

upload - This is the directory where i will save my image
upload/thumbs - This is the directory where i will save my thumbnails


<?php
if($_POST){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0 && $_FILES["file"]["name"]!=' ')
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    $dir="upload";
    if (!is_dir($dir)) {
            mkdir($dir);        
        }
   if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      echo"</br>";
      thumbs("upload");
      }
    }
  }
else
  {
  echo "Invalid file";
  }
 }
?>
<html>
<body>


<form action="#" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>


<?php
/**Function to create thumbnails*/
function thumbs($orig_directory){
   //Full path to image folder /* change this path */
    $thumb_directory =  $orig_directory;    //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
    $dir_handle = @opendir($orig_directory); //Open Full image dirrectory
    if ($dir_handle > 1){ //Check to make sure the folder opened
  
    $allowed_types=array('jpg','jpeg','gif','png');
    $file_parts=array();
    $ext='';
    $title='';
    $i=0;


while ($file = @readdir($dir_handle))
{

    /* Skipping the system files: */
    if($file=='.' || $file == '..') continue;

    $file_parts = explode('.',$file);    //This gets the file name of the images
    $ext = strtolower(array_pop($file_parts));

    /* Using the file name (withouth the extension) as a image title: */
    $title = implode('.',$file_parts);
    $title = htmlspecialchars($title);

    /* If the file extension is allowed: */
    if(in_array($ext,$allowed_types))
    {

        /* If you would like to inpute images into a database, do your mysql query here */

        /* The code past here is the code at the start of the tutorial */
        /* Outputting each image: */

        $nw = 150;
        $nh = 100;
        $source = "{$orig_directory}/{$file}";
        $stype = explode(".", $source);
        $stype = $stype[count($stype)-1];
        $dir="{$thumb_directory}/thumbs";
        if (!is_dir($dir)) {
                mkdir($dir);       
        }
        $dest = "{$thumb_directory}/thumbs/{$file}";

        $size = getimagesize($source);
        $w = $size[0];
        $h = $size[1];

        switch($stype) {
            case 'gif':
                $simg = imagecreatefromgif($source);
                break;
            case 'jpg':
                $simg = imagecreatefromjpeg($source);
                break;
            case 'png':
                $simg = imagecreatefrompng($source);
                break;
        }

        $dimg = imagecreatetruecolor($nw, $nh);
        $wm = $w/$nw;
        $hm = $h/$nh;
        $h_height = $nh/2;
        $w_height = $nw/2;

        if($w> $h) {
            $adjusted_width = $w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;
            imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
        } elseif(($w <$h) || ($w == $h)) {
            $adjusted_height = $h / $wm;
            $half_height = $adjusted_height / 2;
            $int_height = $half_height - $h_height;

            imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
        } else {
            imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
        }
            imagejpeg($dimg,$dest,100);
        }
}
 echo "Coversion Successfully completed";
/* Closing the directory */
@closedir($dir_handle);

}
}
?>

Create thumbnails for complete directory in php

Create thumbnails for complete directory

If you wish to create thumbnails of large number of images then use the below php code
to create thumbnails .To create thumbnails, just give the path to images directory to
$orig_directory variable and run the script and your work is done ..!!


<?php

    $orig_directory = "img";     //Full path to image folder /* change this path */
    $thumb_directory =  $orig_directory;    //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
    $dir_handle = @opendir($orig_directory); //Open Full image dirrectory
    if ($dir_handle > 1){ //Check to make sure the folder opened
   
    $allowed_types=array('jpg','jpeg','gif','png');
    $file_parts=array();
    $ext='';
    $title='';
    $i=0;


while ($file = @readdir($dir_handle))
{

    /* Skipping the system files: */
    if($file=='.' || $file == '..') continue;

    $file_parts = explode('.',$file);    //This gets the file name of the images
    $ext = strtolower(array_pop($file_parts));

    /* Using the file name (withouth the extension) as a image title: */
    $title = implode('.',$file_parts);
    $title = htmlspecialchars($title);

    /* If the file extension is allowed: */
    if(in_array($ext,$allowed_types))
    {

        /* If you would like to inpute images into a database, do your mysql query here */

        /* The code past here is the code at the start of the tutorial */
        /* Outputting each image: */

        $nw = 150;
        $nh = 100;
        $source = "{$orig_directory}/{$file}";
        $stype = explode(".", $source);
        $stype = $stype[count($stype)-1];
        $dir="{$thumb_directory}/thumbs";
        if (!is_dir($dir)) {
                mkdir($dir);        
        }
        $dest = "{$thumb_directory}/thumbs/{$file}";

        $size = getimagesize($source);
        $w = $size[0];
        $h = $size[1];

        switch($stype) {
            case 'gif':
                $simg = imagecreatefromgif($source);
                break;
            case 'jpg':
                $simg = imagecreatefromjpeg($source);
                break;
            case 'png':
                $simg = imagecreatefrompng($source);
                break;
        }

        $dimg = imagecreatetruecolor($nw, $nh);
        $wm = $w/$nw;
        $hm = $h/$nh;
        $h_height = $nh/2;
        $w_height = $nw/2;

        if($w> $h) {
            $adjusted_width = $w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;
            imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
        } elseif(($w <$h) || ($w == $h)) {
            $adjusted_height = $h / $wm;
            $half_height = $adjusted_height / 2;
            $int_height = $half_height - $h_height;

            imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
        } else {
            imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
        }
            imagejpeg($dimg,$dest,100);
        }
}
 echo "Coversion Successfully completed";
/* Closing the directory */
@closedir($dir_handle);

}
?>

Implode and Explode function of Php

Written By Unknown on Kamis, 19 September 2013 | 23.20

Implode and Explode function of Php


<?php
// function 1:  implode()
echo "<h1>IMPLODE</h1>";
$arr=array("test1","test2","test3","test4","test5","test6","test7","test7");
echo "<pre>";  print_r($arr); echo "</pre>";

//implode(glue, pieces)

echo "Array with glue=none";
echo "</br>";echo "</br>";
$str=implode('', $arr);
echo $str;

echo "</br>";echo "</br>";
echo "Array with  ',' as glue to get comma separarted value from array ";
echo "</br>";echo "</br>";
$str=implode(',', $arr);
echo $str;
echo "</br>";echo "</br>";
// implode() function is used to join array elements and return string

// function 2:  explode(delimiter, string)
echo "<h1>EXPLODE</h1>";
echo $str="This is my string i am going to explode";
echo "</br>";echo "</br>";
echo "First using space as delimiter";
echo "<pre>";  print_r($arr); echo "</pre>";
$arr=explode(' ',$str);

echo "</br>";echo "</br>";
echo "Now using t as delimiter";
$arr=explode('t',$str);
echo "<pre>";  print_r($arr); echo "</pre>";
// explode breaks string into array where delimiter comes

?>

Array() / Array_fill() / Array_Keys() in php

Array() / Array_fill() / Array_Keys() in php

<?php
// function 1:  array()
$arr=array();
echo "Empty array created";
echo "<pre>";  print_r($arr); echo "</pre>";
// array() create an empty array

// function 2:  array_fill(start_index, num, value)
$arr=array_fill(0, 5, "test");
echo "Array filled with value";
echo "<pre>";  print_r($arr); echo "</pre>";
$arr[1]="failed";
$arr[3]="failed";
echo "Array after changes";
echo "<pre>";  print_r($arr); echo "</pre>";
// array_fill() fill the array with value given in parameter

// function 3:  arrays_keys(array,value)
echo "Keys where value is test in array";
$keyz=array_keys($arr,"test");
echo "<pre>";  print_r($keyz); echo "</pre>";
// arrays_keys() return the array of keys where value is same as parameter

?>

Append some (text/img) after some html element using jquery

Written By Unknown on Jumat, 13 September 2013 | 04.56

How to append some (text/img) after some html element using jquery 

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" >
        $(document).ready(function(){
var i=0;
            $("#sub").on("click",function(){
$( "#1" ).append("Test "+i+" ... ");
                 i++;
                 });      
            });
 
        </script>
        </head>
    <body>
<div id="1">This is my test...</div>
<button type="button"  id="sub">Append</button>
</form>
</body>

</html>

Get session information in cakephp

Written By Unknown on Kamis, 12 September 2013 | 23.30

How to get session information in cakephp 

In the controller you can use

$this->Session->read();

to get all details of session variable . And you can use

$this->set('session',$this->Session->read());


to use these values in corresponding view page.

-----------------------------------------------------------------------------------------------------------------------

If you wish to use session variable in each page then use set method in appcontroller to set its value

public function beforefilter(){
$this->set('session',$this->Session->read());
}

Now this session variable is accessible in every page of view.

Note: this should be placed in Appcontroller...

Using some other file as index file when no index file is in the directory using .htaccess

Alternative index file using .htaccess

When there is no index file in php directory and you want that some other file act as index file then this code can be helpful
search is done from left to right ... whichever file is found first will be shown as index file


DirectoryIndex index.php index1.php index2.php index3.php

# u can use any name you want in place of index1.php

Hide directory information in php when index file is not present using .htaccess.

When no index file is present in directory and you want to hide listing on other files in php then .htaccess can be used to hide directory information.
Just copy the below lines in .htaccess file and put .htaccess file in directory for which you want to hide files list.

Options -Indexes

Create backup of database using php script

Written By Unknown on Selasa, 10 September 2013 | 06.18


<?php
define('BACKUP_DIR', './Backups' ) ;
// Define  Database Credentials
define('HOST', 'localhost' ) ;
define('USER', 'amit' ) ;
define('PASSWORD', '' ) ;
define('DB_NAME', 'databse' ) ;
/*
Define the filename for the sql file
*/
$fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ;
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 )     set_time_limit(0) ;
}

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ;
// Create an ".htaccess" file , it will restrict direct accss to the backup-directory .
$content = 'deny from all' ;
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$file->fwrite($content) ;

$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information
$return = "--\n";
$return .= "--  Mysql Backup \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ;
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ;
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row())
{
$tables[] = $row[0] ;
}
// Cycle through each  table
 foreach($tables as $table)
 {
// Get content of each table
$result = $mysqli->query('SELECT * FROM '. $table) ;
// Get number of fields (columns) of each table
$num_fields = $mysqli->field_count  ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ;
// Get the table-shema
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema
$tableshema = $shema->fetch_row() ;
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ;
// Cycle through each table-row
while($rowdata = $result->fetch_row())
{
// Prepare code that will insert data into table
$return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
// Extract data of each row
for($i=0; $i<$num_fields; $i++)
{
$return .= '"'.$rowdata[$i] . "\"," ;
 }
 // Let's remove the last comma
 $return = substr("$return", 0, -1) ;
 $return .= ");" ."\n" ;
 }
 $return .= "\n\n" ;
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ;
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ;
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $fileName , "$return" ) ;
    }
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ;
$message = "BACKUP  completed ";
echo $message ;


function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
    default:
    return intval($file_size/(1024*1024)) ." MB" ;
}
}

?>

Join us ...

Written By Unknown on Senin, 09 September 2013 | 22.24

Find position of string in a given string

Written By Unknown on Kamis, 05 September 2013 | 04.11

Strpos Function


<html>
<body>
    <?php
        $str1="test";
        $str2="This is a testing string ";
        $pos=strpos($str2,$str1);
        echo "Given String : ".$str2."</br>";
        echo "String to be matched : ".$str1."</br>";
        echo "Match found at position : ".$pos;
        ?>
    </body>
</html>

How to send an array in url in php ?

Written By Unknown on Rabu, 21 Agustus 2013 | 23.04

File.php  (This file contain array )

<?php

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'script');

$arr=http_build_query($data);

?>
<a href="nextpage.php?<?php echo $arr; ?>">Sendarray</a>


--------------------------------------------------------------------------------------------------------------------------------

nextpage.php (This file will receive array and print it)


<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
?>

How to read a file character by character in php ?

<?php

$file=fopen("filename.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);

?>

Use linkedin api to fetch contact information in php ..

First Register your domain for linkedin api .

Then get your API_KEY, API_SECRET REDIRECT_URI , SCOPE ...

Run the script .. Njoy :)
------------------------------------------------------------------------------------------------------------------------
<?php

// Change these
define('API_KEY',      ' '          );  /*put API_KEY between '  ' */
define('API_SECRET',   ' '      ); /*put between API_SECRET '  '*/
define('REDIRECT_URI', ' '); /*put REDIRECT_URI between '  '*/
define('SCOPE',        ' '     ); /*put Scope between '  '*/


session_name('linkedin');
session_start();
$_SESSION['state']="India" // Name the country you live in
;
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application
    if ($_SESSION['state'] == "India") {
        // Get token so you can make API calls
        getAccessToken();
    } else {
        // CSRF attack? Or did you mix up your states?
        exit;
    }
} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
        $_SESSION = array();
    }
    if (empty($_SESSION['access_token'])) {
        // Start authorization process
        getAuthorizationCode();
    }
}

// Congratulations! You have a valid token. Now fetch your profile by defining field you wanted

$user = fetch('GET', '/v1/people/~:(id,firstName,lastName,skills,location,industry,network)');
echo "<pre>";
print_r($user);
echo "<pre>";
exit;

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
   
    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}
   
function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );
   
    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
   
    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);

    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time
   
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );
   
    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );


    // Hocus Pocus
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    return json_decode($response);
}

Recursion in php

Written By Unknown on Selasa, 20 Agustus 2013 | 23.28

<?php

function recursion($int){
    if($int>0){
        echo $int."</br>";
        recursion($int-1);
        echo $int."</br>"; /*values from stack*/
        }
    }
   
recursion(5);

?>

How to preview array in Php ?

Array

<?php

$arr=array(1,2,3,4,5);
echo "<pre>";
print_r($arr);
echo "</pre>";

?>

How to write your first php script ?

What you need ?

1. A server
2. A php file to be put in your www. or htdocs directory..

Phpfile

<?php

echo "My first PHP script!";
 

?>
 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger