Showing posts with label php tutorial. Show all posts
Showing posts with label php tutorial. Show all posts

Saturday, November 3, 2012

Black Diamond with Question Mark �

If you see that character (� U+FFFD "REPLACEMENT CHARACTER") it usually means that the text itself is encoded in some form of single byte encoding but interpreted in one of the unicode encodings (UTF8 or UTF16).

To fix this you have to tell your browser that you need to display characters from the iso-8859-1 set so it will know how to render them correctly, put the following in HEAD tag of HTML page.
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
for programming languages such as PHP set the content type header to
<?php header("Content-type: text/html; charset=iso-8859-1"); ?>
Continue Reading...

Tuesday, August 14, 2012

Yii Framework Tutorial For Beginners

Yii is an open source, object-oriented, component-based PHP web application framework. Yii is pronounced as "Yee" or [ji:] and it's an acronym for "Yes It Is!".

Yii is a free, open-source Web application development framework written in PHP5 that promotes clean, DRY design and encourages rapid development. It works to streamline your application development and helps to ensure an extremely efficient, extensible, and maintainable end product.

Yii Framework and its key concept: MVC


Setting up a development environment


Creating a skeleton application using yiic


Gii to create Models, Views, Controllers and CRUDs


Talking with Database


Yii Architectural Review


These tutorials are taken from here

Continue Reading...

Friday, May 25, 2012

PHP Convert String SEO Friendly

PHP Convert String SEO Friendly
This tutorial explains how to create SEO friendly URL using PHP. Friendly URLs improves your site's search engines ranking. To make a SEO friendly URL a string must be sanitized for certain things like...
  • URL should be in lower case
  • All spaces should be replaced with a dash or hyphen (-)
  • URL must only contains letters and numbers.
  • NO HTML is allowed.

I found a very quick and clean way to do this.
function Make_SEO_Friendly_URL($string)
{
  // replace all non letters or digits with -
  $string = preg_replace('/\W+/', '-', $string);

  // trim and lowercase
  $string = strtolower(trim($string, '-'));
  return $string;
}

Example

$string="making String SEO Friendly with PHP is easy, isnt?";

echo Make_SEO_Friendly_URL($string);

//OUTPUT
making-string-seo-friendly-with-php-is-easy-isnt
Continue Reading...

Friday, November 25, 2011

CharAt in PHP

If you want to get a character from a string at a given index using PHP, first thing which come in mind to most javascript or java developers is charAt() function or method, but in PHP there is not such method. Which is a surprise to me, i googled for a while and find out no such methods exist, however we can very easily create one.

so here it is.
    public function charAt($string,$index){
        return $string{$index};
    }
That is all folks!
Continue Reading...

Thursday, November 17, 2011

Codeigniter Hello World Tutorial

CodeIgniter is an open source PHP based Web Application Framework. CodeIgniter is based on the most popular web framework Model View Controller (MVC). This video tutorial is for absolute beginners. It will show you how you can make a simple Hello World Application using CodeIgniter.


 

if you know any other tutorials regarding CodeIgniter, Please Share it in comments.
Continue Reading...

Wednesday, August 10, 2011

WAMP Server Localhost URL Rewriting

wamp server icon
In this tutorial short tutorial we will configure WAMP server so that it can support URL Rewriting or User Friendly URLs. To do this go to your System Tray and left click on WAMP server's icon then go to Apache -&gt; Apache Modules -&gt; Click rewrite_module and then the WAMP server will restart it self so that it can reload the Apache server with new configurations and that is it, you have successfully configured the WAMP server for url rewriting without opening any configuration files.

Image below is for your reference.



Continue Reading...

Wednesday, July 20, 2011

Posting to Blogger Automatically

blogger api tutorial

In this post we will learn how to programmatically post to blogger, we use PHP for this but it can be done in any language which can send email. When we talk about programmatically, usually some complex programming scheme comes into mind but in this case there is no such thing, although one can use Blogger's PHP API or Blogger API for JAVA, but here we use simple mail to do this. First you need to configure your blogger account, open your blogger account and go to Setting -> Mobile and email as shown in figure below...

Posting to Blogger Automatically

in the Email section create an email which is your secret email address (do not share it with any one, mine show is figure is fake ;) ), this is used for creating blog post and set the option to your choice either you want it to publish immediately or save it as draft and then you approve it in future, in example i set publish immediately, after that click save settings and you blogger account is configured.

now create a simple PHP script that will send the mail and your post is automatically publish on blogger. A simple PHP code will be like this...
<?php

function sendPostToBlogger($postTitle,$postBody){

// our secret mail address we just created
$mailAddress="tutorialjinni.auto@blogger.com";

// using PHP mail function
mail($mailAddress,$postTitle,$postBody);

}
?>

and that is it... you can configure this is some sort of cron job or set it as a trigger in you code or as you wish :)

*Note You can pass HTML in $postBody too...
Continue Reading...

Sunday, May 8, 2011

SQL Injection & Prevention

sql injection
In this tutorial we will take a look atSQL Injection, how to attack using sql injection and how we can prevent ourselves form it. Firstly we see what is it after all, SQL Injection is subset of the an unverified/unsanitized user input vulnerability ("buffer overflows" are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it's straightforward to create some real surprises. In this tutorial we will discuss only one and most common type to attack that is done usually on the login.

Typically the code we used for loging a user is some what similar to the following.
// ...
    $username=$_REQUEST["username"];
    $password=$_REQUEST["password"];

    $query="select * from user where username='$username' AND password='$password'";

    $result=mysql_query($query);
    $count=$mysql_num_rows($result);

    if($count==1){
        // after login process goes here
    }
    if($coun!=1){
        // Declined user process goes here
    }
    // ...

this work perfectly fine until an invader comes and tried to run credentials like
User Name : admin
Password  : FAKE_PASSWORD' OR 'x'='x
if the above credentials are passed the query rendered will be
select * from user where 
username='admin' 
AND password='FAKE_PASSWORD' 
OR 'x'='x' 
which is a legal SQL query it also satisfy our login criteria and hence an ilegimate user will be granted access.

Prevention

if we want to defend ourselves from this type of attack we have many solution available like
$query = sprintf("SELECT * FROM `user` WHERE username='%s' AND password='%s'",
                  mysql_real_escape_string($username),
                  mysql_real_escape_string($password));
mysql_query($query);
or you can use Object Relation Mapping for may be Prepared statement... but i use the following code to prevent myself from it.
// ...
    $username=$_REQUEST["username"];
    $password=md5(md5($_REQUEST["password"]));
    // Double MD5 are hard to find

    $query="select * from user where username='$username'";

    $result=mysql_query($query);
    $obj=mysql_fetch_object($result);

    $dbPass=$obj->Password;
    // password stored with Double MD5

    if($dbPass==$password){
        // after login process goes here
    }
    else{
        // Declined user process goes here
    }
    // ...
in my case i don't send password to the database just fetch the password and compare it.

i find it easy to implement... do you?
Continue Reading...

Tuesday, April 19, 2011

Symfony Load Helper in Action

Symfony provides a rich set of methods in View part of Symfony MVC, which by defualt are not available in Action part, to make this available you have to load the specific helper that have your desire method, for example if you want to use image_path() method of Symfony you will need to load 'Assest' Helper, or if you want to use url_for() method you will load 'Url' helper, a complete list of helpers and there respective methods is available here

Now, Let the code talk

if i want to use image_path() method i will do it like this,
// ...
// may some code here...
// ...

sfContext::getInstance()
      ->getConfiguration()
        ->loadHelpers("Asset");

// this will load Symfony Asset Helper.. and make available all its helper.

$imagePath=image_path("../uploads/profile_images/IMAGE_NAME");

// ...
// more code...
// ...
Continue Reading...

Friday, April 15, 2011

Detect Country from IP

ip to country
In this tutorial we will find country by IP address, usually a website required this functionality to give a personalized experience to its visitor that includes localization of content i.e. if a user comes from Pakistan the content should be in Urdu as this is national language of the country, or if it come form china content should be in Chinese so on and so forth, other reason may include, to give visitor ads according to there locality, a reason may to block visitors from certain country where a specific offer is not available and many more reasons...

Out main concern is how to do it? there are many ways of doing it
  • you can use $_SERVER["HTTP_ACCEPT_LANGUAGE"] it returns a comma separated values in the format "en-us,en;q=0.5" first value en-us tell its from US, it may en-uk: UK, en-jp: Janpan..
  • or you can use ip database lookup for it (we will discuss it)
  • you can buy a paid service (which i am not intrested)
  • or you can explicitly ask a user from where he belongs...
and may be more ways, do let me know if there are...

Now Let the Code Talk

to find Location from IP address i recommend using an IP database there are two ways of doing this, first download a IP database and install it on you own server and find location from there, and update it monthly or bi-monthly.
Second is more cool way of doing this using an API... go to ipinfodb.com sign up there and get API key and use the following code
function getLocationViaIP($IP_ADDRSS,$CITY=false){

    $KEY="YOUR_API_KEY_HERE";

    $TYPE=$CITY==true?"ip-city":"ip-country";
    // Check if city information is requried too

    $API_URL="http://api.ipinfodb.com/v3/$TYPE/?key=$KEY&ip=$IP_ADDRSS&format=xml";
    // Construst API URL
    // there two more formats json and raw if preder xml
    // there is another parameter callback if you use it
    // via javascript it will be handy
    
    $xml=simplexml_load_file($API_URL);
    
    if($xml->statusCode=="OK"){
        // Check if everything is OK
        
        echo "Country Name:".$xml->countryCode."< b r >";
        echo "Country Code:".$xml->countryName."< b r >";

        if($CITY){
            // Print City information too if requried
            echo "Region Name:".$xml->regionName."< b r >";
            echo "City Name:".$xml->cityName."< b r >";
            echo "Zip Code:".$xml->zipCode."< b r >";
            echo "Latitude:".$xml->latitude."< b r >";
            echo "Longitude:".$xml->longitude."< b r >";
            echo "Time Zone:".$xml->timeZone."< b r >";
        }
    }else{
        echo "Somthing Went Wrong";
    }
}
(break line tag intentionally written like this for display purpose)to call this method for example
$this->getLocationViaIP("74.125.45.100",true);

// alternativly you can use this too

$this->getLocationViaIP($_SERVER["REMOTE_ADDR"],true);

it will be a good idea that you store IP's Location somewhere in Cookies or in you local DB to minimize extra call to API.
Continue Reading...

Tuesday, April 12, 2011

PHP Cookies by Example

PHP Cookies by Example
Cookie is a Dutch word koekje or (informal) koekie which means little cake, and arrived in the English language through the Dutch in North America.

In the United States and Canada, a cookie is a small, flat-baked treat, usually containing fat, flour, eggs and sugar. In most English-speaking countries outside North America, the most common word for this is biscuit; in many regions both terms are used, while in others the two words have different meanings. A cookie is a plain bun in Scotland,[1] while in the United States a biscuit is a kind of quick bread similar to a scone. In the United Kingdom, a cookie is referred to as a baked biscuit most commonly containing chocolate chips.

you can see my love for cookies, let move to the point :)

HTTP Cookies

The term "cookie" (in IT) was derived from "magic cookie", which is a packet of data a program receives and sends again unchanged.

A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece of text stored on a user's computer by their web browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data.

almost all web programming languages provide support for Cookies, PHP is no exception.

Cookies in PHP

To create and modify a cookie, use the PHP function setcookie(). setcookie() takes up to seven arguments, depending upon how much control you want over the cookie and who can read its value. To read value from Cookies you set you use $_COOKIE global array provided by PHP

Method Signature of setcookie();
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
name:The name of the cookie.

value:The value of the cookie. This value is stored on the clients computer; do not store sensitive information.

expire:The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
path:The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

domain:The domain that the cookie is available to. To make the cookie available on all subdomains of example.com (including example.com itself) then you'd set it to '.example.com'. Although some browsers will accept cookies without the initial ., » RFC 2109 requires it to be included. Setting the domain to 'www.example.com' or '.www.example.com' will make the cookie only available in the www subdomain.

secure:Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

httponly:When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers). Added in PHP 5.2.0. TRUE or FALSE

Now Let the code Talk

Simplest way to make a Cookie.
setcookie('name', 'value');
To let cookie expire after a certain time we use mktime() to make time, it gives us time in seconds.
$expireTime=mktime(0,0,0,4,13,2011);
setcookie('name', 'value',$expireTime);
The next two parameters for setcookie() let you control the path and the domain of who can read your cookie. By default, only pages equal to or lower down in the hierarchy on the same server that sends the cookie can read its value. That's for security's sake. However, if you had an account that's sometimes "www.domain.com" but also "other.domain.com," and your account lets you serve pages from ~/myhome, you should modify setcookie() as such.
$expireTime=mktime(0,0,0,4,13,2011);
setcookie('name', 'value',$expireTime,'~/PATH', '.tutorialjinni.com');
to read a Cookie
echo $_COOKIE['NAME_OF_COOKIE'];
// print value of specified Cookie
to Delete a cookie just pass the name of the cookie you want to delete
setcookie("NAME_OF_THE_COOKIE_WHOM_TO_DELETE");
//deletes the specified cookie
Enjoy Cookies :)
Continue Reading...

Sunday, April 10, 2011

PHP cURL by Example

cURL is a computer software project providing a library and command-line tool for transferring data using various protocols. The cURL project produces two products, libcurl and cURL. It was first released in 1997.

cURL in php mostly used for getting contents of a webpage and parse it to extract data, other uses may be to fetch data from a web-service. Here arise a question is cURL is the only way of fetching data? simple answer is NO, there are other methods by which we can do our it, like,
  • you can use file_get_contents(); method.
  • or you can open a socket using fsockopen();
  • one can also use fopen();
  • or if your resource is xml or xhtml you can use simplexml_load_file();
and many more... so why cURL then? because it provide us with the richest set of options, now lets see it by an example...
 function getCURL($url){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_USERAGENT, getRandomUA());
  curl_setopt($ch, CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_AUTOREFERER, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  $html = curl_exec($ch);
  return $html;
 }
    function getRandomUA(){
        $arr=array();
        $arr[]="HTC_Touch_3G Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 7.11)";
        $arr[]="BlackBerry9700/5.0.0.862 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/331 UNTRUSTED/1.0 3gpp-gba";
        $arr[]="Opera/9.80 (J2ME/MIDP; Opera Mini/9.80 (J2ME/23.377; U; en) Presto/2.5.25 Version/10.54";
        $arr[]="Mozilla/5.0 (Windows; U; Windows NT 6.1; sv-SE) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4";
        $arr[]="Mozilla/4.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; fi-fi) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148a Safari/6533.18.5";
        $arr[]="Mozilla/6.0 (X11; U; Linux i686; en-US; rv:1.9a3pre) Gecko/20070330";
        $arr[]="Mozilla/3.0 (X11; Linux i686; rv:2.0b12pre) Gecko/20110204 SeaMonkey/2.1b3pre";
        $arr[]="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.127 Safari/533.4";
        $arr[]="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.4) Gecko/20060612 Firefox/1.5.0.4 Flock/0.7.0.17.1";
        $arr[]="Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2";
        $arr[]="Mozilla/3.0 (x86 [en] Windows NT 5.1; Sun)";
        $arr[]="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)";
        $k=rand(0, count($arr)-1);
        return $arr[$k];
    }
there is a reason why we have to you the second function getRandomUA(), some website block php default header, and if you are heavily requesting with same header it may block you even then, so we use multiple headers randomly to avoid this scenario.
Continue Reading...

Saturday, April 9, 2011

PHP Session by Example

PHP Session login example
When run application on your computer, the computer know who you are, what are you doing, what data you alter, when you close your application and so forth, this is called session. In web communication we use Hyper Text Transfer Protocol (HTTP), which is a stateless protocol that does not retain information on server and treat all request as independent request. To make it remember user information we use SESSION.

There are many ways to retain this information, most common are
  • Session Management via Cookies
  • Embedding Session information in URLs
  • Storing Information on server in $_SESSION array (in PHP)
and many more... every scheme has its own advantages and disadvantages, In this tutorial we will make session using $_SESSION and do it using an example, say making a user log-in page, please note; session variables hold information about one single user, and are available to all pages in one application.

To start a session our page has its first line to session_start(); this tell the server to initialize $_SESSION array if it is already started it will make it available it to page. We can add any number or variable to this array, in our example we will make an simple HTML page and display user a greeting if he is log-in else we will show him a log-in form.

now Let the Code Talk

<?php
session_start();
error_reporting(0);

// CHECK if form is submitted
if(isset ($_POST["submit"])){
    $username=$_POST["username"];
    $password=$_POST["password"];

    if($username=="originative" && $password=="tutorialjinni"){
        $_SESSION["isLoggedIn"]=1;
        //setting a varable so that later i know
        // that this user i logged in
        $_SESSION["uname"]=$username;
        //setting another variable
    }
}
// for logout or destroy session
if(isset($_GET["action"])){
    if($_GET["action"]){

        session_unset();
        //unset all session variables

        session_destroy();
        // destroy session
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Session Login Example | Tutorial Jinni | Originative Systems</title>
</head>
    <body>
        <?php
            if(!$_SESSION["isLoggedIn"]==1){
                // checking the value of isLoggedIn
        ?>
        <form action="" method="post">
          <table width="400" border="0" cellpadding="8" cellspacing="0">
            <tr>
              <td align="right">User Name : </td>
              <td><label for="username"></label>
              <input name="username" type="text" id="username" size="35" /></td>
            </tr>
            <tr>
              <td align="right">Password : </td>
              <td><label for="pass"></label>
              <input name="password" type="password" id="pass" size="35" /></td>
            </tr>
            <tr>
              <td colspan="2"><input type="submit" name="submit" id="submit" value="Let me In" /></td>
            </tr>
          </table>
        </form>
        <?php
            }
            else{
                echo "Welcome <b><em>".$_SESSION["uname"]."</em></b>
                    To Logout Click <a href='sess.php?action=logout'>Here</a>";
            }
        ?>
    </body>
</html>


Continue Reading...

Thursday, April 7, 2011

Symfony url_for in ACTION

symfony tutorial
Symfony url_for() method return the URL according to current context, remember url_for method is available only in VIEW part of Symfony MVC, what if one wants to create a HTML in MODEL (although it is not recommended, just in case) and in that HTML there are link which needs to be formatted according to current context, for that there is a method in Symfony generateUrl().

generateUrl() Method Signature

string generateUrl('URL_ROUTE',
         array(
        'module'=>'MODULE_NAME',
        'action'=>'ACTION_CALLED',
        'PARAMS'=>'VALUE'
             ),
        $isAbsolute
);
URL_ROUTE is the SEO Friendly URL pattern you defined in config file of module, if not defined use 'default' second is the config array in which we define module name and the action we want to call next is the parameter we want to pass via URL you can pass as many as you want params through it, in the form 'PARAM1'=>'VALUE1','PARAM2'=>'VALUE2',.... and last parameter is $isAbsolute it instruct whether we want relative or absolute URL, default is false it generate relative URL by default.

Example

$this->generateUrl('default',
array('module'=>'User','action'=>'EditUser','uid'=>$id))
the out will be something like this...
backend_dev.php/User/EditUser/uid/1130
hope it helps...
Continue Reading...

Monday, April 4, 2011

Yammer API Example

yammer api php example
Yammer is an enterprise social network service that was launched in September 2008.Unlike Twitter, which is used for broadcasting messages to the public, Yammer is used for private communication within organizations or between organizational members and pre-designated groups, making it an example of enterprise social software. Yammer originally launched as an enterprise micro blogging service and has evolved to become a fully-fledged enterprise social network.

Yammer Offer its API to create personalized yammer applications for mobile phones and desktop, to in this tutorial we will make and application, authorize it and access data from user profile. To access data from yammer api one passed from following steps
  1. Register your Application on Yammer and get Application Secret and Application Key.
  2. Then get Token and Token secret from above data.
  3. Then Authorize your application using the token and get the Auth Code.
  4. Then Auth Code, token and token get the access token and access token secret.
  5. Finally get Data from the user profile.
And now get all the obvious stuff out of the way and let the code talk :) i made a small application demonstrating said steps.

yammer php api demo
Click on Image for full size

and the code...
<?php
error_reporting(0);

require_once 'common.inc.php';
require_once 'Yammer.php';
$appKey="YOUR APP KEY HERE";
$appSec="YOUR APP SECRET HERE";
$token="";
$tokenSec="";
$authcode="";
$accessToken="";
$accessTokenSec="";

$b=false;
if(isset ($_POST["isSubmit"])){

    $appKey=$_POST["appkey"]==""?"YOUR APP KEY HERE":$_POST["appkey"];
    $appSec=$_POST["appsec"]==""?"YOUR APP SECRET HERE":$_POST["appsec"];
    $token=$_POST["token"];
    $tokenSec=$_POST["tokensec"];
    $authcode=$_POST["authcode"];
    $accessToken=$_POST["accessToken"];
    $accessTokenSec=$_POST["accessTokenSec"];

    $test_consumer = new OAuthConsumer($appKey, $appSec, NULL);

    if(isset ($_POST["reqtoken"])){
        
        $endpoint="https://www.yammer.com/oauth/request_token";
        
        $req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $endpoint, null);
        $req_req->sign_request($plaintext_method , $test_consumer, NULL);

        $data=getContents($req_req->to_url());

        $data=  explode("&", $data);
        $token= str_replace("oauth_token=", "", $data[0]);
        $tokenSec= str_replace("oauth_token_secret=", "", $data[1]);
        $b=true;
    }
    if(isset ($_POST["acctoken"])){
        
        $endpoint="https://www.yammer.com/oauth/access_token";
        $param=Array('oauth_verifier'=>"$authcode");

        $test_token = new OAuthConsumer($token, $tokenSec);

        $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, "GET", $endpoint, $param);
        $acc_req->sign_request($plaintext_method, $test_consumer, $test_token);

        $data=getContents($acc_req->to_url());
        $data=  explode("&", $data);
        $accessToken= str_replace("oauth_token=", "", $data[0]);
        $accessTokenSec= str_replace("oauth_token_secret=", "", $data[1]);

    }
    if(isset ($_POST["getData"])){
        $obj=new Arc90_Service_Yammer($appKey, $appSec , $accessToken, $accessTokenSec, 10);
        $json=json_decode($obj->getMessagesAll());
        $k =count($json->messages);
        echo "

Messages Retrived via API

    "; for( $i=0;$i<$k;$i++){ echo "
  1. ".$json->messages[$i]->body->plain."
  2. "; } echo "
"; } } function getContents($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); echo curl_error($ch); curl_close($ch); return $data; } ?>
and the html code ...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
input{
 font-size:24px;
 color:#666;
}
body {
font-size:20px;
font-family: Verdana,Arial,Helvetica,sans-serif;

}
.style7 {
 color: #990033;
 font-weight: bold;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Yammer OAuth & API Test -  Originative Systems</title>
</head>

<body>
    <form action="" method="post">
<table width="100%" border="1" style="border-collapse:collapse; border:solid 2px outset" cellpadding="8" cellspacing="5">
  <tr>
    <td colspan="5"><span class="style7">Yammer OAuth & API Test</span> </td>
  </tr>
  <tr>
    <td width="25%"><div align="right">Application Key : </div></td>
    <td width="75%" colspan="4"><label>
      <input name="appkey" type="text" value="<?php echo $appKey; ?>" id="appkey" size="40" />
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Application Secrect : </div></td>
    <td colspan="4"><label>
      <input name="appsec" type="text" value="<?php echo $appSec; ?>" id="appsec" size="40" />
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Token : </div></td>
    <td colspan="4"><label>
      <input name="token" type="text" value="<?php echo $token; ?>" id="token" size="40" />
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Token Secrect : </div></td>
    <td colspan="4"><label>
      <input name="tokensec" type="text" value="<?php echo $tokenSec; ?>" id="tokensec" size="40" />
      </label>
      <?php if($b){
         echo "<INPUT type='button' value='Authorize Request' onClick=\"window.open('https://www.yammer.com/oauth/authorize?oauth_token=$token','Authorize Yammer Request','width=500,height=500')\"> ";
      }
      ?>
    </td>
  </tr>
  <tr>
    <td><div align="right">Auth Code : </div></td>
    <td colspan="3"><label>
      <input name="authcode" type="text" value="<?php echo $authcode; ?>" id="token" size="4"  />
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Access Token : </div></td>
    <td colspan="4"><label>
      <input name="accessToken" type="text" value="<?php echo $accessToken; ?>" id="token" size="40" />
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Access Token Secret : </div></td>
    <td colspan="4"><label>
      <input name="accessTokenSec" type="text" value="<?php echo $accessTokenSec; ?>" id="token" size="40" />
    </label></td>
  </tr>
  <tr>
    <td> </td>
    <td align="center"><label>
      <input name="reqtoken" type="submit" id="reqtoken" value="Request Token" />
    </label>
    </td>
    <td align="center"><label>
      <input name="acctoken" type="submit" id="acctoken" value="Access Token" />
    </label></td>
    <td align="center"><label>
      <input name="getData" type="submit" id="acctoken" value="Get Data" />
    </label></td>
  </tr>
</table>
        <input type="hidden" name="isSubmit" value=""/>
    </form>
</body>
</html>
just run it and you will understand it, there nothing left to explain after source code, download netbeans project with all the files used and enjoy :)

download yammer api
Download Yammer API Example

Continue Reading...

Tuesday, March 29, 2011

Reading CSV File in PHP

php csv
The comma-separated values file format is a set of file formats used to store tabular data in which numbers and text are stored in plain textual form that can be read in a text editor. Lines in the text file represent rows of a table, and commas in a line separate what are fields in the tables row. Different implementations of CSV arise as the format is modified to handle richer table content such as allowing a different field separator character, (which is useful if numeric fields are written with a comma instead of a decimal point); or extensions to allow numbers, the separator character, or newline characters in text fields.

A file format is a particular way to encode information for storage in a computer file. Particularly, files encoded using the CSV format are used to store tabular data. The format dates back to the early days of business computing and is widely used to pass data between computers with different internal word sizes, data formatting needs, and so forth. For this reason, CSV files are common on all computer platforms.

As the Web evolves more and more applications go online, generally to feed data to the new system from existing system we use CSV files for it. PHP as the most popular language for web programming offer many ways to read a CSV file, we consider here two ways of doing it, firstly

The Usual Way

In this example we are considering a file is uploaded through a web form,
        ...
        ...
        ...
        
       $newLineChar="\n";
       $delimeter=",";

       $fileHandle=fopen($_FILES["CSVFILE"]["tmp_name"], 'r');
       $contents = fread ($fileHandle,filesize ($_FILES["CSVFILE"]["tmp_name"]));
       fclose($fileHandle);

       $lines=explode($newLineChar, $contents);

       // dividing contents of file line by line

       foreach($lines as $line){
           
           $values=explode($delimeter, trim($line));

           // we trim it because line break char is still there
           // trim removes it !

           echo $values[0]."
"; echo $values[1]."
"; echo $values[2]."
"; // you can traverse values using foreach // also by the above method if you have // few values like i have } .... .... ....
here we divide and conquer technique first we split the contents of line line by line and the split each line by it delimiter and the read it, this is the most easy and simple method to me :)

PHP had a function to deal with CSV let give a look at it too...

fgetcsv

fgetcsv — Gets line from file pointer and parse for CSV fields, Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Method Signature

array fgetcsv ( resource $handle 
[, int $length = 0 
[, string $delimiter = ',' 
[, string $enclosure = '"' 
[, string $escape = '\\' 
]]]] )

Parameters

handle: A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
length: Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower.
delimiter: Set the field delimiter (one character only).
enclosure: Set the field enclosure character (one character only).
escape: Set the escape character (one character only). Defaults as a backslash.

Return Values

Returns an indexed array containing the fields read.
Note:A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Note:If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Note:Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Example

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "

$num fields in line $row:

\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "
\n"; } } fclose($handle); } ?>
Continue Reading...

Thursday, March 17, 2011

Symfony Session Timeout

Session handling is one of the most important things in web development, it helps to track user, its activity and most importantly give user a personalization feel, Symfony make it very easy to handle user Sessions by changing just one value in a yaml file you can manage user's Sessions, lets get to point :) i am using Netbeans (great IDE) for my development... open you project in Netbeans, if you dont know how to configure Symfony to work with Netbeans this might help you.

Symfony Session Timeout

Open factories.yml located in apps/[MODULE_NAME]/config/factories.yml you will see somthing like this...
all:
  user:
    class: myUser
    param:
      timeout: false
myUser is the child class of sfBasicSecurityUser which is in apps/[MODULE_NAME]/lib/myUser.class.php you can change the name of the class, timeout is the property that controls Session time out of user if this is set as false time out never occur if a numeric value is given time out will occur after that, timeout value is in milliseconds i.e. if value is 36000 timeout will occur in 10 min (60*60*10), simple and easy is not it?
Continue Reading...

Wednesday, March 16, 2011

HTML to PDF - PHP Tutorial

Generating PDF from HTML using PHP is fairly simple and easy using HTML2FPDF

Lets get straight to point, who has time to read and "write" the obvious stuff :P

here is the Simplest code to create HTML to PDF using PHP... First the HTML we want to convert to PDF
<table width='500px' border='1' cellpadding='0' cellspacing='0' style=' border-collapse:collapse;'>
      <tr>
 <td colspan='2' align='left'> Jhon Doe <br>
     Some where on earth :) <br>
     email@domain.com <br>
 </td>
      </tr>
      <tr>
 <td width='75%' align='center'>Description</td>
 <td width='25%' align='center' valign='middle'>Price</td>
      </tr>
       <tr>
  <td align='left'>Some purchased items</td>
  <td align='center' valign='middle'>$ 100.00</td>
       </tr>

       <tr>
  <td align='left'>Another purchased items</td>
  <td align='center' valign='middle'>$ 55.00</td>
       </tr>

       <tr>
  <td align='left'>Another purchased items</td>
  <td align='center' valign='middle'>$ 35.00</td>
       </tr>

       <tr>
  <td align='left'>Another purchased items</td>
  <td align='center' valign='middle'>$ 123.00</td>
       </tr>

       <tr>
  <td align='left'>Yet Another purchased items</td>
  <td align='center' valign='middle'>$ 307.00</td>
       </tr>

       <tr>
  <td align='left'>Another purchased items</td>
  <td align='center' valign='middle'>$ 342.00</td>
       </tr>
     <tr>
 <td align='right'>Total Amount</td>
 <td align='center' valign='middle'>$ 962</td>
      </tr>
      <tr>
 <td align='right'>Advance</td>
 <td align='center' valign='middle'>$ 0.00</td>
      </tr>
      <tr>
 <td align='right'>Total Payable Amount:</td>
 <td align='center' valign='middle'>$ 962</td>
      </tr>
    </table>
Now the PHP code to do the work done
<?php
require('html2fpdf.php');

$name="print_".time().".pdf";
// $name name of the PDF generated.

$html=getHTML();
// getHTML() function will return the above mention HTML

$pdf=new HTML2FPDF();
$pdf->AddPage();
$pdf->WriteHTML($html);

$re=$pdf->Output($name,"D");

// Genrate PDF, There few Options
// 1. D => Download the File
// 2. I => Send to standard output
// 3. F => Save to local file
// 4. S => Return as a string

?>

Image Integration

Its is very easy to integrate images in the PDF, the only thing required is that use absolute path for images, relative path of an image throws an exception.

Example

There many Other options which can be used...
Image Example HTML Page

Test #1 - RTF-like text. Click here for results.

Test #2 - Links,Colors,Forms. Click here for results.

Test #3 - Table. Click here for results.

Test #4 - CSS. Click here for results.

Test #6 - P,DIV tests. Click here for results.

A real HTML page. Click here for results.

Download

Download all the requried items from below...
html to PDF using PHP
HTML to PDF - PHP Tutorial
Continue Reading...

Friday, February 25, 2011

Paging in Symfony

In this tutorial we will learn how to implement Paging in Symfony, the process is fairly simple and easy to implement, just a little know how to PHP, Symfony and Doctrine is required.
First the code we will write in Controller or Symfony module Action class.
public function executePaging(sfWebRequest $request){

        $results_per_page=10;
        $set_first_page=1;

        $this->pagination = new sfDoctrinePager('User', $results_per_page);
        $this->pagination->setQuery(Doctrine::getTable('User')->createQuery('u'));
        $this->pagination->setPage($request->getParameter('page', $set_first_page));
        $this->pagination->init();
        
    }
now the code we write in View or the ethodNameSuccess in our case PagingSuccess.php
<?php foreach ($pagination->getResults() as $users): ?>

<?php endforeach; ?> 
<?php echo $users->getId(); ?> <?php echo $users->getFirstName(); ?> <?php echo $users->getLastName(); ?> <?php echo $users->getEmail(); ?>
<?php echo link_to('<<', 'myModule/Paging?page='.$pagination->getFirstPage()) ?>
<?php if ($pagination->haveToPaginate()): ?> <?php $links = $pagination->getLinks(); foreach ($links as $page): ?>
<?php echo ($page == $pagination->getPage()) ? $page : link_to($page, 'myModule/Paging?page='.$page) ?>
<?php endforeach ?> <?php endif ?>
<?php echo link_to('>>', 'myModule/Paging?page='.$pagination->getLastPage()) ?>
try to implement it and you will see its very easy :)
Continue Reading...

Sunday, February 20, 2011

Symfony Doctrine Native SQL

in my earlier post, Symfony Doctrine Execute Raw SQL i execute Raw or Native SQL quries, however method describe previously can only perform SELECT operations, in this post we will execute all type of SQL quires i.e. SELECT, INSERT, UPDATE, DELETE
public function myDBWrapper($query,$type=0){
      $connection=Doctrine_Manager::getInstance()
                  ->getCurrentConnection()->getDbh();
      // Get Connection of Database

      $statement=$connection->prepare($query);
      // Make Statement

      $statement->execute();
      // Execute Query

      if($type==0){
          // Check if it is SELECT query
          
          $results = $statement->fetchAll();
          return $results;
      }

  }

Usage

public function executeMyDBWrapperTest(sfWebRequest $request){

       $insertQuery="INSERT INTO users (username,email)
                       VALUES ('Originative','originative@live.com')";
       $selectQuery="Select * from users";

       $this->myDBWrapper($insertQuery);
       // INSERT data in table
       
       $this->results=$this->myDBWrapper($selectQuery, 1);
       // Fetch data from table save output 
       // which will be displayed in
       // MyDBWrapperTestSuccess.php

   }
Continue Reading...
 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems