How to create Pinterest-like script – step 2

How to create Pinterest-like script – step 2

12 103395
How to create Pinterest-like script - step 2

How to create Pinterest-like script – step 2

Today I would like to introduce our second turorial where we are creating own Pinterest-like script. For today I prepared next interesting features: html5 photo uploader (please pay attention, that this feature works well in all modern browsers except for the IE) and ajaxy popup to display full-size photos. I used free jQuery plugin ColorBox to do it. Well, I think that now we have to test it and understand the codes.

Now you can check our demonstration and download the sources:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Step 1. HTML

As usual, our first step is html markup. I made one important thing – I moved whole file into ‘templates’ folder. And, made few changes in it: added style and script files for ColorBox, upload form was changed slightly, and finally, I replaced hardcoded pins to template key. It is called {images_set}. Now, our index.html template looks like that:

templates/index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <meta name="author" content="Script Tutorials" />
        <title>How to create Pinterest-like script - step 2 | Script Tutorials</title>
        <!-- add styles -->
        <link href="css/main.css" rel="stylesheet" type="text/css" />
        <link href="css/colorbox.css" rel="stylesheet" type="text/css" />
        <!-- add scripts -->
        <script src="js/jquery.min.js"></script>
        <script src="js/jquery.colorbox-min.js"></script>
        <script src="js/jquery.masonry.min.js"></script>
        <script src="js/script.js"></script>
    </head>
    <body>
        <!-- header panel -->
        <div class="header_panel">
            <!-- logo -->
            <a href="#" class="logo"></a>
            <!-- search form -->
            <form action="" method="get" class="search">
                <input autocomplete="off" name="q" size="27" placeholder="Search" type="text" />
                <input name="search" type="submit" />
            </form>
            <!-- navigation menu -->
            <ul class="nav">
                <li><a href="#add_form" id="login_pop">Add +</a></li>
                <li>
                    <a href="#">About<span></span></a>
                    <ul>
                        <li><a href="#">Help</a></li>
                        <li><a href="#">Pin It Button</a></li>
                        <li><a href="#" target="_blank">For Businesses</a></li>
                        <li class="div"><a href="#">Careers</a></li>
                        <li><a href="#">Team</a></li>
                        <li><a href="#">Blog</a></li>
                        <li class="div"><a href="#">Terms of Service</a></li>
                        <li><a href="#">Privacy Policy</a></li>
                        <li><a href="#">Copyright</a></li>
                        <li><a href="#">Trademark</a></li>
                    </ul>
                </li>
                <li>
                    <a href="#">Profile<span></span></a>
                    <ul>
                        <li><a href="#">Invite Friends</a></li>
                        <li><a href="#">Find Friends</a></li>
                        <li class="div"><a href="#">Boards</a></li>
                        <li><a href="#">Pins</a></li>
                        <li><a href="#">Likes</a></li>
                        <li class="div"><a href="#">Settings</a></li>
                        <li><a href="#">Logout</a></li>
                    </ul>
                </li>
                <li>
                    <a href="https://www.script-tutorials.com/pinterest-like-script-step-2/">Back to tutorial<span></span></a>
                </li>
            </ul>
        </div>
        <!-- upload form -->
        <a href="#x" class="overlay" id="add_form"></a>
        <div class="popup">
            <div class="header">
                <a class="close" href="#close">x</a>
                <h2>Upload a Pin</h2>
            </div>
            <form id="upload_form">
                <input type="file" name="image_file" id="image_file" onchange="" />
            </form>
            <div id="upload_result"></div>
        </div>
        <!-- main container -->
        <div class="main_container">
            {images_set}
        </div>
    </body>
</html>

Step 2. PHP

Now, our main index file is index.php. Mainly because we have to prepare list of images (HTML) at this step. Please review this file:

index.php

// set warning level
if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
$sFolder = 'photos/';
$aAllowedExt = array('jpg' => 1, 'png' => 1);
$sImages = '';
$iCnt = 1;
$rDir = opendir($sFolder);
if ($rDir) {
    while ($sFile = readdir($rDir)) {
        if ($sFile == '.' || $sFile == '..' || ! is_file($sFolder . $sFile))
            continue;
        $aPathInfo = pathinfo($sFile);
        $sExt = strtolower($aPathInfo['extension']);
        if (isset($aAllowedExt[$sExt])) {
            if (strpos($sFile, '_full') === false) {
                $sFilename = $aPathInfo['filename'];
                $sImages .= <<<EOL
<!-- pin element {$iCnt} -->
<div class="pin">
    <div class="holder">
        <div class="actions" pin_id="{$iCnt}">
            <a href="#" class="button">Repin</a>
            <a href="#" class="button">Like</a>
            <a href="#" class="button comment_tr">Comment</a>
        </div>
        <a class="image ajax" href="service.php?id={$sFilename}&ext={$sExt}" title="Photo number {$iCnt}">
            <img alt="Photo number {$iCnt}" src="{$sFolder}{$sFile}">
        </a>
    </div>
    <p class="desc">Photo number {$iCnt} description</p>
    <p class="info">
        <span>{$iCnt} likes</span>
        <span>{$iCnt} repins</span>
    </p>
    <form class="comment" method="post" action="" style="display: none">
        <input type="hidden" name="id" value="0" />
        <textarea placeholder="Add a comment..." maxlength="1000"></textarea>
        <button type="button" class="button">Comment</button>
    </form>
</div>
EOL;
                $iCnt++;
            }
        }
    }
    closedir( $rDir );
}
// draw common page
$aKeys = array(
    '{images_set}' => $sImages
);
echo strtr(file_get_contents('templates/index.html'), $aKeys);

Everything is easy: basically, we parse all image files in ‘photos’ folder, and prepare our pins (image objects) to display at index page. For today’s lesson, we don’t use database, but we will (in next lesson). Because we still have to link comments and authors with certain images. Please pay attention how we use ColorBox plugin: we just can set class name as ‘ajax’, and add necessary url (href) to a page with ajax response (bigger image), we use ‘service.php’ to generate it. Let’s review this file:

service.php

// set warning level
if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
$i = stripslashes(strip_tags($_GET['id']));
$ext = stripslashes(strip_tags($_GET['ext']));
// if something is wrong
if (! $i || ! $ext) {
    exit;
}
// prepare full image path
$sFullImgPath = $sFilename = '';
$sFolder = 'photos/';
$aAllowedExt = array('jpg' => 1, 'png' => 1);
$aPathInfo = pathinfo($i . '.' . $ext);
$sExt = strtolower($aPathInfo['extension']);
if (isset($aAllowedExt[$sExt])) {
    $sFilename =  $aPathInfo['filename'];
    $sFullImgPath = $sFolder . $sFilename . '_full.' . $sExt;
}
if (! $sFullImgPath) {
    exit;
}
?>
<div class="pin bigpin">
    <div class="owner">
        <a href="#" class="button follow_button">Follow</a>
        <a target="_blank" class="owner_img" href="#">
            <img alt="Mr Brown" src="images/avatar.jpg" />
        </a>
        <p class="owner_name"><a target="_blank" href="#">Mr Brown</a></p>
        <p class="owner_when">Uploaded X months ago</p>
    </div>
    <div class="holder">
        <div class="actions">
            <a href="#" class="button">Repin</a>
            <a href="#" class="button">Like</a>
        </div>
        <a class="image" href="#" title="Photo <?= $sFilename ?>">
            <img alt="Photo <?= $sFilename ?>" src="<?= $sFullImgPath ?>">
        </a>
    </div>
    <p class="desc">Photo <?= $sFilename ?> description</p>
    <div class="comments"></div>
    <form class="comment" method="post" action="#">
        <input type="hidden" name="id" value="0" />
        <textarea placeholder="Add a comment..." maxlength="1000"></textarea>
        <button type="button" class="button">Comment</button>
    </form>
</div>

As you see, right now we use this file only to generate bigger block with image (and – with several other elements). I’m going to use this file to work with comments, likes, and possible something else. Finally, as I mentioned – I added the ability to upload files (images). Here is it:

upload.php

// set warning level
if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
function uploadImageFile() { // Note: GD library is required for this upload function
    $iDefWidth = 192; // default photos width (in case of resize)
    $iFDefWidth = 556; // full default photos width (in case of resize)
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $iWidth = $iHeight = $iFDefWidth; // desired image dimensions
        $iJpgQuality = 75;
        if ($_FILES) {
            // if there are no errors and filesize less than 400kb
            if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 400 * 1024) {
                if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
                    // new unique filename
                    $sTempFileName = 'photos/' . md5(time().rand());
                    // move uploaded file into cache folder
                    move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);
                    // change file permission to 644
                    @chmod($sTempFileName, 0644);
                    // if temp file exists
                    if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
                        $aSize = getimagesize($sTempFileName); // obtain image info
                        if (!$aSize) {
                            @unlink($sTempFileName);
                            return;
                        }
                        // check for image type and create a new image from file
                        switch($aSize[2]) {
                            case IMAGETYPE_JPEG:
                                $sExt = '.jpg';
                                $vImg = @imagecreatefromjpeg($sTempFileName);
                                break;
                            case IMAGETYPE_PNG:
                                $sExt = '.png';
                                $vImg = @imagecreatefrompng($sTempFileName);
                                break;
                            default:
                                @unlink($sTempFileName);
                                return;
                        }
                        // get source image width and height
                        $iSrcWidth = imagesx($vImg);
                        $iSrcHeight = imagesy($vImg);
                        // recalculate height (depends on width)
                        $iHeight = $iSrcHeight * $iWidth / $iSrcWidth;
                        // create a new true color image
                        $vDstImg = @imagecreatetruecolor( $iWidth, $iHeight );
                        // copy and resize
                        imagecopyresampled($vDstImg, $vImg, 0, 0, 0, 0, $iWidth, $iHeight, $iSrcWidth, $iSrcHeight);
                        // define a result image filename
                        $sResultFileName = $sTempFileName . '_full' . $sExt;
                        // output image to file and set permission 644
                        imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
                        @chmod($sResultFileName, 0644);
                        // and, prepare a thumbnail as well
                        $iWidth = $iDefWidth;
                        $iHeight = $iSrcHeight * $iWidth / $iSrcWidth;
                        $vDstThImg = @imagecreatetruecolor($iWidth, $iHeight);
                        imagecopyresampled($vDstThImg, $vImg, 0, 0, 0, 0, $iWidth, $iHeight, $iSrcWidth, $iSrcHeight);
                        $sResultThumnName = $sTempFileName . $sExt;
                        imagejpeg($vDstThImg, $sResultThumnName, $iJpgQuality);
                        @chmod($sResultThumnName, 0644);
                        // unlink temp file
                        @unlink($sTempFileName);
                        return $sResultFileName;
                    }
                }
            }
        }
    }
}
$sImage = uploadImageFile();
echo '1';

Our script accepts only 2 formats: png and jpg images. It uses GD library to resize incoming image into 2 dimensions (with width = 192px as a thumbnail and 556px as a full image).

Step 3. CSS

Now, I should give you all the styles for our bigger unit (which we get when we click at pin object):

css/main.css

/* big pin styles */
.bigpin {
    background-color: transparent;
    box-shadow: none;
    float: none;
    margin: 0;
    padding: 5px;
    width: 600px;
}
.bigpin .owner {
    border-bottom: 1px solid #D1CDCD;
    overflow: hidden;
    padding-bottom: 10px;
}
.bigpin .follow_button {
    background-color: #D43638;
    background-image: -webkit-linear-gradient(center top , #EB5367, #E04751 50%, #DE404A 50%, #D43638);
    background-image: -moz-linear-gradient(center top , #EB5367, #E04751 50%, #DE404A 50%, #D43638);
    background-image: linear-gradient(center top , #EB5367, #E04751 50%, #DE404A 50%, #D43638);
    border-color: #910101;
    color: #FCF9F9;
    font-size: 13px;
    padding: 7px 9px;
    text-shadow: 0 -1px rgba(34, 25, 25, 0.5);
}
.bigpin .owner_img {
    float: left;
    margin-right: 9px;
    width: 50px;
}
.bigpin .owner_img img {
    display: block;
    height: 50px;
    width: 50px;
}
.bigpin .owner_name {
    font-size: 23px;
    line-height: 1em;
    margin-bottom: 2px;
}
.bigpin .owner_when {
    color: #8C7E7E;
    display: block;
    font-size: 13px;
    margin: 5px 0 0;
    padding-left: 60px;
}
.bigpin .holder {
    margin-top: 10px;
}
.bigpin .actions {
    left: 7px;
    top: 15px;
}
.bigpin .image {
    cursor: pointer;
}
.bigpin .image img {
    display: block;
    margin: 0 auto;
    max-width: none;
}
.bigpin .desc {
    border-bottom: 1px solid #D1CDCD;
    padding-bottom: 10px;
}
.bigpin .comments {
    margin: 20px 0;
    overflow: hidden;
    width: 99%;
}
.bigpin .comments p {
    color: #211922;
    font-size: 13px;
    line-height: 1.33em;
    margin-bottom: 10px;
    word-wrap: break-word;
}
.bigpin .comment {
    background-color: transparent;
    border-top: medium none;
    box-shadow: none;
    margin: 0;
    padding: 0;
}
.bigpin  .comment textarea {
    padding: 10px;
    margin-bottom: 10px;
    width: 96%;
}

Step 4. JS

As the latests step for today – updated javascript code:

js/script.js

function fileSelectHandler() {
    // get selected file
    var oFile = $('#image_file')[0].files[0];
    // html5 file upload
    var formData = new FormData($('#upload_form')[0]);
    $.ajax({
        url: 'upload.php', //server script to process data
        type: 'POST',
        // ajax events
        beforeSend: function() {
        },
        success: function(e) {
            $('#upload_result').html('Thank you for your photo').show();
            setTimeout(function() {
                $("#upload_result").hide().empty();
            }, 4000);
        },
        error: function(e) {
            $('#upload_result').html('Error while processing uploaded image');
        },
        // form data
        data: formData,
        // options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });
}
$(document).ready(function(){
    // file field change handler
    $('#image_file').change(function(){
        var file = this.files[0];
        name = file.name;
        size = file.size;
        type = file.type;
        // extra validation
        if (name && size)  {
            if (! file.type.match('image.*')) {
                alert("Select image please");
            } else {
                fileSelectHandler();
            }
        }
    });
    // masonry initialization
    $('.main_container').masonry({
        // options
        itemSelector : '.pin',
        isAnimated: true,
        isFitWidth: true
    });
    // onclick event handler (for comments)
    $('.comment_tr').click(function () {
        $(this).toggleClass('disabled');
        $(this).parent().parent().parent().find('form').slideToggle(250, function () {
            $('.main_container').masonry();
        });
    });
    $('.ajax').colorbox({
        onOpen:function(){
        },
        onLoad:function(){
        },
        onComplete:function(){
            $(this).colorbox.resize();
        },
        onCleanup:function(){
        },
        onClosed:function(){
        }
    });
});

A new function was added: fileSelectHandler. It uses html5 to POST image file to server. Once it has received a file, it returns us a message if our image was accepted or not. Also, I added here ‘colorbox’ initialization. It is very easy to use this plugin.


Live Demo

Conclusion

We have just finished our second lesson where we writing our own Pinterest-like script. I hope that you like it. It would be kind of you to share our materials with your friends. Good luck and welcome back!

SIMILAR ARTICLES

Understanding Closures

0 16780

12 COMMENTS

  1. You are really great bro… Thankx for your nice experience and sharing to web world… My request to you please add login and registration php forms codes.
    thankx

    • Hi Victor,
      Unfortunately, it won’t work for lower IE, because of lots of CSS3 features (as you know, IE8 and below doesn’t support CSS3 at all)

  2. Very cool! But unfortunately does not work with chrome :( the pins in further rows do not align correctly

Leave a Reply to admin Cancel reply