user1481850
user1481850

Reputation: 248

optimizing php code for less php processing

I am having some problem with my apache server when handling big amount of traffic. after some optimizations I did. I still have the same problem. I check my log file and it turned out that I have a lot of php processing. The following code is getting processed about 800 times a minute (when I have high traffic) and casing my server to crash.

1) is there any parts of the code that I need to rewrite that would make it take less php processing ? 2) is it a good idea to have all of this code before the html starts ?

<?php
$ip = $_SERVER['REMOTE_ADDR'];
mysql_connect('', '', '');
mysql_select_db('');

if(empty($_GET['i']) == false){
    $get_image = mysql_real_escape_string($_GET['i']);
    $check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");
    if(mysql_num_rows($check_if_image) == 1){
        $result = mysql_fetch_assoc($check_if_image);
        $image_id = $result['id'];
        $image_name = $result['image_name'];
        $image_type = $result['image_type'];
        $image_caption = stripslashes($result['image_caption']);
        $image_voteup = $result['image_voteup'];
        $image_votedown = $result['image_votedown'];
        //$image_date = $result['image_date'];
        $image_views = $result['image_views'];
        $fb_username = $result['fb_username'];
        $fb_userid = $result['fb_userid'];

        //next image
        $next_image_id = $image_id + 1;
        $check_next_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$next_image_id'");
        if(mysql_num_rows($check_next_image) == 1){
            $next_image_result = mysql_fetch_assoc($check_next_image);
            $next_image_name = $next_image_result['image_name'];
            }
        // pre image
        $pre_image_id = $image_id - 1;
        $check_pre_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$pre_image_id'");
        if(mysql_num_rows($check_pre_image) == 1){
            $pre_image_result = mysql_fetch_assoc($check_pre_image);
            $pre_image_name = $pre_image_result['image_name'];
            }
        //shares, comments, and likes
        $fb_page_url = "http://www.xxx.com/images.php?i=".$get_image;
        $fb_url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($fb_page_url);
        $fb_xml = file_get_contents($fb_url);
        $fb_xml = simplexml_load_string($fb_xml);
        $fb_shares = $fb_xml->link_stat->share_count;
        $fb_likes = $fb_xml->link_stat->like_count;
        $fb_likes_and_shares = $fb_likes + $fb_shares;
        $fb_comments = $fb_xml->link_stat->commentsbox_count; 


        //facebook
        require_once('scripts/facebook.php');
        $config = array('appId' => '','secret' => '');
        $params = array('scope'=>'user_likes,publish_actions,email,offline_access,user_birthday');
        $facebook = new Facebook($config);
        $user = $facebook->getUser();

        if($user){
            try{
            $user_profile = $facebook->api('/me','GET');
            $user_id = $user_profile['username'];
            $expire_time = time() + 30758400;


            //insert cookie id
            if (!isset($_COOKIE['id'])){
                $cookie_id = $user_profile['username'];
                setcookie("id", $cookie_id, $expire_time, '/');
                }
            //insert cookie name
            if (!isset($_COOKIE['name'])){
                $user_name = $user_profile['first_name'];
                setcookie("name", $user_name, $expire_time, '/');
                }

            //check if the user like the fan page
            $isFan = $facebook->api(array(
            "method"    => "pages.isFan",
            "page_id"   => ''
            ));


            }catch(FacebookApiException $e) {
                        error_log($e->getType());
                        error_log($e->getMessage());
      } 
            }else{//if no user
                if(isset($_COOKIE['name'])){
                $user_name = $user_profile['first_name'];
                setcookie("name", $user_name, time() - 30758400, '/');
                    }
                }

            //increase views
            if($facebook->getUser()){
            mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
            mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
            }


}else{//image was not found in the database.
            header('Location: index.php');
            }
    }else{//redirect if get is empty
        header('Location: index.php');
        }

?>

Upvotes: 1

Views: 168

Answers (2)

kalpaitch
kalpaitch

Reputation: 5271

I would say the key factor is your call to the Facebook API, such things are always expensive and easily cacheable, put that code in a separate page/include and cache it as you like.

Also as a side note, you should consider reducing the number of db queries and you may wish to update your db driver... as invariably everyone points out @Madara Uchiha

Upvotes: 3

Seth
Seth

Reputation: 1373

I see a few items right off the bat.

First query:

 $check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");

If you only need one result back, put a 'LIMIT 1' at then end (unless this field has a UNIQUE index, in which case this shouldn't matter). Also make sure this field is indexed and preferably a VARCHAR field instead of TEXT or BLOB.

Next, you are running 2 queries to get the previous and next images. I would combine this into 1 query like this:

SELECT `image_name` FROM images_new WHERE id IN ('$next_image_id', '$pre_image_id')

Also, you can apply the first optimization I mentioned to these 2 queries:

if($facebook->getUser()){
        mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
        mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
}

Lastly, going through the Facebook API is going to add load time that you cannot do much about. Hopefully this gets you started down the right path.

Upvotes: 2

Related Questions