0

I have the following problem:

I've made a social network where every user can share his profile on facebook. The user has a ranking on my social network and that ranking must appear in the title of the link shared on facebook. This ranking change basing on user activity: if the user posts anything his ranking grows.

Here comes the first problem: Facebook caches open graph data, so if i share my page for the first time and my ranking is 100, i will have 100 in the title shared on facebook. Then, if my ranking goes up to 200 because i've posted something and i share my page again, i will still see 100 on facebook, because data is cached.

Then i've made the following function:

function refresh(){
  $access_token="APPID|APPSECRET"; //replace with your app details
  $params = array("id"=>'MY URL', "scrape"=>"true","access_token"=>$access_token);
  $ch = curl_init("https://graph.facebook.com");
  curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_SSL_VERIFYHOST=>false,
    CURLOPT_SSL_VERIFYPEER=>false,
    CURLOPT_POST=>true,
    CURLOPT_POSTFIELDS=>$params
  ));
  $result = curl_exec($ch);
}

Which successfully refreshes the cache.

So, when the user adds a new post a script is called which does as follows:

1) add post to db;
2) refresh();
3) header('location: profile_page');

The problem is the following: refresh() takes long time..so the script to add new post goes from 0.2s (without refresh) to 4s (with refresh) which is annoying for users, because they have to wait long time after having posted and they think my website is slow. Is there a way, in PHP, to execute refresh() in a way that does not let the user wait? Something like:

1) add post to db;
2) run refresh(), but finish the script even if refresh has not finished yet.
3) header('location: profile_page');
Alberto Fontana
  • 928
  • 1
  • 14
  • 35

2 Answers2

0

You can do the refresh work in a separate script. From current script you call that script by opening a socket to it. Running the script using socket will return asynchronously and user will not have to wait.

check this to see how to execute a script asynchronously: Can PHP asynchronously use sockets?

Community
  • 1
  • 1
Haider
  • 938
  • 2
  • 11
  • 25
0

Unfortunatelly, PHP does not support multi threading. You can try this:

header('location: profile_page');
header('Connection: close');
header('Content-Length: 1');
echo 'a';
flush();

It does not run anything in a separate thread, but finishes the script output and sends it to browser immediatelly. (Maybe lines 2-4 will not be needed on your server, just experiment with that)

The other way is to open some other script with non-blocking fopen (http://cz2.php.net/manual/en/function.fopen.php , seems to be supported only on linux), but It is a bit dirty solution.

amik
  • 5,613
  • 3
  • 37
  • 62