GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, April 17, 2011

Apache - Removing index.php

For removing index.php on url, type this code to an .htaccess file:
RewriteEngine On
RewriteRule ^[a-z]/* index.php


The process the script in the file of index.php

<?php

    // you can process the url use this one
    $q = $_SERVER['REQUEST_URI'];

    $queries = explode('/',$q);
   
    $page = $queries[1];

    if($page == 'css'){
        include "css/index.php";
    }else if($page == 'js'){
        include "js/index.php";
    }else if($page == 'hello'){
        include ("hello.php");
    }else{
        include "404.php";
    }
?>
Share/Bookmark

Saturday, April 16, 2011

Apache - Building Pretty URL

<?php
    $q = $_SERVER['REQUEST_URI'];
    $queries = explode('/',$q);  // the url: /index.php/hello/somevalue/somevalue
    var_dump($queries);
    $page = $queries[2];
    $value1 = $queries[3];
    $value2 = $queries[4];
    if($page == 'holla'){
        include "holla.php";
    }else if($page == 'hello'){
        include "hello.php";
    }else if($page == '' && $queries[1] = 'index.php'){
        include "front.php";
    }else{
        include "404.php";
    }
?>

And the htaccess file is like this one:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule .* index.php [L]
Share/Bookmark

Zend - SOAP Web Service

Below is a three file:
1. mywebservie.php - defining class that used in this web service
2. webservice.php - WSDL document and Soap server creation
3. hello.php - a client that request a service from the soap server
You can find nice guide here: http://www.phpriot.com/articles/zend-soap/6


Share/Bookmark

PHP - The First Web Services

This is my first web service I try to do that successfully executed:
index.php
<?php
require_once "nusoap.php";

$server = new soap_server;
$server->register('hello');

function hello($name){
    return 'Hello, '.$name.' From Soap Server';
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

While the client code is:
<?php
require_once 'nusoap.php';

$client = new SoapClient(
    null,
    array(
        'location' => 'http://localhost/index.php',
        'uri' => 'http://localhost:80',
        'soap_version' => '0.9.5',
    )
);

$result = $client->hello('Barack Obama');
print_r($result);
?>
Share/Bookmark

Tuesday, April 5, 2011

PHP - Caching The Page

<?php

    date_default_timezone_set('Asia/Jakarta');
   
    // get the url as file name
    $file = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   
    $cachefile = 'cache/'.$file.'.html';
   
    // get this page file name
    $file_page = __FILE__;

    if (file_exists($cachefile) && (filemtime($file_page)) < filemtime($cachefile)) {

        // this must be included because the file cache comes from here.
        include($cachefile);

        echo "<!– Cached ".date('H:i', filemtime($cachefile))." –>n";

        exit;

    }

    ob_start(); // start the output buffer

?>

<h1>...Everything Here Is Cached...</h1>


<?php

    $fp = fopen($cachefile, 'w'); // open the cache file for writing

    fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file

    fclose($fp); // close the file

    ob_end_flush(); // Send the output to the browser

?>

Share/Bookmark

Tuesday, March 29, 2011

PHP - PDO MySQL

<?php

$hostname = 'localhost';
$username = 'root';
$password = 'indonesia';

try{
    $db = new PDO("mysql:host=$hostname;dbname=a", $username, $password);
    echo 'Connected to database';
    $db = null;
}catch(PDOException $e){
    echo $e->getMessage();
}

Share/Bookmark

Friday, March 18, 2011

PHP - SQLite3

<?php

// automatically created if doesn't exist
$db = new SQLite3("data.db");

$db->execute("CREATE TABLE data ( name STRING)");
$db->execute("INSERT INTO data (name) VALUES ('Lady Gaga')");

$result = $db->query("SELECT name FROM data");
print_r($result->fetchArray());         // equiv mysql_fetch_array
Share/Bookmark

PHP - Get the result of MySQL

mysql_fetch_row
    Array ( [0] => 2 [1] => corolla [2] => toyota ) 
mysql_fetch_assoc
    Array ( [id] => 3 [brand] => accord [owner] => honda ) 
mysql_fetch_array
    Array ( [0] => 1 [id] => 1 [1] => saab [brand] => saab [2] => gm [owner] => gm ) 
mysql_fetch_object
    stdClass Object ( [id] => 4 [brand] => kijang [owner] => toyota )  

Share/Bookmark

Thursday, March 17, 2011

JSON - Response As An Array

When you hope your json response as an array, not as an object, so do it like this one:
Server:
    $data = array();
    $data[] = 'lady gaga';
    $data[] = 'luna maya';
    $data[] = 'barack obama';

    echo json_encode($data);

Client:
    $data = eval('('+ajax.responseText+')');
    for(i=0; i<data.length; i++){
        element.innerHTML = innerHTML + data[i];
    }
Share/Bookmark

Sunday, March 13, 2011

PHP - DOMDocument For XML

To get a value of a specified tag, use
$dom->getElementsByTagName('name')->item(0)->nodeValue;

To initialize, type:
$dom = new DOMDocument();
$dom->loadXML($data); // or using $dom->load('file.xml');

To create element, use:
$city = $dom->createElement('city', 'One Bay 21th, London');
$dom->getElementsByTagName('data')->item(0)->appendChild($city);

Look the real code below:
<?php

$data = '<?xml version="1.0" ?>';
$data .= '<data>';
$data .= '<name>Lady Gaga</name>';
$data .= '<city>New York</city>';
$data .= '<age>24</age>';
$data .= '</data>';

$dom = new DOMDocument();
$dom->loadXML($data);

echo $dom->getElementsByTagName('name')->item(0)->nodeValue;
echo $dom->getElementsByTagName('city')->item(0)->nodeValue;
echo $dom->getElementsByTagName('age')->item(0)->nodeValue;

// create a new node: address node
$address = $dom->createElement('address','Gaga Streets 21th');
$data = $dom->getElementsByTagName('data')->item(0);
$data->appendChild($address);

// remove a child node: remove name node
$doc = $dom->documentElement;
$child = $doc->getElementsByTagName('name')->item(0);
$doc->removeChild($child);


// replace child nodes: replace city node with interest
$interest = $dom->createElement('interest','music');
$city = $dom->getElementsByTagName('city')->item(0);
$dom->getElementsByTagName('data')->item(0)->replaceChild($interest, $city);

// create text node: create description node
$desc = $dom->createElement('desc');
$text = $dom->createTextNode('Lady Gaga Is An Singer Of Pop');
$data = $dom->getElementsByTagName('data')->item(0);
$desc->appendChild($text);
$data->appendChild($desc);

// create attribute: album = Monster Ball Album
$album = $dom->createAttribute('album');
$desc->appendChild($album);
$value = $dom->createTextNode('Monster Ball Album');
$album->appendChild($value);

// get the attribute: album
$desc = $dom->getElementsByTagName('desc')->item(0);
$value = $desc->getAttribute('album');
echo '<p>'.$value.'</p>';

// remove the attribute: album
$desc = $dom->getElementsByTagName('desc')->item(0);
$desc->removeAttribute('album');

// set the attribute: replace or add new one
$desc = $dom->getElementsByTagName('desc')->item(0);
$desc->setAttribute('album','Monster Allbum');

// set the id attribute:
$age = $dom->getElementsByTagName('age')->item(0);
$age->setAttribute('id','lady');
$ages = $dom->getElementsByTagName('age')->item(0)->tagName;
echo $ages;

$xml = $dom->saveXML();
echo '<pre>'. htmlentities($xml).'</pre>';


Share/Bookmark

Friday, March 11, 2011

PHP - Drawing Rectangle

<?php
  $s = new SWFShape();
  $s->setLine(14, 0x7f, 0xf0, 0);
  $s->setRightFill($s->addFill(0xff, 0, 0xaf));
  $s->movePenTo(100, 100);
  $s->drawLineTo(300, 100);
  $s->drawLineTo(300, 300);
  $s->drawLineTo(100, 300);
  $s->drawLineTo(100, 100);
  

  $m = new SWFMovie();
  $m->setDimension(400, 400);
  $m->setRate(1.0);
  $m->add($s);
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Share/Bookmark

PHP - Intro To Ming Flash

Here's a flash generator. Name it index.php
<?php
  $s = new SWFShape();
  $s->setLine(4, 0x7f, 0, 0);
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(10, 10);
  $s->drawLineTo(310, 10);
  $s->drawLineTo(310, 230);
  $s->drawCurveTo(10, 230, 10, 10);

  $m = new SWFMovie();
  $m->setDimension(320, 240);
  $m->setRate(12.0);
  $m->add($s);
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Then this is a file that show the flash. Name it hello.php
<h1>This is a flash moview</h1>
<object width="100" height="50">
     <param name="movie" value="somefilename.swf">
     <embed src="index.php" width="100" height="50">
     </embed>
</object>


Share/Bookmark

PHP - Resizing Image

<?php
// File and new size
$filename = 'lamp.png';
$percent = 5.5;

// Content type
header('Content-type: image/png');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($filename);

// Resize
imagecopyresized($thumb, $source, 100, 100, 10, 10, $newwidth, $newheight, $width, $height);

// Output
imagepng($thumb);
imagedestroy($thumb);
?>

Share/Bookmark

PHP - Loading PNG Image

<?php
header('Content-type: image/png');

$img = imagecreatefrompng('lamp.png');
imagecolorallocate($img, 200, 200, 200);

imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)


imagepng($img);
imagedestroy($img);


Share/Bookmark

PHP - Start GD Library

The code below is just draw a black png image to browser:
<?php
header('Content-type: image/png');

// initialization 250x300 pixels
$img = imagecreate(250,300);

// backgrouning
$black = imagecolorallocate($img, 0,0,0);

imagepng($img);
imagedestroy($img);
?>


To add a string, just do

<?php
header('Content-type: image/png');

// initialization 250x300 pixels
$img = imagecreate(250,300);

// backgrouning
$black = imagecolorallocate($img, 0,0,0);

$text_color = imagecolorallocate($img, 0, 15, 250);
// nan, nan, left, top, text, color
imagestring($img, 2, 5, 5, "A simple text string", $text_color);

imagepng($img);
imagedestroy($img);
?>

Other Sample:

<?php
header('Content-type: image/png');
$img = imagecreate(900,700);

$lime = imagecolorallocate($img, 200, 250, 0);

//drawing string
$text_color = imagecolorallocate($img, 10, 10, 10);
imagestring($img, 12, 65, 150, "Lucia", $text_color);

//drawing rectangle box
$rect_color = imagecolorallocate($img, 10, 250, 10);
imagerectangle($img, 0, 0, 50, 100, $rect_color);

//drawing solid rectangle box
$rect_color = imagecolorallocate($img, 100, 20, 150);
imagefilledrectangle($img, 60, 0, 120, 120, $rect_color);

// drawing ellipse (handle, centerX, centerY, width, height, color)
$ect_color = imagecolorallocate($img, 200, 0, 0);
imagefilledellipse($img, 200, 50, 100, 50, $ect_color);


imagepng($img);
imagedestroy($img);


?> 


Share/Bookmark

Thursday, March 10, 2011

PHP - XML In Sending Data

Here's a code on how to sending data from client to server in the form of xml format. You can see also at this link.
1. file index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
    Name: <input type="text" id="name"/><br/>
    City: <input type="text" id="city"/><br/>
    Age: <input type="text" id="age"/><br/>
    <input type="button" onclick="sendData()" value="Save"/>
</div>
<div id="response"></div>

Share/Bookmark

JSON Vs XML

Here's a comparison for JSON and XML
1. When you do a request data from server, on the client side you do:
  a. JSON: 
        var data = eval('(' +ajax.responseText+ ')'); or
        var data = null; eval('data ='+ajax.responseText); or
        var data = new Function('return '+ajax.responseText);
  b. XML:
        var data = ajax.reponseXML;

2. On the server side, the process for the request handling is:
  a. JSON:
        $data_json = json_encode($data_array);
  b. XML:
        $data = '<?xml version="1.0"?>';
        header('Content-type: text/xml');
        echo $data;

3. When you do sending data to server, the process in the client is like this one:
  a. JSON:
         var data = {};
         var data_sending = JSON.stringify($data);
  b. XML:
         var xml_data = '<?xml version=\"1.0\"?>';
         var parser = new DOMParser();
         var xmlDoc = parser.parseFromString(xml_data, 'text/xml');

4. And the process on the server is like:
  a. JSON:
         $data = $_GET['data'];
         $data_array = json_decode($data, true);
  b. XML:
         $data = $_GET['data'];
         $xmlDoc = new DOMDocument();
         $xmlDoc->loadXML(data); // or load(file);
         $names = $xmlDoc->getElementsByTagName('name');
         $name = $names->item(0)->nodeValue;

5. Other similarities:
  a. Converting native object to string representations:
     - JSON => JSON.stringify(data);
     - XML => ?????????
  b. Converting string text to native object:
     - JSON => var data = text.parseJSON();
     - XML => var doc = new DOMParser();
              var xmlDoc = doc.parserFromString(data, 'text/xml');


Share/Bookmark

PHP - Handling XML

To handle xml document using php, here's a bit of code of it:
For example, you have an xml document:
<?php

$xml = '<?xml version="1.0"?>';
$xml .= '<data>';
$xml .= '<name>Luna Maya</name>';
$xml .= '<city>Denpasar</city>';
$xml .= '<age>27</age>';
$xml .= '</data>';

$xmlDoc = new DOMDocument();
// if the xml document lies on the file, use $xmlDoc->load('your_file.xml');
$xmlDoc->loadXML($xml);

$name = $xmlDoc->getElementsByTagName('name');
echo $name->item(0)->nodeValue;

Share/Bookmark

AJAX AND JSON - Sending Data

Here's a demo on how to send data from client to server:
In the client side, the steps are:
1. You get the data using Javascript DOM
2. Then you convert it to Javascript object literal
3. Then you change the object literal to string - JSON.stringify(data)
4. Then you send it through ajax

In the server side:
1. Catch the json data as a like $data = $_POST['data'];
2. Convert the data as an array $data = json_decode($data,true);

The Files:
a. index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
    Name: <input type="text" id="name"/><br/>
    City: <input type="text" id="city"/><br/>
    Age: <input type="text" id="age"/><br/>
    <input type="button" onclick="sendData()" value="Save"/>

</div>

<script>
function sendData(){
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
   
    var data = {};
    data.name = name.value;
    data.city = city.value;
    data.age = age.value;
   
    var datas = JSON.stringify(data);
   
    var ajax = new XMLHttpRequest();
    ajax.open("GET","hello.php?data="+datas,false);
    ajax.send();
   
    name.value = '';
    city.value = '';
    age.value = '';
   
      
}

</script>

b. hello.php
<?php

$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data",$handle);

$data = $_GET['data'];


// convert the json format to php array style
$data = json_decode($data, true);

$query = "INSERT INTO personal_info (name, city, age) VALUES ";
$query .= "('".$data['name']."', '".$data['city']."', 
          ".$data['age'].")";

$result = mysql_query($query);
Share/Bookmark

AJAX And XML

XML can be used as a data format when you handling data transfer between server and client. Here's a code that shows to you on how to use the both:

1. Create File index.php
<h1>Ajax And XML Demos</h1>
<div>Enter a name:
    <input type="text" id="name_id"/>
    <input type="button" onclick="getData()" value="Get Data"/>
</div>

Name: <span id="name"></span><br/>
City: <span id="city"></span><br/>
Age: <span id="age"></span><br/>


<script>
function getData(){
    var name_d = document.getElementById('name_id');
    var name = document.getElementById('name');
    var city = document.getElementById('city');
    var age = document.getElementById('age');
   
    var ajax = new XMLHttpRequest();
    ajax.open("GET","hello.php?name="+name_id.value,false);
    ajax.send();
    var data = ajax.responseXML;
   
    name.innerHTML = data.getElementsByTagName('name')[0].childNodes[0].nodeValue;
    city.innerHTML = data.getElementsByTagName('city')[0].childNodes[0].nodeValue;
    age.innerHTML = data.getElementsByTagName('age')[0].childNodes[0].nodeValue;
   
}
</script>


2. Create file: hello.php
<?php
/**
 * Assume the table structure is like this one
 * CREATE TABLE personal_info
 * (id INT NOT NULL AUTO_INCREMENT KEY,
 * name CHAR(20) NOT NULL DEFAULT '',
 * city CHAR(20) NOT NULL DEFAULT '',
 * age INT NOT NULL DEFAULT 0
 * );
 */

$handle = mysql_connect("localhost","root","indonesia");
mysql_select_db("data", $handle);
$name = $_GET['name'];
$name = urldecode($name);

$query = "SELECT * FROM personal_info WHERE name= '$name'";

$result = mysql_query($query);

$output = '<?xml version="1.0" ?>';
$output .= '<data>';
$output .= '<name>'.$name.'</name>';


while($row=mysql_fetch_array($result)){
    $output .= '<age>'.$row['age'].'</age>';
    $output .= '<city>'.$row['city'].'</city>';
}

$output .= '</data>';

header("Content-type: application/xml");
echo $output;

?>
Share/Bookmark