Posts

Home PHP

Append Subtitle/Caption Image Using PHP and Hide It with CSS

Note: People say it isn’t actually a watermark, the image appended can be called a “Caption” or “Hidden Subtitle”. So in this post, when I say “watermark”, it refers to the ”Caption” or “Hidden Subtitle”.
Nowadays I see many websites with image contents. Funny images, interesting images, cosplay, art and many more kinds of images. Many people don’t want to hotlink or copy the image link and share it to any social networking site such as Facebook, instead they copy or download the image (using browser’s “Save image as” option) and upload it to their own account without linking it to the source or website where they found it.

One solution websites do is to append a watermark on their images. The don’t want this watermark to be shown on their website but they want it to appear when the user went to the actual image link or when this image was copied or downloaded.
An example website the does this is 9gag.com. When you see the image on their site, it does not have any watermark. But when you try to save the image, the watermark will appear, appended at the bottom part of the image, it is in white background.
Today we’re going to do a code the does something like that.

DOWNLOAD CODE LIVE DEMO

  • Append a watermark at the bottom part of the image using PHP
  • Hide it using CSS

First, we need to prepare:

  • Sample image – the image you want to put a watermark
  • Watermark image – the image that will be put as watermark on the sample image
    • As for the sample image, we’re going to use this image of my pets (yes, my pets):

      Append Subtitle/Caption Image Using PHP and Hide It with CSS

      For the watermark image:

      This will be appended on the main image

      This will be appended on the main image

      Some notes:

      • “sample.jpg” and “watermark.jpg” should be your variable
      • PHP GD library should be enabled on your server

      Our index.php, we are going to have the following code:

      <?php
      
          //set the header
          header( "Content-type: image/jpg" );
      
          //get image sizes first
          $image_size = getimagesize( "sample.jpg" );
          $watermark_size = getimagesize( "watermark.jpg" );
      
          $image_size_width = $image_size[0];
          $image_size_height = $image_size[1];
      
          $watermark_size_width = $watermark_size[0];
          $watermark_size_height = $watermark_size[1];
      
          //create images
          $main_img = imagecreatefromjpeg( "sample.jpg" );
          $watermark = imagecreatefromjpeg( "watermark.jpg" );
      
          //create canvas
          $canvas = imagecreatetruecolor(
      
              $image_size_width, //width of main image
              $image_size_height + $watermark_size_height //this is the new height, height of main image plus watermark image
          ) or die('Cannot Initialize new GD image stream.');
      
          
          //set white background of canvas
          $bg = imagecolorallocate( $canvas, 255, 255, 255 );
          imagefill ( $canvas, 0, 0, $bg );
      
      
          //paste main image to the canvas
          imagecopymerge(
              $canvas, 
              $main_img, 
              0, //main_img x coordinate ( distance from left side of main_img )
              0, //main_img y coordinate ( distance form top of main_img )
              0, //main_img x coordinate image ( distance from left side of main_img )
              0, //main_img y coordinate image ( distance from top side of main_img )
              $image_size_width, //main_img width
              $image_size_height, //main_img height
              100 //the opacity of main_img
      
          );
      
          //paste the watermark image to the canvas
          imagecopymerge(
              $canvas, 
              $watermark, 
              0, //watermark x coordinate ( distance from left side of main_img )
              $image_size_height, //watermark y coordinate ( distance form top of main_img )
              0, //watermark x coordinate image ( distance from left side of watermark )
              0, //watermark y coordinate image ( distance from top side of watermark ) 
              $watermark_size_width, //watermark width
              $watermark_size_height, //watermark height
              100 //the opacity of watermark
      
          );
      
          //show the new image
          imagejpeg( $canvas );
      
          //if you want to save it to your server directory, just add the second param
          //something like:
          //imagejpeg($canvas, 'your_directory/new_img.jpg');
      
          imagedestroy( $canvas );
          imagedestroy( $main_img );
          imagedestroy( $watermark );
      
      ?>
      

      new_img

      Now, we are going to the second part of this post. We are going to show the output image on a webpage, but the watermark is hidden using CSS.

      Our page.php should have the following code:

      <html>
      
          <head>
      
              <title></title>
      
          </head>
      
      <body>
      
          <div style='font-weight:bold; font-size:18px;'>The image below has a watermark, but it was hidden.</div>
          <div style='margin:5px 0;'>Try to go to the actual image by doing 'open image in new tab' or downloading it.</div>
      
      
          <div style='overflow:hidden;'>
      
              <!-- -30px here is the height of our watermark -->
              <img src='new_img.jpg' style='margin:0 0 -30px 0;' />
      
          </div>
      
      </body>
      </html>
      

      See the live demo for the output! :)

Past Month Traffic Details By Google Analytics

Hi guys! Earlier, I (accidentally) checked out our website’s Google Analytics account. I was surprised and happy about what I saw. 
The Stats
For the past month, we got almost 12 thousand unique visitors, more than 14 thousand visits and more than 22 thousand page views. For me these statistics are very encouraging. I realized that I can help other people by writing something about programming. I feel like today, I’m realizing my dream of being a teacher in the future.

Click to enlarge. This link could help us undertand these data.

The Sources

Most of the traffic we got are from search engines, so I thank Google, Bing, Yahoo Search and the like for bringing more people to our website. Second source of traffic are from referral links, so I thank those people who liked, tweeted, shared and linked our posts to Facebook, Twitter, Stackoverflow, DZone, Hacker News and other websites that are linked to our place. Third source of traffic is the direct traffic, thanks for bookmarking, subscribing and returning here guys! 
Click to enlarge.
The New Perspective
Since I’m encouraged and inspired by your positive feedbacks, I will blog more high quality contents (Hmm, maybe as often as every week?) that can be useful for different level of programmers and not just short code snippets or quick tips. I will still reply to your comments depending on my available time. Yes, I’m also aware of negative feedbacks on this site but I prefer to look at it in a positive way. For me, negative feedbacks are great opportunities to learn something. 
Regarding code snippets or quick tips or fast posts, I’d still love to blog about it. I believe they are helpful too. Little code blocks with a little story or experience. I’ll blog these things on a different website or sub domain, something like php.codeofaninja.com, jquery.codeofaninja.com or android.codeofaninja.com. I just want to put more high quality posts as much as possible on our main website codeofaninja.com 
Again, thanks guys! See you!
Home Facebook

Display Facebook Videos To Your Website Script

Update 2: Hi guys! The script on this page is not actively developed anymore, but we have the alternatives!

Learn how to display other Facebook page data using these scripts too!

Hi guys! After my post about displaying Facebook photos and events to website, some of you requested this post – how to display Facebook Fan Page Videos to your website or webpage.

This one is useful if you want your Facebook videos to be shown in your website in a synchronized way.

Once you uploaded a video in your fan page, it will be automatically shown to your website too.

The advantages and risks of this is almost the same with what I discussed in my first post related to this one.

fbvideos

DOWNLOAD CODE LIVE DEMO

On the demo, I just uploaded some random videos of mine, taken using my Android phone. Haha!

In this post I’ll show you the code on:

  • How to pull videos from you Facebook Page and display it to your website.
  • We will retrieve just the video’s title, date it was created, the actual video and its description.

We were able to achieve this using the FQL, Facebook PHP SDK. As of this posting, the current PHP SDK version I downloaded is v.3.1.1. And of course, creating a Facebook App so you can have your own AppId and App Secret Id.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja Dummy Page Videos</title>
        <style type=’text/css’>
            #page_title{
                font-size:16px;
                font-weight:bold;
                margin: 0 0 10px 0;
            }
           
            .date_created{
                font:italic 12px Arial, Helvetica, sans-serif;
                color:#fff;
                margin:0 0 5px 0;
            }
           
            .video_desc{
                font:12px Arial, Helvetica, sans-serif;
                color:#fff;
                margin:0 0 5px 0;
            }
           
            .video_item{
                width:320px; /*i tried it with a bigger video and it’s 400px*/
                float:left;
                padding:5px;
                background-color:brown;
                margin: 5px;
            }
           
            .video_title{
                font:20px Arial, Helvetica, sans-serif;
                font-weight:bold;
                color:#fff;
            }
        </style>
    </head>
<body>
<div class=’page_title’>
    These videos are synchronized with this
    <a href=’https://www.facebook.com/video/?id=221167777906963′ target=’_blank’>
        Dummy Page Videos
    </a>
</div>
<?php
require ‘fb-sdk/src/facebook.php’;

//specify you appId and secret
$facebook = new Facebook(array(
  ‘appId’  => ‘change_to_your_app_id’,
  ‘secret’ => ‘change_to_your_app_secret’,
  ‘cookie’ => true, // enable optional cookie support
));

//query to get videos
//specify you fan page id, I got 221167777906963
//you can also use the LIMIT clause here if you want to show limited number of videos only
$fql = “SELECT
            vid, owner, title, description, thumbnail_link,
            embed_html, updated_time, created_time
        FROM
            video
        WHERE owner=221167777906963″;
           
$param  =   array(
 ‘method’    => ‘fql.query’,
 ‘query’     => $fql,
 ‘callback’  => ”
);
$fqlResult   =   $facebook->api($param);

//loop through each videos
foreach( $fqlResult as $keys => $values ){
   
    echo “<div class=’video_item’>”;
        echo “<div class=’video_title’>” . $values['title'] . “</div>”;
        echo “<div class=’date_created’>Date Created: “ . date( ‘l, F d, Y’, $values['created_time'] ) . “</div>”;
        echo $values['embed_html'];
        echo “<div class=’video_desc’>” . $values['description'] . “</div>”;
    echo “</div>”;
}
?>
   
  </body>
</html>

You can also retrieve other videos information if you want, please see the videos table of Facebook.

Home Android

How To Get A Job In Tech

How To Get A Job In Tech? Well, I currently have a job in the IT industry but not in these big and amazing  companies such as Google, Apple and Facebook. Honestly, I've been dreaming of getting a job at Google. Haha! I choose Google because I love their products such as GMail, Google Docs, Android, Search Engine and many others even though there are some ads, for me it's just fine and natural. It enable me to enjoy great technologies free. :)

But anyway, I'm happy with my current job, developing Google Android applications and utilizing lots of their web development tools such as of Google Code, Analytics, and Webmaster tools.

I wondered how to get at job in these awesome companies. So I thank this info-graphic for giving me some idea. Haha! Let's see:

Computers – A Chronological Timeline

I love computers. This is where I do most of my stuff. I do Web and Android programming, made my dream of being a writer come true by blogging, connecting with friends via social networking site such as facebook and twitter, researching, having a conversation with other Software Developers around the world via StackOverflow and other Q and A or forum sites, helping and inspiring others, playing games such as Angry Birds and Red Alert, etc. 
My career wouldn't exist without it. 
Computers changed the world - how we work, think and live. Most businesses in the world won't run without computer systems, and they won't get promoted without a website.

So, it is such a joy to see some of its history, how it evolved from generation to generation.

It was so nice that I came across this infographic here. :)

Home Facebook

Google+ vs. Facebook: Mark Zuckerberg’s Reaction

Alright, so I watched this video for about 10 times now and I know I'm gonna be watching this one tomorrow and in the future. Hahaha! This one really makes me laugh. Well I know some of you might not find it funny but this one is really hilarious for me! I mean, I was like ROFL! This is about MySpace, Facebook and Google+. We all know the competition they had or they're having. The actors are really good.

Real Tom, Fake Tom :))

Fake Zuck, Real Zuck. Well yeah, Fake Zuck looks Gay here. :))

The movie clip were made by the Rooster Teeth. Thanks to them for making my day. :))

Here are some of my favorite lines on that video:

------

Zuck: Listen, we're friends right?
Guy: Sure yeah, we're on the same, circle of friends.

------

Zuck: Do I know you from somewhere?
Tom: Let me give you a hint.

------

Tom: I'm sorry I didn't get your name
Zuck: It's not important, listen, I have to go.

------

Tom: I'm not gonna hurt you, you know why Zuckerberg? I don't have to.

------

There's a lot more. Well, to understand those lines more, just watch it:


The real Tom Anderson had his personal comment on this video:

"G+ / FB / MySpace Parody :-) Takes awhile to get goin' :) Sorta a video version of the comic I shared a few days ago. Update: Some people reacted to this post by suggesting I'm eager to see Zuckerberg / Facebook go down. You're not reading my posts at all if you think that. As I've started a few times, Mark has always been a gentleman to me, and I admire what he's done, and am looking forward to what he will do. The competition between G+, Twitter and Facebook will make all three companies better. Who wins? Us, the users. Did Facebook even have a "status update" before Twitter? FB grew and became better because of that competition. And as for me, my ownership of MySpace was sold in the initial 2005 sale not in the recent fire sale (see previous post). From my perspective, I'm grateful and feel lucky both for the money I made and the long run MySpace did have (I left in early 2009)."

He said that on his Google+ account. Yes, he posted it in his personal G+ account. I admire Tom for being really cool, he has such a great sense of humor. He's a good sport. Tom, "Invented Friends" should be one of your bragging rights in your Google Plus account!

:))))

Home PHP

How To Customize reCAPTCHA

Have you ever received unsolicited (Spam) messages, comments or notifications in your email, facebook account, or to other services you are using online? Probably yes. I think almost all people using the internet experienced it already. There are trillions of spam messages sent every year.

One effective way to prevent those spam messages to your form is using a “Completely Automated Public Turing test to tell Computers and Humans Apart” or CAPTCHA in short. Google, Facebook, Yahoo, and other big internet companies uses this method. So today we are going to do a script that uses Google reCAPTCHA for our form. This tool by Google is widely used in the internet, maybe you’re familiar with the red box image below:

Home>PHP How To Customize reCAPTCHA

Customizing your Google Recaptcha

DOWNLOAD SOURCE CODE LIVE DEMO

Step 1: Download the recaptcha library here.

Step 2: We’re going the have the following code on our index.php file.

<html>
<head>
<title>https://www.codeofaninja.com/ - Customized reCAPTCHA For Your Form using PHP</title>
<style type='text/css'>    
/*
the customization of our recaptcha field
recaptcha_widget id is what we're customizing
*/

#recaptcha_widget{
    magin: 0;
}

#recaptcha_widget a{
    color: #000;
    text-decoration: none;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    margin: 15px 0 0 0;
    padding: 2px 4px 2px 4px;
    background-color: #F5DEB3;
}

#recaptcha_widget a:hover{
    background-color: #DEB887;
}

.text{
    margin: 0 0 5px 0;
}

/*
just some message box style
when form is submitted
*/
#error-box{
    border: 4px solid #FF0000; 
    background-color: #FA8072;
    color: #fff;
    font-family: Arial, Helvetica, sans-serif;
    width: 430px;
    margin: 0 0 5px 0;
    padding: 4px;
}

#success-box{
    border: 4px solid #32CD32; 
    background-color: #00FF7F;
    color: #000;
    font-family: Arial, Helvetica, sans-serif;
    width: 430px;
    margin: 0 0 5px 0;
    padding: 4px;
}
</style>
</head>
<body>
<?php
//defining indexes
isset( $_REQUEST['action'] ) ? $action = $_REQUEST['action'] : $action = '';
isset( $_REQUEST['email'] ) ? $email = $_REQUEST['email'] : $email = '';
isset( $_REQUEST['user_password'] ) ? $user_password = $_REQUEST['user_password'] : $user_password = '';
isset( $_REQUEST['recaptcha_challenge_field'] ) ? $recaptcha_challenge_field = $_REQUEST['recaptcha_challenge_field'] : $recaptcha_challenge_field='';
isset( $_REQUEST['recaptcha_response_field'] ) ? $recaptcha_response_field = $_REQUEST['recaptcha_response_field'] : $recaptcha_response_field='';

require 'recaptcha/recaptchalib.php'; 
/* ---------------------------recaptcha code----------------------- */
//use your own private key here
$privatekey = "6LdUOcYSAAAAAGT-EbCqOldQ54GJhqG3ZdMkwLBG";
$resp = recaptcha_check_answer ($privatekey,
                        $_SERVER["REMOTE_ADDR"],
                        $recaptcha_challenge_field,
                        $recaptcha_response_field);

if (!$resp->is_valid) {
    $recaptcha = 'wrong';
} else {
    $recaptcha = 'correct';
}
/* ---------------------------recaptcha code----------------------- */
    
//when the form is submitted
if( $action == "signup" ){

$error_msg = '';

//if( empty($email) || empty($user_password)){
if( $email == '' || $user_password == ''){
    $error_msg .= "<div>-{$email}{$user_password}Field cannot be empty.</div>";
}

if( $recaptcha == 'wrong' ){
    $error_msg .= "<div>-You should enter characters that match the word verification.</div>";
}

if( $error_msg != '' ){
    echo "<div id='error-box'>";
        echo $error_msg;
    echo "</div>";
}else{
    echo "<div id='success-box'>";
        echo "Form successfully submitted.";
    echo "</div>";
}

}

?>

<!-- 
-this script is needed since we
are customizing recaptcha 
-it comes first before the form tag - always
-->
<script type="text/javascript">
var RecaptchaOptions = {
    theme : 'custom',
    custom_theme_widget: 'recaptcha_widget'
};
</script>

<!-- form tag comes first before table tag - always. -->
<form action='#' method='post' class='form'>
<table>
    <tr>
        <td align='right'>Email:</td>    
        <td><input type='text' name='email' /></td>
    </tr>
    <tr>
        <td align='right'>Password:</td>
        <td><input type='text' name='user_password' /></td>
    </tr>
    <tr>
        <td valign='top'>Word Verification.: </td>
        <td>
        
<div style='margin: 0px auto; text-align: center; width: 360px;'>
    

        <div class="field-space" style='text-align: left;'>
        
<!-- the id recaptcha_widget is what we're customizing -->
<div id="recaptcha_widget" style="display:none">

    <div id="recaptcha_image"></div>
    <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect, please try again</div>

    <div class="recaptcha_only_if_image" style='margin-bottom: 10px;'>Enter the words above : </div>
    <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>

    <div><input type="text" id="recaptcha_response_field" name="recaptcha_response_field" size='30' class='text' /></div>
    
    <span><a href="javascript:Recaptcha.reload()">Get Another Challenge</a>  </span> 
    <span class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')">Try Audio</a>  </span>
    <span class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')">Try Image</a>  </span>

    <span><a href="javascript:Recaptcha.showhelp()">Help</a></span>

</div>

<!-- user your own public key after "k="-->

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LdUOcYSAAAAALa38Uxegl8owzKXGomiSkV498n_"></script>
<noscript>
    <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LdUOcYSAAAAALa38Uxegl8owzKXGomiSkV498n_" height="300" width="500" frameborder="0"></iframe>
    <br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>

        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            
        <!-- our hidden field and submit button here -->
        <div class="submit" style='float: left;'>
                <input type='hidden' name='action' value='signup' />
                <input type='submit' value='Sign Up!' />
        </div>
        
        </td>
    </tr>
</table>
</form>

</body>
</html>

That’s it! :)

display-facebook-events-on-website

How To Display Facebook Page Events on Website using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

Need to embed a single Facebook page event on your website? Watch this tutorial.

What's next? You can try SociableKIT now, view a live demo here and here or continue with the code tutorial below.

Let's code!

Do you have an event manager on your website? Do you create events on your Facebook page? If your answer is both YES, you're wasting a lot of time managing your brand's events information online.

What if there's a way to create an event ONCE, and then let it appear both on your Website and Facebook page? Will you be happy saving your precious time? Our code for today will make you happy then, just like we are!

Today we're gonna talk about how to display publicly available Facebook Page EVENTS on your website. This one is great if you want your Facebook page events to be shown in your website in a synchronized way.

Once you created or updated an event on Facebook, it will be automatically reflected on your website too. The advantages and risks of this is almost the same with what I discussed in my first post  related to this one.

Read more