Twitter OAuth Sign In Tutorial: Get A User’s Profile Information


Twitter Bird

Since we are going to be using three classes to handle all the OAuth requests for us I would like to explain what will be going on in the background before we begin. I will refer to twitter’s API as the API but know that this applies to all others that use OAuth.

The way OAuth works is the like this

  • your script sends a url to an API
  • the API sends a token (oauth_token) back to us,
  • we use this token to make a url that will take the user to a verification page
  • after granting us access we can request a secret token or access token (oauth_token_secret)
  • now we can use this secret token to make calls to the API

Step 1: The set up

Make three files “keys.php” , “sign-in.php” and “profile-page.php”m

The firs file will be used to store you twitter app keys. We will then make a login form with a twitter sign in button and process the response with “profile-page.php”.

Step 2: Register you twitter application.

Go to this link to register you app Twitter OAuth, your callback URL must be the URL to your “profile-page.php” file.

In your “keys.php” file make two variables, one for your “consumer key” and for your “consumer secret” .

$consumerKey='xxxxxxxxxx';
$consumerSecret='xxxxxxxxxxxxxxxxxxxxxxx';

Step 3: Some files you need

We’ll be using three classes developed by   @jmathai

Download the files “EpiCurl.php”, “EpiOAuth.php” and “EpiTwitter.php” from this link EpiFramework and put them in the same folder as the 3 files in step 1.

Step 4 : Get a  ”Sign in with Twitter” button

Go to this page (sign in with twitter buttons) , scroll all the way down, and download your favorite button image.

Step 5: The sign in page

This is where we request the first token (oauth_token) and use it to make a link to to twitter’s verification page.

Open your “sign-in.php” file and include the three Epi classes and keys file.

We will also make an object for EpiTwitter, the constructor for this class takes two paramaters, you cosumerkey and cosumer secret from step 2.

EpiTwitter has a function called “getAuthenticateUrl()” , this function returns a URL which we’ll use to make a link ( sign in button) to the twitter authentication page.

Contents of “sign-in.php”

<?php
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'keys.php';

$Twitter = new EpiTwitter($consumerKey, $consumerSecret);

echo '<a href="' . $Twitter->getAuthenticateUrl() . '">
<img src="twitterButton.png" alt="sign in with twitter" />
</a>';
?>

Step 6: User is Now on Twitter’s Verification Page.

If your users allow your app they will be redirected to your call back URL with an “oauth_token” variable in the url, http://www.yourdomain.com/profile-page.php?oauth_token=xxxxxxxxxxxxxx  for example.

If they deny access twitter will show them  the following message:

“OK, you’ve denied YourAppName access to interact with your account!”

YourAppName will be a link to your call back url with a “denied” variable in the url. Something like this

http://www.yourdomain.com/profile-page.php?denied=xxxxxxxxxxxxxxx

Step 7: The Profile Page

This is where we will retrieve the user’s info from twitter’s api.

Begin by making an object of the class EpiTwitter.

// include Epi
require_once 'classes/php/oauth/keys.php';
require_once 'classes/php/oauth/EpiCurl.php';
require_once 'classes/php/oauth/EpiOAuth.php';
require_once 'classes/php/oauth/EpiTwitter.php';

$Twitter = new EpiTwitter($consumerKey, $consumerSecret);

We should also check to see if the user allowed or denied access by checking if the “oauth_token” variable is set in our url (Cookie variables explained after the snippet)

// previous code here
if(isset($_GET['oauth_token']) || (isset($_COOKIE['oauth_token']) && isset($_COOKIE['oauth_token_secret'])))
{
  // user has signed in
}
elseif(isset($_GET['denied'])
{
 // user denied access
 echo 'You must sign in through twitter first';
}
else
{
// user not logged in
 echo 'You are not logged in';
}

Before we get a user’s info,  we need an access token, to get this token we use a function called getAccessToken(). The function getAccessToken() returns two variables, oauth_token and oauth_token_secret, we are going to store these two variables in two different cookies, that is why I also checked for these cookies in the previous code.

If the user has already signed in when they get to this page then there is no need to request another token, that means there is no need to call getAccessToken() if we already obtained the secret token and stored it in a cookie. Put the following code where it said “// user has signed in” up above.

// user has signed in
	if( !isset($_COOKIE['oauth_token']) || !isset($_COOKIE['oauth_token_secret']) )
	{
		// user comes from twitter
                // send token to twitter
	        $Twitter->setToken($_GET['oauth_token']);
               // get secret token
		$token = $Twitter->getAccessToken();
                // make the cookies for tokens
		setcookie('oauth_token', $token->oauth_token);
		setcookie('oauth_token_secret', $token->oauth_token_secret);
               // pass tokens to EpiTwitter object
		$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);

	}
	else
	{
	 // user switched pages and came back or got here directly, stilled logged in
        // pass tokens to EpiTwitter object
	 $Twitter->setToken($_COOKIE['oauth_token'],$_COOKIE['oauth_token_secret']);
	}

Finally we can use the object $Twitter to get the user’s profile info. And this is what it looks like.

    $user= $Twitter->get_accountVerify_credentials();

The variable $user is actually an object of SimpleXml containing this response.
Now let’s display some info.

// show screen name (not real name)
echo $user->screen_name}
// show profile image url
echo $user->profile_image_url
// show last tweet
echo $user->status->text;

full contents of profile-page.php

<?php

// include Epi
require_once 'classes/php/oauth/keys.php';
require_once 'classes/php/oauth/EpiCurl.php';
require_once 'classes/php/oauth/EpiOAuth.php';
require_once 'classes/php/oauth/EpiTwitter.php';
	    $Twitter = new EpiTwitter($consumerKey, $consumerSecret);

if(isset($_GET['oauth_token']) || (isset($_COOKIE['oauth_token']) && isset($_COOKIE['oauth_token_secret'])))
{
// user accepted access
	if( !isset($_COOKIE['oauth_token']) || !isset($_COOKIE['oauth_token_secret']) )
	{
		// user comes from twitter
	    $Twitter->setToken($_GET['oauth_token']);
		$token = $Twitter->getAccessToken();
		setcookie('oauth_token', $token->oauth_token);
		setcookie('oauth_token_secret', $token->oauth_token_secret);
		$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);

	}
	else
	{
	 // user switched pages and came back or got here directly, stilled logged in
	 $Twitter->setToken($_COOKIE['oauth_token'],$_COOKIE['oauth_token_secret']);
	}

    $user= $Twitter->get_accountVerify_credentials();
	echo "
	<p>
	Username: <br />
	<strong>{$user->screen_name}</strong><br />
	Profile Image:<br/>
	<img src=\"{$user->profile_image_url}\"><br />
	Last Tweet: <br />
	<strong>{$user->status->text}</strong><br/>

	</p>";

}
elseif(isset($_GET['denied']))
{
 // user denied access
 echo 'You must sign in through twitter first';
}
else
{
// user not logged in
 echo 'You are not logged in';
}

To log a user out, make a log-out.php for example, and expire the cookies.

setcookie("oauth_token", '', time()-100);
setcookie("oauth_token_secret", '', time()-100);

Epi does not currently support twitter sign out even though twitter’s API does, but the user will be signed out of twitter when they close the browser’s window. I will show you how to update statuses and other neat stuff in part of two of this tutorial.


저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

트위터 OAuth Sign in 튜토리얼  (0) 2013.07.22
트위터 oauth with php  (0) 2013.07.22
php 파일 include  (0) 2013.01.11
php 파일업로드 크기 제한 설정 php.ini (nginx)  (0) 2013.01.05
php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
How to Authenticate Users With Twitter OAuth

\Rating:

How to Authenticate Users With Twitter OAuth

Tutorial Details


Beginning August 16th, Twitter will no longer support the basic authentication protocol for its platform. That means the only way to authenticate users will be through a Twitter application. In this tutorial, I’ll show you how to use Twitter as your one-click authentication system, just as we did with Facebook.


Step 1: Setting Up The Application

We’ll first need to set up a new Twitter application.

  • Register a new app at dev.twitter.com/apps/
  • Fill in the fields for your site accordingly, just be sure to select Browser in Application Type, and set the Callback URL to something like http://localhost.com/twitter_login.php(http://localhost/ won’t be accepted because it doesn’t have a domain name).
  • Finally, select Read & Write. Fill in the captcha, click “Register Application,” and accept the Terms of Service.

Now, you’ll see the screen as shown below.

We will be using the Consumer key and Consumer secret values shortly.

Now that this is done, let’s download a library. As we will be coding with PHP, it seems the best one istwitteroauth; but if you’re using another language, you’ll find other good libraries here.

Find the twitteroauth directory inside the zip file, and extract it to your application’s folder.

Finally, since we’re using Twitter to authenticate users, we’ll need a database table to store those users. Here’s a quick example of what we will be doing.

  1. CREATE TABLE `users` (  
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
  3.     `oauth_provider` varchar(10),  
  4.     `oauth_uid` text,  
  5.     `oauth_token` text,  
  6.     `oauth_secret` text,  
  7.     `username` text,  
  8.     PRIMARY KEY (`id`)  
  9. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;  

Notice the oauth_token and oauth_secret fields. Twitter’s OAuth requires token and a token_secretvalues to authenticate the users, so that’s why we’re including those. With that, we are done with the setup!


Step 2: Registering Users

In this step we, will be doing three things:

  • Requesting authorization from Twitter.
  • Registering or, if the user is already registered, logging the user in.
  • Setting the data into a session.

Requesting authorization

The OAuth workflow starts by generating a URL for the request; the user is redirected to that URL and is asked for authorization. After granting it, the application redirects back to our server with two tokens in the URL parameters, which are required for the authentication.

Let’s begin by including the library and starting a session handler.

  1. require("twitteroauth/twitteroauth.php");  
  2. session_start();  

After that, let’s create a new TwitterOAuth instance, giving it the consumer key and consumer secret that Twitter gave us when we created the application. Then, we’ll request the authentication tokens, saving them to the session, and redirect the user to Twitter for authorization.

  1. // The TwitterOAuth instance  
  2. $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY''YOUR_CONSUMER_SECRET');  
  3. // Requesting authentication tokens, the parameter is the URL we will be redirected to  
  4. $request_token = $twitteroauth->getRequestToken('http://localhost.com/twitter_oauth.php');  
  5.   
  6. // Saving them into the session  
  7. $_SESSION['oauth_token'] = $request_token['oauth_token'];  
  8. $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];  
  9.   
  10. // If everything goes well..  
  11. if($twitteroauth->http_code==200){  
  12.     // Let's generate the URL and redirect  
  13.     $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']); 
  14.     header('Location: '. $url); 
  15. } else { 
  16.     // It's a bad idea to kill the script, but we've got to know when there's an error.  
  17.     die('Something wrong happened.');  
  18. }  

Save it as twitter_login.php, go to http://localhost.com/twitter_login.php or whatever your local host name is. If everything went correctly, you should be redirected to twitter.com, and you should see something like this.

Click allow, and you will be redirected to http://localhost.com/twitter_oauth.php — since we set this URL as a parameter in the getRequestToken statement. We haven’t created that file, so it should throw an error. Create that file, and then include the library and start a session, just like we did in the first file.

After that, we will need three things:

  • Auth verifier in the URL query data
  • Auth token from the session
  • Auth secret from the session

So, the first thing to do in this script is validate this data and redirect if one of these variables is empty.

  1. if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){  
  2.     // We've got everything we need  
  3. else {  
  4.     // Something's missing, go back to square 1  
  5.     header('Location: twitter_login.php');  
  6. }  

Now, if everything is set, inside the conditional we will be creating the TwitterOAuth instance, but with the tokens we just got as third and fourth parameters; after that, we will be getting the access token, which is an array. That token is the one we will be saving to the database. Finally, we’ll do a quick test to see if everything works out.

  1. // TwitterOAuth instance, with two new parameters we got in twitter_login.php  
  2. $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY''YOUR_CONSUMER_SECRET'$_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);  
  3. // Let's request the access token  
  4. $access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']); 
  5. // Save it in a session var 
  6. $_SESSION['access_token'] = $access_token; 
  7. // Let's get the user's info 
  8. $user_info = $twitteroauth->get('account/verify_credentials'); 
  9. // Print user's info  
  10. print_r($user_info);  

If nothing goes wrong, the print_r should show the user’s data. You can get the user’s id with$user_info->id, his or her username with $user_info->screen_name; there’s a bunch of other info in there as well.

It is very important to realize that the oauth_verifier hasn’t been used before this. If you see the user’s info correctly and then reload the page, the script will throw an error since this variable has been used. Just go back to twitter_login.php and it will automatically generate another fresh token.

Registering users

Now that we have the user’s info we can go ahead and register them, but first we have to check if they exist in our database. Let’s begin by connecting to the database. Add these lines in the script’s beginning.

  1. mysql_connect('localhost''YOUR_USERNAME''YOUR_PASSWORD');  
  2. mysql_select_db('YOUR_DATABASE');  

Modify the database info as required. Now, just below where we fetch the user’s info, we’ll have to check for the user in our database. If he or she is not there, we’ll enter the info. If the user has been registered, we must update the tokens, because Twitter has generated new ones and the ones we have in the database are now unusable. Finally, we set the user’s info to the session vars and redirect to twitter_update.php.

  1. if(isset($user_info->error)){  
  2.     // Something's wrong, go back to square 1  
  3.     header('Location: twitter_login.php'); 
  4. } else { 
  5.     // Let's find the user by its ID  
  6.     $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = "$user_info->id);  
  7.     $result = mysql_fetch_array($query);  
  8.   
  9.     // If not, let's add it to the database  
  10.     if(empty($result)){  
  11.         $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");  
  12.         $query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());  
  13.         $result = mysql_fetch_array($query);  
  14.     } else {  
  15.         // Update the tokens  
  16.         $query = mysql_query("UPDATE users SET oauth_token = '{$access_token['oauth_token']}', oauth_secret = '{$access_token['oauth_token_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");  
  17.     }  
  18.   
  19.     $_SESSION['id'] = $result['id']; 
  20.     $_SESSION['username'] = $result['username']; 
  21.     $_SESSION['oauth_uid'] = $result['oauth_uid']; 
  22.     $_SESSION['oauth_provider'] = $result['oauth_provider']; 
  23.     $_SESSION['oauth_token'] = $result['oauth_token']; 
  24.     $_SESSION['oauth_secret'] = $result['oauth_secret']; 
  25.  
  26.     header('Location: twitter_update.php');  
  27. }  

Note that these queries are not validated; if you leave them as they are, you are leaving your database vulnerable. Finally, below the database connection, we should set a check to verify that the user is logged in.

  1. if(!empty($_SESSION['username'])){  
  2.     // User is logged in, redirect  
  3.     header('Location: twitter_update.php');  
  4. }  

You can now greet the user by his or her username.

  1. <h2>Hello <?=(!empty($_SESSION['username']) ? '@' . $_SESSION['username'] : 'Guest'); ?></h2>  

Let’s get to the fun side: updating, following and reading.


Step 3: Reading Statuses

There are over twenty categories of resources available: timeline, tweets, users, trends, lists, direct messages, etc. Each one has a bunch of methods, you can check them all in the official documentation. We’ll get to the basics, as most of these features are accessed in a similar way.

Just like the other two scripts, we’ll need to create the TwitterOAuth instance, including the variables in the session.

  1. if(!empty($_SESSION['username'])){  
  2.     $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY''YOUR_CONSUMER_SECRET'$_SESSION['oauth_token'], $_SESSION['oauth_secret']);  
  3. }  

We’ll begin with the user’s timeline. The reference tells us that the path is statuses/home_timeline; ignore the version and format, the library will take care of it.

  1. $home_timeline = $twitteroauth->get('statuses/home_timeline');  
  2. print_r($home_timeline);  

That will get you the timeline. You can fetch each item with a foreach loop. However, the reference specifies some optional parameters like count, which limits how many tweets will be fetched. In fact, get‘s second parameter is an array of every option needed, so if you want to fetch the latest forty tweets, here’s the code:

  1. $home_timeline = $twitteroauth->get('statuses/home_timeline'array('count' => 40));  

Also, you can see somebody else’s timeline, as long as it’s not protected. statuses/user_timelinerequires either a user’s id or screen name. If you want to check @nettuts timeline, you’ll have to use the following snippet:

  1. $nettuts_timeline = $twitteroauth->get('statuses/user_timeline'array('screen_name' => 'nettuts'));  

As you can see, after authenticating, reading timelines is a breeze.


Step 4: Friendships

With friendships, you can check if a user follows another one, as well as follow or unfollow other users. This snippet will check if you are following me and and will create the follow if not.

But first, check the friendships/exists and friendships/create reference. Notice something?friendships/create method is POST. Fortunately, the library includes a post() function, which works just as the get() function; the main difference is that get() is for reading and post() is for creating, deleting or updating.

Anyways, friendships/exists requires two parameters: user_a and user_b, and friendships/createrequires just one, either screen_name or user_id.

  1. $follows_faelazo = $twitteroauth->get('friendships/exists'array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo'));  
  2. if(!$follows_faelazo){  
  3.     echo 'You are NOT following @faelazo!';  
  4.     $twitteroauth->post('friendships/create'array('screen_name' => 'faelazo'));  
  5. }  

You can unfollow an user with basically the same code that creates a follow, just replace create withdestroy:

  1. $follows_faelazo = $twitteroauth->get('friendships/exists'array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo'));  
  2. if($follows_faelazo){  
  3.     echo 'You are following @faelazo! Proceed to unfollow...';  
  4.     $twitteroauth->post('friendships/destroy'array('screen_name' => 'faelazo'));  
  5. }  

Step 5: Posting Updates

This is probably the most interesting section, since it’s Twitter’s core: posting an update, as you might have imagined, is pretty straightforward. The path is statuses/update, the method is POST (since we are not reading), and the one required argument is status.

  1. $twitteroauth->post('statuses/update'array('status' => 'Hello Nettuts+'));  

Now go to your Twitter profile page and you’ll see your tweet.

Let’s retweet @Nettuts’ update announcing the HTML 5 Competition; the status id is 19706871538 and the reference tells us that the path is statuses/retweet/:id, where the :id part is the status id we will be retweeting. The method is POST and it doesn’t require additional parameters.

  1. $twitteroauth->post('statuses/retweet/19706871538');  

To delete a tweet, you’ll have to pass the status id you’ll be destroying in the first parameter, just like retweeting. If the tweet’s id is 123456789, the code to destroy will be.

  1. $twitteroauth->post('statuses/destroy/123456789');  

Of course, this code can only delete tweets made by the authenticated user.


Conclusions

Twitter’s API is quite easy to understand; it’s far more documented than even Facebook’s (even though Facebook offers an in-house library). Unfortunately, the authentication is not as smooth as we might hope, depending on session data.

One thing worth noticing is that, once a Twitter user has been authorized (assuming the app has read and write permissions), you have plenty of control over this account. If you change something on behalf of the user without his permission, you’ll create trouble. Use it with caution!

The API changes coming to Twitter will deny basic authentication; Twitter is focusing on ceasing the countless scams that trick users into giving up their login credentials. OAuth is the solution; and, if you’ve worked through the Facebook Connect tutorial, you can now provide your website or app users with a quick login without credentials, using your choice of the two most used social networks. How cool is that?


저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

트위터 OAuth Sign in 튜토리얼  (0) 2013.07.22
트위터 oauth with php  (0) 2013.07.22
php 파일 include  (0) 2013.01.11
php 파일업로드 크기 제한 설정 php.ini (nginx)  (0) 2013.01.05
php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 파일이 여러개고.. db접속문과같이 여러번 중복되는 코드를 줄이기위해 include를 사용

<?     include "db.php"; ?>


db.php에는 이런코드가

<? $db = mysql_connect("localhost","root","password"); mysql_select_db("database",$db); mysql_query("set session character_set_connection=utf8;"); mysql_query("set session character_set_results=utf8;"); mysql_query("set session character_set_client=utf8;"); ?>


이런식으로 사용
저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

트위터 OAuth Sign in 튜토리얼  (0) 2013.07.22
트위터 oauth with php  (0) 2013.07.22
php 파일 include  (0) 2013.01.11
php 파일업로드 크기 제한 설정 php.ini (nginx)  (0) 2013.01.05
php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php로 게시판 구현하다, 파일업로드 제한(기본설정 2MB)이 있다는걸 알게되었다....몰랐던 사실

$cd /etc/php5/fpm/ $sudo vi php.ini

이 부분을 수정하면 된다
upload_max_filesize = 2M
↓
upload_max_filesize = 10M
변경 후 저장후에 nginx restart
$sudo /etc/init.d/nginx restart
Restart 해도 안될경우엔 서버 Reboot을 한번 해준다.
$sudo reboot

the system is going down for reboot now

phpinfo() 로 확인해보면 변경 완료
저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

트위터 oauth with php  (0) 2013.07.22
php 파일 include  (0) 2013.01.11
php 파일업로드 크기 제한 설정 php.ini (nginx)  (0) 2013.01.05
php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31

<head>

 이부분에 아래 코드를 추가한다.

</head>


<meta http-equiv="Content-Type" content="text/html" charset="utf-8">


그 후 저장시 utf-8로 저장하기


저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

php 파일 include  (0) 2013.01.11
php 파일업로드 크기 제한 설정 php.ini (nginx)  (0) 2013.01.05
php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31
리눅스 아파치 한글깨질때  (0) 2012.07.27

For/while

/* while 문 예제 */


   $i=0;
   while ($i < 5) {
      echo $i;
      $i = $i + 1;
   }
   
   echo "<br />";
   
   $i=5;
   while( $i > 0 ) {
      echo  $i;
      $i = $i - 1;
   }

 

 

/* for 문 예제 */
   for ($i=0 ; $i<5;$i++){
     echo $i;
   }
   
   echo "<br />";
   
   for ($i=5 ; $i>0;$i--){
     echo  $i;
   }



문자열 자르기


split() 함수. ]

[ ex. ]

 
     $datetime = "2010/09/13 23:45:46" ;
     list($year, $month, $day, $hour, $minute, $second) = split("[/ :]", $datetime);
     echo "$year 년 $month 월 $day 일 $hour 시 $minute 분 $second 초" ;


내가 적용한 코드

  	list($tag1, $tag2, $tag3, $tag4, $tag5) = split("[/ : ; ,]", $row[tags]) ; 
  	$atags = array($tag1,$tag2, $tag3, $tag4, $tag5 );  	
	for($i=0; $i<5 ; $i++){
		echo"	
				
			$atags[$i]
		";
	}
  	
  



저작자 표시 비영리 변경 금지
신고


time();


시간을 잡아주는 함수입니다. 이 함수가 실행된 바로 그

순간의 시간을 잡아내는거죠. 그런데 이 시간이 우리가

생각하는 2000.6.15.2.57.23 식이 아니라는거죠.

어떤 규칙인지는 저도 모릅니다. 다만 확실한건 11자리의

숫자라는거죠.


date();


time() 함수로 나온 시간을 date 함수로 분리해줍니다.

년도, 월, 일, 시간, 분, 초까지 아무 세밀하게 나오죠.


$nowtime = time();

$tt = date("Y년 m월 d일,h시", $nowtime);


이라고 하시면 2000년 6월 15일,3시 라고 $tt 에

저장될 겁니다. 이런 date 의 형태는 매우 다양합니다.


a : am, pm 형식으로

A : AM, PM 형식으로

d : 날짜

D : 요일 (Mon, Fri, 이런식)

F : 월(달) 이름으로 (January, November 이런식)

h : 12시간 타입의 시간으로. 15시는 3시로 출력 같은.

H : 24시간 타입의 시간으로. 오후 3시는 15시로.

i : 분

m : 숫자형 월 출력. (1 ~ 12)

M : Jan, Nov 형식으로 월 출력

s : 초

저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31
리눅스 아파치 한글깨질때  (0) 2012.07.27
mysql 접속방법,아파치 실행, 아파치폴더 권한  (0) 2012.07.27
우분투 mysql 암호 재설정  (0) 2012.07.27

1. 해당 html 페이지 <head>...</head> 사이에 아래 문장을 추가 해 줍니다.
 인코딩을 한글로 하겠다는 뜻 입니다.

<meta http-equiv="Content-Type" content="text/html; charset=euc-kr" >


2. 리눅스 httpd.conf 파일을 수정 해 줍니다.
보통 httpd.conf 파일은 아파치 설치해 놓은 곳에 xxx/apache/conf/httpd.conf 위치에 있죠~ㅎ
못 찾으셨다면 

# find / -name httpd.conf -print


명령어로 찾아보셈~

AddDefaultCharset UTF-8

  이렇게 된 것을

AddDefaultCharset off

로 바꿔줍니다.

인코딩을 따로 지정하지 않고 
모두 사용하겠다는 뜻 입니다. 
강력한 기능입니다~^^

그리고 마지막으로

# service httpd restart
또는
$ sudo /etc/init.d/apache2 restart
로 아파치 웹서버를 재시작 해 줍니다.


출처 : http://byeonely.tistory.com/23

저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31
리눅스 아파치 한글깨질때  (0) 2012.07.27
mysql 접속방법,아파치 실행, 아파치폴더 권한  (0) 2012.07.27
우분투 mysql 암호 재설정  (0) 2012.07.27



$ mysql -u root -p 엔터

비번 입력하면 접속됨


아파치 웹서서 재실행

$ sudo /etc/init.d/apache2 restart


Mysql서버 테스트

$ sudo netstat -tap|grep mysql


폴더권한

$su 엔터

비밀번호입력 

또는 

sudo so


하고, #chmod 777 /var/www 하거나

아니면,

$sudo chmod 7 /var/www  -R (하위폴더까지 모두)


저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31
리눅스 아파치 한글깨질때  (0) 2012.07.27
mysql 접속방법,아파치 실행, 아파치폴더 권한  (0) 2012.07.27
우분투 mysql 암호 재설정  (0) 2012.07.27



$ sudo dpkg-reconfigure mysql-server-5.5(버전)


저작자 표시 비영리 변경 금지
신고

'공부 > Php' 카테고리의 다른 글

php 한글깨짐현상  (0) 2012.08.03
for,while문. 문자열자르기, list와 배열  (0) 2012.08.02
php 문법 시간  (0) 2012.07.31
리눅스 아파치 한글깨질때  (0) 2012.07.27
mysql 접속방법,아파치 실행, 아파치폴더 권한  (0) 2012.07.27
우분투 mysql 암호 재설정  (0) 2012.07.27

+ Recent posts