max_execution_time vs default_socket_timeout

The default setting in php.ini,

max_execution_time = 30
default_socket_timeout = 60

For example, your script need to do socket based streams, which takes 45 seconds, will script timeout because the max_execution_time is 30 seconds?

The answer is NO, because max_execution_time is not affected by system calls or stream operation.
Another important note is that default_socket_timeout is counting before socket responds, as long as it gets response, it will wait forever.

PHP Memory Error

Got PHP fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in /usr/share/pear/Zend/Search/Lucene/Field.php on line 98

Which is not necessary happened to Lucene Script, and it could happen to any script requiring a ton of memory to run, for example parsing a large of XML file.

If you see this error, first check your php.ini file. Looking for “memory_limit”, Mine was set to 128M, which is pretty high already. But that script now asks for more (134M+). So increasing memory_limit should fix the problem. You can also increase memory limit by ini_set(‘memory_limit’, ‘200M’);

Note that you should also check your script to see if you can make it more efficient.

Step by Step to Post to Facebook Wall using PHP

Update on 12/21/2012: this approach is no longer working.

Set up new App

Go at http://www.facebook.com/developers/, which requires some verification, either using your cell phone or your credit card. And then follow the instruction, you should be able to get FB_APIKEY and FB_SECRET keys.

Download Facebook API Library

The API library (facebox-platform) used in this tutorial is kinda old. Looks like Facebook has removed it. You can get it at Github.

Get Permission

Before your App can access to any Facebook account, you need permission.

  • First you need to login the target Facebook account.
  • Copy the following url change api_key to yours, and run it in your browser to get access permission to access target Facebook account.
  • http://www.facebook.com/login.php?api_key=YOUR-API-KEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access
  • Copy the following url change api_key to yours and fan page id to the related fan page id to get access permission.
  • http://www.facebook.com/connect/prompt_permissions.php?api_key=YOUR-API-KEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=page&ext_perm=publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=FAN-PAGE-ID

Get FB_SESSION

One FB_SESSION is tied to an unique Facebook account. To get FB_SESSION,

  • you need to login the target Facebook account
  • and then copy the following url, change the api_key to yours and paste and run it in your browser. and then click “Generate” to get one-time code (something, like 4PI64O)
  • https://login.facebook.com/code_gen.php?api_key=YOUR-API-KEY&v=1.0
  • And then run the following PHP code to get FB_SESSION

Sample Code

OK, you have done the preparations, and you can write the code to post something to the target Facebook Wall and Facebook Fan Page Wall now. The following is a sample code that you can start with.

<?php
define('FB_APIKEY', 'YOURAPI');
define('FB_SECRET', 'YOURSECRET');
define('FB_SESSION', YOURSESSION');
require_once('facebook-platform/php/facebook.php'); //YOUR LIB PATH
$att = array( "name" => "CaiApps",
   "href" => "http://www.caiapps.com",
   "media"=> array(
                          array("type"=>"image",
                                  "src"=>"http://www.caiapps.com/images/logo.png", 
                                   "href"=> "http://www.caiapps.com")
                   ),
   "description"=> "Hello from CaiApps.com"
);

$attachment = json_encode($att);
post2wall($attachment);

function post2wall($attach=null){
   try {
   $facebook = new Facebook(FB_APIKEY, FB_SECRET);
   $facebook->api_client->session_key = FB_SESSION;

   $message = 'some message'; 

   if( $facebook->api_client->stream_publish($message, $attach))
      echo "Added on FB Wall";

   $page_id = '155965577765104'; //Fan Page ID
   $action_links = null;

   if( $facebook->api_client->stream_publish(null, $attach,$action_links, null,$page_id))
      echo "Added on FB Wall on Fan Page";
   }
   catch(Exception $e) {
      echo $e ;
   }
}
?

Some Note

Facebook limits the number of posts you can make via your App. Not sure the exactly how many, they may be dynamically set. If you see the error of “Request Limit Reached”, then it means your App reach the limit. I have seen this problem and it took about 2 days (48 hours) to unlock. So remember to set the limit on your end.

Password protect a file

Using PHP’s $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’] to protect a file is pretty easy and straightforward.

Refer to PHP.NET

PHP_AUTH_USER
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
PHP_AUTH_PW
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.

First you can save a secret file in a non-public directory, for example, your web root directory is /home/user/adam/public_html/, then you can save the file at /home/user/adam/secret_file.txt.

Secondly, in the PHP script, which should be a public script under web root directory , for example, the file name is get_secret_file.php,

<?php

$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : "";
$pass = isset($_SERVER['PHP_AUTH_PW'])   ? $_SERVER['PHP_AUTH_PW']   : "";

if($_SERVER['PHP_AUTH_USER'] == 'user' && $_SERVER['PHP_AUTH_PW'] == 'P@ss'){
   header("Content-type: text/plain");
   echo file_get_contents("/home/user/secret_file.txt");
}
else{
   header('WWW-Authenticate: Basic realm="ssww.com"');
   header('HTTP/1.0 401 Unauthorized');
   echo 'Login Failed';
   exit;
}

?>

Finally, the file is protected. If someone try to access the file, from http://www.example.com/get_secret_file.php, he/she will be asked for user and password.

How to Access a secret file programmably by passing username and password? Here are two solutions.

1. Include username and password in the URL, which works the same way as fetch file from FTP site.

http://USERNAME:PASSWORD@www.example.com/get_secret_file.php

2. Using CURL

$url = "http://www.example.com/get_secret_file.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
$content = curl_exec($ch);
//You got content!
curl_close($ch);