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

Tuesday, June 26, 2012

php: get input and write text file, then return

Put the following codes in the server side to receive the inputs from Apps.

<?php
     
    // assign the input to the variables
    $method = $_POST['method'];
    $name = $_POST['name']; // variable to be received by server
    $id = $_POST['userID']; // variable to be received by server
    echo " user name: ".$name ." id: ". $id. " method: ". $method; // echo the received data to the Apps
    
    
    // write text file with above two variables
    $file = "file.txt";
    $fh = fopen( $file, 'w' );
    $carriageReturn = "\n";
    fwrite( $fh, $method );
    fwrite( $fh, $carriageReturn );
    fwrite( $fh, $name );
    fwrite( $fh, $carriageReturn );
    fwrite( $fh, $id );
    fclose( $fh );
   
    
    
?>

php: return data in json

In server side, the following code can return the data in JSON format to client(Apps).

<?php

     
    $name = "Ben";
    $id = "id1234";
    $method = "get data";
    
    // build result in json format
    $arr = array("result" => "success",
                 "uid" => $id,
                 "data"=>array("name"=>$name, 
                               "id"=>$id, 
                               "method"=>$method 
                               
                               )
                 );
    
    echo json_encode($arr);
    
    
?>

php: generates Token with random string

The following code generate the random string with certain length to the client. It can be used to create the token and send to client's apps.

<?php
    
    // generate random string
    function random_gen($length)
    {
        $random= "";
        srand((double)microtime()*1000000);
        $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $char_list .= "abcdefghijklmnopqrstuvwxyz";
        $char_list .= "1234567890";
        // Add the special characters to $char_list if needed
        
        for($i = 0; $i < $length; $i++)  
        {    
            $random .= substr($char_list,(rand()%(strlen($char_list))), 1);  
        }  
        return $random;
    } 
    
    $random_string = random_gen(30); //This will return a random 30 character string
    echo "New Token: ".$random_string;
    
   
?>