Showing posts with label [IT] PHP. Show all posts
Showing posts with label [IT] PHP. Show all posts

Friday, November 7, 2014

Basic http server authentication from mobile app via ajax

1. script for ajax 
function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax({
type: 'POST',
beforeSend: function (xhr){  xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));   },
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
url: 'http://www.gtatrade.ca/mobiletest',
data: ({name: "aaa"}),
success: function(data){alert(data.name);},
error: function(e, x, settings, exception){alert("error!!" + "," + e.staus + ","  + e.responseText + ","  + x + ","  + settings + ","  + exception);},
dataType: 'json'
});

*** If you send header every time, use ajaxSetup like below.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));
    }
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
});

2. Server php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header("Access-Control-Allow-Origin: *"); // required for cross domain .. 
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
header("Access-Control-Allow-Origin: *");  // required for cross domain ..
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    $output = array("name"=>$_SERVER['PHP_AUTH_USER'], "pass"=>$_SERVER['PHP_AUTH_PW']);
    echo json_encode($output);
}

Saturday, June 14, 2014

[CodeIgniter] Remove the index.php in the URL and using sub folders for controller.

1. Edit .htacess file in www root folder.
This is what I have...

<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On
  RewriteBase /
  # If your default controller is something other than 'welcome' you should probably change this.
  RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301]
  RewriteRule ^(.*)/index/?$ $1 [L,R=301]
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ /index.php/$1 [L]
  SetEnvIfNoCase X-Forwarded-For .+ proxy=yes
  SetEnvIfNoCase X-moz prefetch no_access=yes
  
  # Block pre-fetch requests with X-moz headers.
  RewriteCond %{ENV:no_access} yes
  RewriteRule .* - [F,L]
  # Fix for infinite redirect loops.
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [L]
</IfModule>

2. Make mod_rewrite enabled in apache configuration file(httpd.conf)
Just uncoment this line.
LoadModule rewrite_module modules/mod_rewrite.so

Make sure AllowOverride is set to All.
AllowOverride All

3. Extend the core Router class of CodeIgniter(for using controller sub folder)
You can obtain the MY_Router.php file at this link and save it to application/core/ folder.
https://degreesofzero.com/article/controllers-in-sub-sub-folders-in-codeigniter.html

4. Restart WAMP server.

5. Tips - If you want to add port based virtual hosts ....

Listen 8080
NameVirtualHost *:8080

<Directory />
#    Require all denied
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

<VirtualHost *:8080>
    ServerName localhost
    DocumentRoot "D:/admin"
</VirtualHost>



Monday, April 21, 2014

Google Cloud Messaging(GCM) for Android. (Part 2/2)

6. Implement GCM receiver code.(Client)
<< Broadcast Receiver class>>

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{
public static final String Key_Type = "Type";
public static final String Key_Command = "CMD";
public static final String Key_Msg = "MSG";

@Override
public void onReceive(Context context, Intent intent) {
    Log.i("GCMBroadcastReceiver.onReceive","new message is received.");


    Bundle extras = intent.getExtras();
    String action = intent.getAction();
    if(extras != null){
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String messageType = gcm.getMessageType(intent);
        // read data from gcm

        String type = intent.getStringExtra(Key_Type);
        String command = intent.getStringExtra(Key_Command);
        String msg = intent.getStringExtra(Key_Msg);

        // TODO you can add some specific code to do....
        // You can start new service to do some works.
        // startWakefulService(context, (intent.setComponent(comp)));
        // see the artical in google developer's guide http://developer.android.com/google/gcm/client.html#sample-receive

    }
}
}


7. Setup in AndroidManifast.xml file.(Client)
The instuction under ... http://developer.android.com/google/gcm/client.html#manifest

<manifest package="com.example.gcm" ...>
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- I didn't add this permission -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.example.gcm.permission.C2D_MESSAGE"

android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />


<application ...>
            <receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <category android:name="com.example.gcm" />
                </intent-filter>
            </receiver>
            <service android:name=".GcmIntentService" /> <!-- if you created service to handle gcm messages you should add this service-->
</application>


8. Implement GCM message sender.(Server)
  • This is the PHP function to send gcm message to GCM connecton server.
  • You can also send gcm message to GCM connection server from you android app.
  • As you may not need it if you have a server to send the message, I will not add the codes. :-)
  • I used Curl... and you can use the lib with comment off this extesion in php.ini, if you installed latest WAMP server.
  • extension=php_curl.dll

function sendGCMMessage_($data, $registrationIDs)
{   $apiKey = 'GsfgaSFc13-2reIDSD4qK_3_dfghspVWDSxEAA'; // this is the brower key you generated in 3. Creating a Google API project and obtaining an API Key.

    $senderId = "153023456724"; // this is the project code you generated in 3. Creating a Google API project and obtaining an API Key.

    $url = 'https://android.googleapis.com/gcm/send';

 

   $fields = array(

   'delay_while_idle' => False, // If you want to receive message when the phone is idle, you have to set this 'False'. You can set this 'True' to save the battery.
   'time_to_live' => 108,
   'collapse_key' => 'score_update',
   'registration_ids' => $registrationIDs,
   'data' => $data,

   );

   $headers = array(

   'Authorization: key=' . $apiKey,
   'Sender: id=' . $senderId,
   'Content-Type: application/json'

   );

   // Open connection
   $ch = curl_init();
   // Set the URL, number of POST vars, POST data

   curl_setopt( $ch, CURLOPT_URL, $url);

   curl_setopt( $ch, CURLOPT_POST, true);

   curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);

   curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);

   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

   $result = curl_exec($ch);

   return $result;

}
  • how to call the function?? It is quite easy. 

$registrationIDs = array("APA91bEr6sdfjJzIsdfO76YsdfsvQ5NGago9JvRYod0v-n...", "APA91bEr6zWLWizsdfMO76YVRdfsfQ5NGagdfYod0vdsf...");
// The registeration id you obtained in 5. Implement GCM register code.(Client). You can add multiful registeration ids.

$data = array("Type" => "My Type", "CMD" => 'My Command', "MSG" => "My Message" );
// You should add the same key value pairs just the same as you will receive in you client app you implemented in 6. Implement GCM receiver code.(Client).
$result = sendGCMMessage_($data, $registrationIDs);
 

Sunday, April 20, 2014

Code igniter multiple file upload.

1. Prepare upload form view.

<< uploadview.php >>

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h2> file upload example </h2>
Only image files(gif|jpg|png) can be accepted. <br /> <br />
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" /><br /><br />
<input type="file" name="userfile2" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>

2. Prepare uploadsuccess page view.

<< uploadsuccess.php >>

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<table ><tr valign=top><td>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<img src="/uploads/<?php echo $upload_data["file_name"]?>">
</td><td>
<ul>
<?php foreach ($upload_data2 as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<img src="/uploads/<?php echo $upload_data2["file_name"]?>">
</td></tr></table>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>

3. Prepare upload controller.

<< upload.php >>

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

   function index()
   {
     $data['error'] = '';
     $this->load->view('uploadview', $data);
   }
   function do_upload()
   {
     $this->load->helper(array('form', 'url'));
     $config['upload_path'] = 'C:\wamp\www\uploads';
     $config['allowed_types'] = 'gif|jpg|png';
     $config['max_size'] = '100';
     $config['max_width']  = '1024';
     $config['max_height']  = '768';
     $this->load->library('upload', $config);

     $result = $this->upload->do_upload("userfile");
     if (!$result){
         $error = array('error' => $this->upload->display_errors());
         echo $this->upload->display_errors();
         $this->load->view('uploadview', $error);
         return;
     }
     $data = array('upload_data' => $this->upload->data());
     $result2 = $this->upload->do_upload("userfile2");
     if (!$result2){
         $error = array('error' => $this->upload->display_errors());
         echo $this->upload->display_errors();
         $this->load->view('uploadview', $error);
         return;
     }
     $data['upload_data2'] = $this->upload->data();
     $this->load->view('uploadsuccess', $data);
     }
}

4. You can find more information from this user-guide page.

http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

Thursday, March 27, 2014

Use code igniter [Code ignigter install and create helloworld app.]

1. Install code igniter.

  • go to code igniter site and click download button.
http://ellislab.com/codeigniter
  • Installation Instruction.(Please refer to Code Igniter user guide.)
  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
2. create hello world php.
  • create helloworld.php file in application/controllers folder with these codes.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Helloworld extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

   function index()
   {
     echo 'Hello world!';
   }
   function test()
   {
      echo 'Second hello world!';
   }
}
3. create hello world php with view.
  • update helloworld.php file with these codes.
   function index()
   {
    // echo 'Hello world!';
       $this->load->view('helloview');
   }
  • create helloview.php file in application/view folder with these codes.
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hello World App</title>
</head>
<body>
    <h1>Hello World!</h1>
    <div >
        <p>My First CodeIgniter Application.
    </div>
</body>
</html>
4. passing parameters to view.

  • update helloworld.php file with these codes.
   function index()
   {
     // echo 'Hello world!';
  $data['message'] = 'Hello World!!!';
  $this->load->view('helloview', $data);
   }
  • update helloview.php file with these codes.
  <body>
    <h1><?php echo $message; ?></h1>



Wednesday, March 26, 2014

How to install WAMP Server and getting started web development.

1. What is WAMP?
WAMP stands for Windows-Apache-MySQL-PHP.
When it goes for Linux it is LAMP and MAMP for Mac.

2. Install WAMP server.















3. Start up WAMP server.
  • choose "start WampServer" from the "Start" menu; or run "wampmanager.exe".
  • You can see WAMP Server icon from tray as below.


4. Start service.
  • Left mouse buton click on WAMP Server icon.
  • Select 'Start All Services'.
  • Make sure if the WAMP Server icon is green.
  • If 80 port is used by another process, the Apache server cannot be started.

  • If the server is running properly, you can access to web pages.
          http://localhost/
          http://localhost/phpmyadmin/

5. Folder structures.
  • bin : binaries for Apache, MySQL, and PHP. Multiful version can be installed.
  • apps : server-side tools such as PhpMyAdmin, SQL Buddy and WebGrind.
  • tools : client-side tools such as xdc(XDebug Client).
  • www : web root
  • logs : log files.
  • alias : appache's alias configuration.
6. Helloworld app.
Create helloworld.php in www folder(web root).
Add this codes.

<?php echo 'Hello world!';?>

You can see the result at....
http://localhost/helloworld.php