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

Tuesday, July 17, 2012

Cannot modify header information - headers already sent.


When ever we are dealing with header function the common warnning we get is "Cannot modify header information - headers already sent". 

Lets see php.net mannual -"header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called."  So as it clearly indicate that if our code is generating a space or empty lines also result into this warnning. 

Now the solution: A solution for this is dont allow any output to print any thing on browser till all headers are executed. So we are adding ob_start() in the begnning of page & ob_flush() at the end of page. then what ever is the output will be there in the output buffer, So this time we can use header function without any worry. And your code will somthing like:

<?php
ob_start();
//Your code
header('Location: example.php');
exit()
//your code
ob_flush();
?>
In case we are dealing with session, then session should start after ob_start() otherwise again it will through same warnning.

Saturday, February 11, 2012

How to Authenticate Users With Facebook Connect

How to Authenticate Users With Facebook ConnectTutorial Details


  • Topic: Facebook Connect, PHP

  • Difficulty: Moderate

  • Estimated Completion Time: 45 Minutes


 

 

 

Lately, there’s been quite a fuzz about lazy registration. It turns out that the less the user has to think, the higher the conversion rates are! What a thought! If everybody seems to have a Facebook profile, why not add a one-click user registration? I’ll show you how to do that today.

 




Step 1. The Setup


MySQL Table


Let’s begin by creating a database table.



  1. CREATE TABLE `users` (

  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  3.     `oauth_provider` varchar(10),

  4.     `oauth_uid` text,

  5.     `username` text,

  6.     PRIMARY KEY (`id`)

  7. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;



Quite simple: we will be setting up a table for user information with id, username, first and last name, the URL to the user’s picture, and registered date. Also, we’re adding both an oauth_provider andoauth_uid fields, to distinguish between different third party open authentication protocols and their identifiers. For example, let’s say that, next week, you decide that it’s a good idea to also let Twitter users in. Easy; you just set another value to the oauthprovider, and avoid duplicating oauthuid values.

The Facebook App


Let’s begin by creating a new application. Give it a name and agree to the terms and conditions. Next, grab both the API Key and Secret in the basic tab as shown below.

On the canvas tab, set both the Canvas URL and Post-Authorize Redirect URL to your localhost and path that the script will process — something like http://localhost.com/login_facebook.php?. Note the question mark at the end and the domain; both are required by Facebook. Simply set your hosts file to a valid domain name.

On the connect tab, set the Connect URL to the same value and set localhost.com (or the one you are using) as the Base Domain.

Now save, download the client library, and unzip facebook.php in the srcdir to a new directory created in the root.




Step 2. The Callback


The authentication flow has three steps:

  1. The local script generates a URL asking the user for permission

  2. Facebook returns to the Canvas URL specified with a GET parameter

  3. The GET parameter authenticates the session


Let’s make a quick test before registering and login.



  1. # We require the library

  2. require("facebook.php");


  3. # Creating the facebook object

  4. $facebook = new Facebook(array(

  5.     'appId'  => 'YOUR_APP_ID',

  6.     'secret' => 'YOUR_APP_SECRET',

  7.     'cookie' => true

  8. ));


  9. # Let's see if we have an active session

  10. $session = $facebook->getSession();


  11. if(!empty($session)) {

  12.     # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))

  13.     try{

  14.         $uid = $facebook->getUser();

  15.         $user = $facebook->api('/me');

  16.     } catch (Exception $e){}


  17.     if(!empty($user)){

  18.         # User info ok? Let's print it (Here we will be adding the login and registering routines)

  19.         print_r($user);

  20.     } else {

  21.         # For testing purposes, if there was an error, let's kill the script

  22.         die("There was an error.");

  23.     }

  24. } else {

  25.     # There's no active session, let's generate one

  26.     $login_url = $facebook->getLoginUrl();

  27.     header("Location: ".$login_url);

  28. }



Now, go to http://localhost.com/login_facebook.php, and let’s see what happens. If you are redirected to Facebook and requested for permission, we are on the right track.

However, there might be two issues. The first one: if you’re redirected to Facebook, but it shows an error, there might be a missing value in the configuration. Go back to your application settings and check both the Connect and Canvas tabs and make sure the fields are ok as described above.

There might be another issue, where you see an error, like “Uncaught CurlException: 60: SSL certificate problem, verify that the CA cert is OK.” This happens because of the CURL settings. You’ll have to openfacebook.php, find the makeRequest() method, and, inside the function, find this line:



  1. $opts = self::$CURL_OPTS;



Immediately following it, add:



  1. $opts[CURLOPT_SSL_VERIFYPEER] = false;



I hate hacking libraries, but I haven’t found another way. Well, let’s continue with user registration. I’ve also added a try/catch statement, because, if there’s an old session keys in the GET params in the URL, the script will die with a horrible error.




Step 3. Registration and Authentication


We’ll next be working with MySQL. Please note that I will not implement a data sanitizer, since I want to keep the code as short and on task as possible. Please keep this in mind: always sanitize your data.

First, let’s connect to the database.



  1. mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD');

  2. mysql_select_db('YOUR_DATABASE');



Now, let’s work on the $session conditional, in case we have a session.



  1. # We have an active session; let's check if we've already registered the user

  2. $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);

  3. $result = mysql_fetch_array($query);


  4. # If not, let's add it to the database

  5. if(empty($result)){

  6.     $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");

  7.     $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());

  8.     $result = mysql_fetch_array($query);

  9. }



Note that I’m querying the database, looking for facebook as a oauth_provider; it’s generally a good idea, if you want to accept other OAuth providers (as twitter, Google Accounts, Open ID, etc.) and aoauth_uid, since it’s the identifier the provider gives to its user accounts.

The oauth_provider field could potentially lead to bad performance if we leave it as a text field type. As such, the best option is setting it to an ENUM type.

We have now a $result var with the values queried from the database. Let’s next add some sessions. Add this line at the beginning of your script.


  1. session_start();



After the empty($result) conditional, append the following:



  1. if(!empty($user)){

  2.     # ...


  3.     if(empty($result)){

  4.         # ...

  5.     }


  6.     # let's set session values

  7.     $_SESSION['id'] = $result['id'];

  8.     $_SESSION['oauth_uid'] = $result['oauth_uid'];

  9.     $_SESSION['oauth_provider'] = $result['oauth_provider'];

  10.     $_SESSION['username'] = $result['username'];

  11. }



As it makes little sense to authenticate a user who is already logged in, just below the session_start()line, add:




  1. if(!empty($_SESSION)){

  2.     header("Location: home.php");

  3. }



And in the scripts which require authentication, just add:



  1. session_start();

  2. if(!empty($_SESSION)){

  3.     header("Location: login_facebook.php");

  4. }



And if you want to display the username, access it as an array.



  1. echo 'Welcome ' . $_SESSION['username'];

  2. # or..

  3. echo 'Welcome ' . !empty($_SESSION) ? $_SESSION['username'] : 'guest';







Step 4. Additional Methods


Facebook has a ton of connect features, but here are four that I’ve found to be the most useful.

Legacy Methods


I might be missing something, but the FQL seems more flexible and easy than the Graph API. Fortunately, Facebook still lets developers use it, altough with the new library, it has changed a bit.

If you want the user id, first name, last name, squared thumbnail for the user picture, the biggest user picture available, and his or her gender, you can use the users.getInfo method.



  1. $uid = $facebook->getUser();

  2. $api_call = array(

  3.     'method' => 'users.getinfo',

  4.     'uids' => $uid,

  5.     'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex'

  6. );

  7. $users_getinfo = $facebook->api($api_call);



You can check the full list of fields available for Users.getInfo.


It is possible to achieve the same result, using FQL.



  1. $uid = $facebook->getUser();

  2. $fql_query  =   array(

  3.     'method' => 'fql.query',

  4.     'query' => 'SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = ' . $uid

  5. );

  6. $fql_info = $facebook->api($fql_query);



Here’s the list of tables which can be accessed with FQL, as well as the fields available for the table users.

Extended Permissions


Facebook provides applications with some interaction with the user’s data – just as long as it’s authorized. With the old API, the authorization for additional permissions was exclusively available for the Javascript SDK (altough I’m not quite sure). With the new API, we can easily redirect the user to an authorization dialog in Facebook, and return to our site after the access is either granted or denied.

In the following example, we will be redirecting a user to authorize posts status updates, photos, videos and notes, the user’s real email address, birthday and access to photos and videos.


  1. $uid = $facebook->getUser();

  2. # req_perms is a comma separated list of the permissions needed

  3. $url = $facebook->getLoginUrl(array(

  4. 'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'

  5. ));

  6. header("Location: {$url} ");



Here’s a full list of permissions. Note that you can specify both the url to direct to if the user accepts and the url to be redirected to if the user denies. The key for these array elements are next and cancel_url, respectively. Here’s a quick example:



  1. $url = $facebook->getLoginUrl(array(

  2.     'req_perms' => 'email',

  3.     'next' => 'http://localhost.com/thanks.php',

  4.     'cancel_url' => 'http://localhost.com/sorry.php'

  5. ));



If not specified, the default is the requesting script’s location.

Checking for Extended Permissions


Since the user can easily revoke permissions, the application should always check if a given permission is granted before using it, specially if it’s about publishing something. We will have to use the legacy API, as it seems it’s not fully implemented with the new one yet.



  1. $uid = $facebook->getUser();


  2. # users.hasAppPermission

  3. $api_call = array(

  4.     'method' => 'users.hasAppPermission',

  5.     'uid' => $uid,

  6.     'ext_perm' => 'publish_stream'

  7. );

  8. $users_hasapppermission = $facebook->api($api_call);

  9. print_r($users_hasapppermission);



The ext_perm will only support the old list of available permissions.

Publishing to the Wall


Let’s post something to the wall after verifying the user has the publish_stream permission.



  1. # let's check if the user has granted access to posting in the wall

  2. $api_call = array(

  3.     'method' => 'users.hasAppPermission',

  4.     'uid' => $uid,

  5.     'ext_perm' => 'publish_stream'

  6. );

  7. $can_post = $facebook->api($api_call);

  8. if($can_post){

  9.     # post it!

  10.     $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));

  11.     echo 'Posted!';

  12. } else {

  13.     die('Permissions required!');

  14. }



Essentially, we are making an API call to /<user_id>/feed, using the POST method (second argument) and an array as a third argument for the data to be sent. In this case, this third argument supports message,link, picture, caption, name and description. Here’s the code:



  1. $facebook->api('/'.$uid.'/feed', 'post', array(

  2.     'message' => 'The message',

  3.     'name' => 'The name',

  4.     'description' => 'The description',

  5.     'caption' => 'The caption',

  6.     'picture' => 'http://i.imgur.com/yx3q2.png',

  7.     'link' => 'http://net.tutsplus.com/'

  8. ));



Here’s how it is posted.

 

Some Additional Information you Should Know:


The user can easily revoke permissions with two clicks in his or her wall. You should heavily test what might happen if a user revoked one or more permissions that are vital for the proper functioning of your website, or even if the application is fully removed. This is important.





5. Conclusion


While Facebook’s authentication capabilities are indeed useful, since so many people are on Facebook these days, using it as the only method of authentication in a site is not recommended. What about those who don’t have Facebook accounts? Are they not allowed to access your application? Thanks for reading!

Friday, December 30, 2011

Creating Dynamic PDF files using PHP

Here, we are going to study on converting HTML 2 PDF using PHP. Here we are going to use free open source PHP scripts to accomplish this file conversion. So we will be using FPDF for this, as all Libraries are already written for this And well Optimize also in terms of PDF generation time & size.

FPDF: The PDF Generator


The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.



<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
$pdf=new FPDF('P','mm','A4');

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).


Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().


To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:



$pdf->SetFont('Arial','B',16);

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:



$pdf->Cell(40,10,'Hello World !',1);

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.There are lot more functions in FPDF and we cannot cover all those in this article.
To learn FPDF, please browse http://www.fpdf.org.

Wednesday, October 19, 2011

serialize Data in PHP Drupal

If we have an array
$ary=array();
$ary['alt']="Cordy icon";
$ary['title']="Cordy";

then its serialize output "serialize($ary)" will be something like this:
a:2:{s:3:"alt";s:10:"Cordy icon";s:5:"title";s:5:"Cordy";}

on unserialize(a:2:{s:3:"alt";s:10:"Cordy icon";s:5:"title";s:5:"Cordy";})
it will give Array
(
[alt] => Cordy icon
[title] => Cordy
)

In drupal if we are using cck field then we are getting this serialize data.
So to insert query will be somthing like this
db_query("INSERT INTO {my_table} (name, description, array1) VALUES ('something', 'something else', '%s')",serialize($ary));

or
db_query("update {my_table} set array1='%s' where name='something'",serialize($ary));

Note: Remember to keep tablename inside {} then it will work in drupal.

coz Drupal uses {} arround the tables names, to be able to do some manipulations on those names -- like prefix them, if you have configured it to do so. So, you must not use {} in your query -- except arround tables names,

Saturday, October 15, 2011

Configuring a PHP Cron Job on Linux server

IF we are providing Direct url Then we need to Call CURL to execute that url as:
curl http://localhost/cronjob.php

What ever arguments are there needed to execute this url can be provided, Its as simple as calling any API.

Installing Apache2 With PHP5 And MySQL Support On OpenSUSE

Just follow the steps mention below:

  •  Installing MySQL 5


First we install MySQL 5 like this:
yast2 -i mysql mysql-client

Then we create the system startup links for MySQL (so that MySQL starts automatically whenever
the system boots) and start the MySQL server:
chkconfig --add mysql
/etc/init.d/mysql start

To secure the MySQL installation, run:
mysql_secure_installation
Now you will be asked several questions:

server1:~ # mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none): <-- ENTER
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.
Set root password? [Y/n] <-- Y
New password: <-- fill in your desired MySQL root password
Re-enter new password: <-- confirm that password
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] <-- Y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] <-- Y
... Success!
By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] <-- Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] <-- Y
... Success!
Cleaning up...

All done! If you've completed all of the above steps, your MySQL
installation should now be secure.
Thanks for using MySQL!
server1:~ #
Now your MySQL setup should be secured.


  • Installing Apache2


Apache2 is available as an OpenSUSE package, therefore we can install it like this:
yast2 -i apache2

Now configure your system to start Apache at boot time...
chkconfig --add apache2

... and start Apache:
/etc/init.d/apache2 start

Now direct your browser to http://192.168.0.100, and you should see the Apache2 placeholder page (don't worry about the 403 error, this happens because there's no index file (e.g. index.html) in the document root directory):



Apache's default document root is /srv/www/htdocs/ on OpenSUSE, and the configuration file is /etc/apache2/httpd.conf. Additional configurations are stored in the /etc/apache2/conf.d/ directory.

  • Installing PHP5


We can install PHP5 and the Apache PHP5 module as follows:
yast2 -i apache2-mod_php5

We must restart Apache afterwards:
/etc/init.d/apache2 restart

 

  •  Testing PHP5 / Getting Details About Your PHP5 Installation


The document root of the default web site is /srv/www/htdocs/. We will now create a small PHP file (info.php) in that directory and call it in a browser. The file will display lots of useful details about our PHP installation, such as the installed PHP version.
vi /srv/www/htdocs/info.php
<?php
phpinfo();
?>

Now we call that file in a browser (e.g. http://192.168.0.100/info.php):


As you see, PHP5 is working, and it's working through the Apache 2.0 Handler, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5. MySQL is not listed there which means we don't have MySQL support in PHP5 yet.

  •  Getting MySQL Support In PHP5


To get MySQL support in PHP, we can install the php5-mysql package. It's a good idea to install some other PHP5 modules as well as you might need them for your applications:

 
yast2 -i php5-mysql php5-bcmath php5-bz2 php5-calendar php5-ctype php5-curl php5-dom php5-ftp php5-gd php5-gettext php5-gmp php5-iconv php5-imap php5-ldap php5-mbstring php5-mcrypt php5-odbc php5-openssl php5-pcntl php5-pgsql php5-posix php5-shmop php5-snmp php5-soap php5-sockets php5-sqlite php5-sysvsem php5-tokenizer php5-wddx php5-xmlrpc php5-xsl php5-zlib php5-exif php5-fastcgi php5-pear php5-sysvmsg php5-sysvshm

Now restart Apache2:

 
/etc/init.d/apache2 restart

 

Now reload http://192.168.0.100/info.php in your browser and scroll down to the modules section again. You should now find lots of new modules there, including the MySQL module:



  • phpMyAdmin


phpMyAdmin is a web interface through which you can manage your MySQL databases.
phpMyAdmin can be installed as follows:
cd /srv/www/htdocs
wget http://space.dl.sourceforge.net/project/phpmyadmin/phpMyAdmin/3.4.5/phpMyAdmin-3.4.5-all-languages.tar.gz
tar xvfz phpMyAdmin-3.4.5-all-languages.tar.gz
mv phpMyAdmin-3.4.5-all-languages phpmyadmin

Afterwards, you can access phpMyAdmin under http://192.168.0.100/phpmyadmin/: