Updates from December, 2013 Toggle Comment Threads | Keyboard Shortcuts

  • WordPress Custom Image Field in 80 lines 

    You need nearly 80 lines to add a custom file field to post edit screen (and create screen). There are some situations where it’s necessary to have more than one post image, for example if you want to have a separate image of facebook sharing (og:image).

    The examples i found online are a bit complicated and often do more than just adding an image field, so here is the minimal code to do just add the field and save the image-url to post-meta.

    Adding the field to admin is still simple and done in bohuco_edit_post and bohuco_image functions. There are two actions used, one for edit and the other for creating new posts. The bohuco_image formats the html for the form field, for this example i made it very simple.

     
        function bohuco_edit_post($post_id) {
            add_meta_box('bohuco_customImage', 'Custom Image', 'bohuco_image', 'post', 'normal', 'high' );
        }
        add_action('load-post.php', 'bohuco_edit_post');
        add_action('load-post-new.php', 'bohuco_edit_post');
     
        function bohuco_image($post, $field) {
            wp_nonce_field(plugin_basename(__FILE__), '_wpnonce_bohuco');
     
            if (! $value = get_post_meta($post->ID, $field['id'], true)) {
                $value = '';
            }
     
            echo '<input type="file" name="'.$field['id'].'_upload" size="55" /><br />';
            if ($value) {
                echo '<img src="'.$value.'" />';
            }
        }

    Saving happens in bohuco_save_post where first the upload is done with build-in wordpress function wp_handle_upload, after that the url of the uploaded image is saved to a meta field (add_post_meta or update_post_meta). The overrides array holds some configuration for wp_handle_upload, the test_form must be false because it checks if the default upload action is used.

     
        function bohuco_save_post($postId) {
     
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                return $postId;
            }
     
            if(isset($_FILES['bohuco_customImage_upload']['name'])
                && ! empty($_FILES['bohuco_customImage_upload']['name'])) {
     
                if (! wp_verify_nonce($_REQUEST['_wpnonce_bohuco'], plugin_basename(__FILE__))) {
                    die('Security check'); 
                }
     
                $overrides = array('test_form'=>false);
                $result = wp_handle_upload($_FILES['bohuco_customImage_upload'], $overrides);
     
                if(isset($result['error']) && ! empty($result['error'])) {
                    echo '<div class="error">'.$result['error'].'</div>';
                } else {
                    $imageFileLocation = $result['url'];
                    if (! update_post_meta($postId, 'bohuco_customImage', $imageFileLocation)) {
                        add_post_meta($postId, 'bohuco_customImage', $imageFileLocation, true);
                    }                
                }
            }
        }
        add_action('save_post', 'bohuco_save_post');

    This all works only if you first change the editor form enctype to multipart/form-data as you can see in add_post_enctype function. It’s a hack but it works, maybe there is a better method to change the post form tag?

     
        function add_post_enctype() {
            echo "<script type='text/javascript'>
                      jQuery(document).ready(function(){
                          jQuery('#post').attr('enctype','multipart/form-data');
                      });
                  </script>";
        }
        add_action('admin_head', 'add_post_enctype');

    Here is the whole example as little plugin, it should also work if you put it in a functions.php of a theme. I build it in wordpress 3.8 but should also work in older versions.

    /*
    Plugin Name: Custom Image Field
    Plugin URI: http://bohuco.net/blog
    Version: 1.0.0
    Author: @DerFichtl
    */
     
    if (is_admin()) {
     
        /**
         * Modify form enctype to support uploads
         */
        function add_post_enctype() {
            echo "<script type='text/javascript'>
                      jQuery(document).ready(function(){
                          jQuery('#post').attr('enctype','multipart/form-data');
                      });
                  </script>";
        }
        add_action('admin_head', 'add_post_enctype');
     
        /**
         * Add custom field to new post and edit post screen
         */
        function bohuco_edit_post($post_id) {
            add_meta_box('bohuco_customImage', 'Custom Image', 'bohuco_image', 'post', 'normal', 'high' );
        }
        add_action('load-post.php', 'bohuco_edit_post');
        add_action('load-post-new.php', 'bohuco_edit_post');
     
        /**
         * Format the field html and output image if present
         */
        function bohuco_image($post, $field) {
            wp_nonce_field(plugin_basename(__FILE__), '_wpnonce_bohuco');
     
            if (! $value = get_post_meta($post->ID, $field['id'], true)) {
                $value = '';
            }
     
            echo '<input type="file" name="'.$field['id'].'_upload" size="55" /><br />';
            if ($value) {
                echo '<img src="'.$value.'" />';
            }
        }
     
        /**
         * Do upload and save custom meta field 
         */
        function bohuco_save_post($postId) {
     
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                return $postId;
            }
     
            if(isset($_FILES['bohuco_customImage_upload']['name'])
                && ! empty($_FILES['bohuco_customImage_upload']['name'])) {
     
                if (! wp_verify_nonce($_REQUEST['_wpnonce_bohuco'], plugin_basename(__FILE__))) {
                    die('Security check'); 
                }
     
                $overrides = array('test_form'=>false);
                $result = wp_handle_upload($_FILES['bohuco_customImage_upload'], $overrides);
     
                if(isset($result['error']) && ! empty($result['error'])) {
                    echo '<div class="error">'.$result['error'].'</div>';
                } else {
                    $imageFileLocation = $result['url'];
                    if (! update_post_meta($postId, 'bohuco_customImage', $imageFileLocation)) {
                        add_post_meta($postId, 'bohuco_customImage', $imageFileLocation, true);
                    }                
                }
            }
        }
        add_action('save_post', 'bohuco_save_post');
    }

    Things to improve would be: 1. Check if the uploaded file is an image, example works with all files allowed by wordpress. 2. Create a thumbnail of the image. 3. The save function is called twice if a new post is saved.

    DerFichtl 4:23 am on December 17, 2013 Permalink
    Tags: ,   

     
  • New on GitHub: Game Engine for Text Games 

    My Waiting Game Engine (WGE) is an simple php-engine for online browser games where the main task is to wait.

    For each second you wait you get some money (depends on your level) and with money you can do/buy things. You can then combine the things and do more and more actions. For each action you earn experience (or lost some if you do the wrong action). And so on, and so on. More infos on GitHub.

    Test a waiting game:
    http://bohuco.net/waiting-game-engine/

    Source code on GitHub:
    https://github.com/DerFichtl/waiting-game-engine

     

    DerFichtl 3:15 pm on June 15, 2013 Permalink  

     
  • How to Licence Apple Fonts for Web Usage 

    … not so easy as first thought: Buy a “Web-Licence” or “Web-Font” and use it on your page … thats not possible with apple fonts.

    If you want browsersafe use one of more than 300 adobe webfonts like myriad, garamond or juniper you have to do it via typekit or webink. Just this two vendors can sell web licences for apple fonts.

     

    Both services are easy to use: Just select the fonts you want to use and then insert the provided snippet in your webpage. Typekit uses javascript to deliver the font, webink do it with css-tag. So i like the webink delivery version more.

    <!-- html head -->
    <link href="http://fnt.webink.com/wfs/webink.css/
        ?project=CD0700EA-B4D9-4AFA-A52E-1F3AB19287CF
        &fonts=73E6C83D-7F13-A8AE-4770-C315AE5061C3:f=MyriadPro-Regular" rel="stylesheet" type="text/css"/>
    /* in css */
    @import url("http://fnt.webink.com/wfs/webink.css/
        ?project=CD0700EA-B4D9-4AFA-A52E-1F3AB19287CF
        &amp;fonts=73E6C83D-7F13-A8AE-4770-C315AE5061C3:f=MyriadPro-Regular");

    The pricing is based  on website usage … typekit on pageviews and webink on unique users. The prices goes from free to 120 USD per year for larger websites. More Infos you can find on the Adobe web fonts site.

    DerFichtl 6:57 am on November 25, 2012 Permalink  

     
  • Neurale Netzwerke in PHP programmieren 

    Neural Network ist ein relativ einfacher Algorithmus mit dem man allerhand interessante Dinge anstellen kann. Grundsätzlich funktionierts so das man das Neuronen-Netzwerk mit Trainingsdaten füttert, aufgrund dieses Trainingssets kann das Netzwerk dann andere Daten auswerten.

    (More …)

    DerFichtl 7:22 pm on November 22, 2012 Permalink  

     
  • New Bootstrap Version by Twitter 

    Today Twitter released a new version of their popular html/css boilerplate for webpages. A good time to introduce my favorite bootstrap features …

    1. Icons, Icons, Icons

    Bootstrap includes a fat icon sprite with 120 small icons from glyphicons.com. all have transparent background and are available in black and in white.

    2. Inline Labels

    Put some highlights in your texts with inline labels.

    3. Real Button Porn

    Buttons in different colors, with and without dropdown and in groups or lonely.

    … and what is your favorite feature from twitter bootstrap?

    DerFichtl 11:00 pm on February 2, 2012 Permalink  

     
  • Image Watermarks in WordPress 

    Here a quick and easy way to put watermarks in your images. Just copy the code in the function.php of the active theme and you can watermark your pictures in wordpress admin.

    (More …)

    DerFichtl 8:37 pm on June 2, 2011 Permalink  

     
    • Aneeq Tariq 11:34 am on June 6, 2012 Permalink | Reply

      Watermarking an image in PHP is very easy. If you follow the code below, you can do it in 2 minutes.

      <?php

      function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
      //$SourceFile is source of the image file to be watermarked
      //$WaterMarkText is the text of the watermark
      //$DestinationFile is the destination location where the watermarked images will be placed

      //Delete if destinaton file already exists
      @unlink($DestinationFile);

      //This is the vertical center of the image
      $top = getimagesize($SourceFile);
      $top = $top[1]/2;
      list($width, $height) = getimagesize($SourceFile);

      $image_p = imagecreatetruecolor($width, $height);

      $image = imagecreatefromjpeg($SourceFile);

      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

      //Path to the font file on the server. Do not miss to upload the font file
      $font = ‘arial.ttf’;

      //Font sie
      $font_size = 16;

      //Give a white shadow
      $white = imagecolorallocate($image_p, 255, 255, 255);
      imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);

      //Print in black color
      $black = imagecolorallocate($image_p, 0, 0, 0);
      imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);

      if ($DestinationFile”) {

      imagejpeg ($image_p, $DestinationFile, 100);

      } else {

      header(‘Content-Type: image/jpeg’);

      imagejpeg($image_p, null, 100);

      };

      imagedestroy($image);

      imagedestroy($image_p);

      };

      ?>

      <?php

      $SourceFile = ‘image.jpg’;//Source image
      $DestinationFile = ‘watermarked/image.jpg’;//Destination path
      $WaterMarkText = ‘www.phpHelp.co’;//Watermark text

      //Call the function to watermark the image
      watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

      //Display watermarked image if desired
      if(file_exists($DestinationFile)){
      echo “”;
      echo “The image has been watermarked at ‘”.$DestinationFile.”‘”;
      }
      ?>

      Note:

      This code is being provided to you as a help by http://www.phpHelp.co without any warranty and liability
      Place all the files in a folder on web server.
      Do not forget to upload the font file – arial.ttf.
      Once the image is watermarked, it will be placed in the folder named ‘watermarked’.
      You might need to give ‘write permission’ or ’777 permission’ to the folder named ‘watermarked’ as the new watermarked image will be written in this folder.

      Source:
      http://addr.pk/a730e
      AND
      http://phphelp.co/2012/06/01/how-to-watermark-an-image-in-php/

    • Aneeq Tariq 11:34 am on June 6, 2012 Permalink | Reply

      Watermarking an image in PHP is very easy. If you follow the code below, you can do it in 2 minutes.

      <?php

      function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
      //$SourceFile is source of the image file to be watermarked
      //$WaterMarkText is the text of the watermark
      //$DestinationFile is the destination location where the watermarked images will be placed

      //Delete if destinaton file already exists
      @unlink($DestinationFile);

      //This is the vertical center of the image
      $top = getimagesize($SourceFile);
      $top = $top[1]/2;
      list($width, $height) = getimagesize($SourceFile);

      $image_p = imagecreatetruecolor($width, $height);

      $image = imagecreatefromjpeg($SourceFile);

      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

      //Path to the font file on the server. Do not miss to upload the font file
      $font = ‘arial.ttf’;

      //Font sie
      $font_size = 16;

      //Give a white shadow
      $white = imagecolorallocate($image_p, 255, 255, 255);
      imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);

      //Print in black color
      $black = imagecolorallocate($image_p, 0, 0, 0);
      imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);

      if ($DestinationFile”) {

      imagejpeg ($image_p, $DestinationFile, 100);

      } else {

      header(‘Content-Type: image/jpeg’);

      imagejpeg($image_p, null, 100);

      };

      imagedestroy($image);

      imagedestroy($image_p);

      };

      ?>

      <?php

      $SourceFile = ‘image.jpg’;//Source image
      $DestinationFile = ‘watermarked/image.jpg’;//Destination path
      $WaterMarkText = ‘www.phpHelp.co’;//Watermark text

      //Call the function to watermark the image
      watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

      //Display watermarked image if desired
      if(file_exists($DestinationFile)){
      echo “”;
      echo “The image has been watermarked at ‘”.$DestinationFile.”‘”;
      }
      ?>

      Note:

      This code is being provided to you as a help by http://www.phpHelp.co without any warranty and liability
      Place all the files in a folder on web server.
      Do not forget to upload the font file – arial.ttf.
      Once the image is watermarked, it will be placed in the folder named ‘watermarked’.
      You might need to give ‘write permission’ or ’777 permission’ to the folder named ‘watermarked’ as the new watermarked image will be written in this folder.

      Source:
      http://addr.pk/a730e
      AND
      http://phphelp.co/2012/06/01/how-to-watermark-an-image-in-php/

  • Firefox 4 – Neue HTTP Header 

    Mit der neuen Version des Firefox wurden einige neue HTTP Header eingeführt die Entwicklern die Arbeit etwas erleichtern sollen und den Benutzer besser schützen.

    (More …)

    DerFichtl 7:52 pm on April 5, 2011 Permalink  

     
  • Translate your Site with Google Translate and jQuery 

    With the new Google Translate API and the jQuery Plugin from Balazs Endresz you can add more language versions within seconds.

    (More …)

    DerFichtl 1:14 pm on February 19, 2011 Permalink
    Tags: , , , translate   

     
    • Gordon 2:12 pm on February 19, 2011 Permalink | Reply

      Wir müssen das HTML für die Sprach-Auswahl, und eine kurze Javascript … ;)

      • DerFichtl 11:03 pm on February 20, 2011 Permalink | Reply

        :) Tja, die automatischen Übersetzungen … aber immer noch besser als gar keine Übersetzung …

  • WordPress Quicky: Use the [Shortcode] API 

    Another quicktipp for wordpress plugin developers. With the shortcode API you can easily provide additional commands for wordpress authors …

    (More …)

    DerFichtl 8:52 am on September 24, 2010 Permalink
    Tags: , , , , Shortcode, ,   

     
  • WordPress Quicky: Exclude Categories 

    Another quicktipp for wordpress theme developers.

    If you want to exclude one or more categories from a page (startpage, category-page), you can call the query_posts function with negative category-ids …

    <?php query_posts($query_string . '&cat=-1,-2,-3'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <!-- POST -->
    <?php endwhile; endif; ?>

    DerFichtl 9:35 am on September 23, 2010 Permalink
    Tags: , , ,   

     
  • WordPress Quicky: Register Sidebar Widget with 3.0 

    Another quicktipp for wordpress plugin developers. Registering a sidebar widget can end with a fatal error if you use the code from the wordpress documentation …

    (More …)

    DerFichtl 9:45 am on September 22, 2010 Permalink
    Tags: , , , ,   

     
    • Jamy Hudsk 12:17 pm on February 20, 2011 Permalink | Reply

      Thanks, little less info though, you should visit http://wordpressfunctions.com/global/sidebar-global/register-a-new-sidebar.html if you want to know more.

    • Hubert Pic 10:57 pm on March 18, 2012 Permalink | Reply

      Where can i write this code? and what is the “MyWidgetClass” ? I haven’t create a widget and i have this problem … can you help me ?

      (sorry i’m french, and my englsih is so poor …)

    • Nicolas Bouliane 2:00 am on November 25, 2010 Permalink | Reply

      Why is that? I have the same problem (which you have solved), but I’d love to understand what I’m doing

    • DerFichtl 8:59 am on November 25, 2010 Permalink | Reply

      I really don’t know, it seems that the add_action needs to work with the result of register_widget() and not with the widget classname itself. very irrational but …

    • Hubert Pic 10:57 pm on March 18, 2012 Permalink | Reply

      Where can i write this code? and what is the “MyWidgetClass” ? I haven’t create a widget and i have this problem … can you help me ?

      (sorry i’m french, and my englsih is so poor …)

  • Use Google Closure Compiler Local with PHP 

    In “Google Closure Compiler with PHP” i described how you can use the compiler online via http. Now i will show how you do it local on your server with the java command line application …

    (More …)

    DerFichtl 7:42 pm on September 11, 2010 Permalink
    Tags: , , compiler, , , , performance,   

     
    • Panik 11:07 am on January 12, 2012 Permalink | Reply

      in windows how to do that… i am using xampp and java is installed on C:Program FilesJavajdk1.6.0_18bin

    • Panik 11:07 am on January 12, 2012 Permalink | Reply

      in windows how to do that… i am using xampp and java is installed on C:Program FilesJavajdk1.6.0_18bin

    • Panik 11:07 am on January 12, 2012 Permalink | Reply

      in windows how to do that… i am using xampp and java is installed on C:Program FilesJavajdk1.6.0_18bin

  • Google Ranking Checker Class in PHP 

    Important notice: Check google rankings become a very complicated task today. So many environment variables are important so that this simple ranking checker class don’t work any more. But there are some commercial tools that can still track your rankings like sistrix or seolytics.

    The only goal for an SEO is a good or very good google ranking. To ensure this you have to monitor your rankings and compare it to the positions of your competitors. With the Google AJAX Search API and my little PHP Class you can easy build a Google Ranking Checker …

    The class needs an Google API key for the AJAX Search API (get it here) … it’s just one field and a click and you can start. You can check multiple keywords for multiple domains or urls, just pass this two arrays to the check() method.

    (More …)

    DerFichtl 7:51 pm on July 15, 2010 Permalink
    Tags: , , , , ,   

     
    • Bill 9:13 pm on July 18, 2010 Permalink | Reply

      This is nice article learned new things from this site.thanks for sharing

    • Indiana web design 9:54 pm on July 20, 2010 Permalink | Reply

      How do you post this when designing a website? Do you have the Html file?

    • GXKevin 4:26 pm on July 23, 2010 Permalink | Reply

      Nice post! ;-)

      Flying Tech

    • Soren Beck Jensen 6:30 pm on July 26, 2010 Permalink | Reply

      The demo does not work?

    • DerFichtl 9:37 am on July 27, 2010 Permalink | Reply

      thanks for info, bug fixed, now it works again …

    • Travis L 7:25 pm on July 29, 2010 Permalink | Reply

      Demo still doesn’t seem to work.

    • DerFichtl 8:55 am on July 30, 2010 Permalink | Reply

      @Travis Demo works! What do you want to check?

    • Ash 12:34 am on October 19, 2010 Permalink | Reply

      HI,

      This is very useful. Have you licensed this as GPL or MIT etc. Meaning may I use this in my own projects, for clients etc

      • DerFichtl 4:29 pm on October 19, 2010 Permalink | Reply

        hi, thanks for concern, the class has no license it is just free to use and modify for everyone. maybe when i have time i choose a gpl or lgpl license for it …

    • JC 12:49 pm on October 26, 2010 Permalink | Reply

      hi,

      can you show us how we can invoke this script in html?

    • CJA 5:02 pm on November 11, 2010 Permalink | Reply

      I checked out the test script and its not working. I tried a few keywords and came up with no results then i tried the most obvious keyword ‘Google’ and its coming up as 9th position? it should be #1 position.

      • DerFichtl 5:58 pm on November 11, 2010 Permalink | Reply

        Thanks for comment, i have checked the code and it works fine … but: my class is using the german language version and austria as country so google.at is on first position.

        you can easily change that in the class … and maybe i will add this feature to the online demo … when i have time …

    • CJA 5:27 am on November 12, 2010 Permalink | Reply

      you’re absolutely right… i was thinking about that on my way home from work. If the server the script is located on is somewhere else the results will be different. i’ll have to play with your script.

      thanks for the quick feedback :)

    • Ruben Sedano 11:51 pm on December 14, 2010 Permalink | Reply

      but its not very accuracy because i prove with keyword ‘deportes’ and domain ‘clarin.com’ and not results!!! (-) :S

    • Wes 4:38 am on January 14, 2011 Permalink | Reply

      Hey DerFichtl,
      The new version works great! I see a call to RankingChecker.php. Do you have a link to the code in that file somewhere?

      I tried copying the code above to create a RankingChecker.php file to use with the new version, however I get this error:

      Fatal error: Call to undefined method RankingChecker::setLocale() in /home/wadmin/public_html/index.php on line 17

      Thank you, I really appreciate it.

      • DerFichtl 9:28 am on January 14, 2011 Permalink | Reply

        Dear Wes!
        Thanks for using the ranking checker, you can download the new version here.

    • Dreis 9:09 pm on January 14, 2011 Permalink | Reply

      Tnx for this! Awsome & handy script! if you had a donate button I would donate.

    • DerFichtl 11:41 pm on January 17, 2011 Permalink | Reply

      Thanks, DerFichtl!

    • buy generic Keflex 6:33 pm on March 3, 2011 Permalink | Reply

      The Zune concentrates on being a Portable Media Player. Not a web browser. Not a game machine. Maybe in the future it’ll do even better in those areas, but for now it’s a fantastic way to organize and listen to your music and videos, and is without peer in that regard. The iPod’s strengths are its web browsing and apps. If those sound more compelling, perhaps it is your best choice.

    • Waiver Form 5:18 pm on March 5, 2012 Permalink | Reply

      Great Post

    • Waiver Form 5:18 pm on March 5, 2012 Permalink | Reply

      Great Post

    • Excelanto 6:50 am on December 6, 2014 Permalink | Reply

      Thanks for your valuable posting.I have collect more than information from your website. It is really wonderful blog. please added more than tips. i’m working in Erp Software in india.Here providing very low price and Quality ERP,Cloud ERP, CMS , responsive webdesign and ERP. you have any more than information kindly make me call this number 044-42127512 or send your mail info@excelanto.com.

  • HTML5 WebSockets Example 

    HTML5 WebSockets makes it possible to open a persistent connection to a server within a web-browser via javascript.

    (More …)

    DerFichtl 8:07 pm on July 11, 2010 Permalink
    Tags: , , ,   

     
    • zcorpan 9:58 am on July 13, 2010 Permalink | Reply

      Firefox can’t open the connection for the same reason Chrome 6 dev can’t open the connection. You have implemented version -75 of the protocol (which Safari 5 and Chrome 5 use), while Firefox and Chrome 6 dev support version -76.

    • DerFichtl 2:37 pm on July 14, 2010 Permalink | Reply

      Thanks zcorpan for your advice … i have recoded my class, now it works with the new Firefox 4 Beta too.

    • deekobraz 9:15 pm on July 16, 2010 Permalink | Reply

      it was very interesting to read.
      I want to quote your post in my blog. It can?
      And you et an account on Twitter?

    • skybinary 2:18 pm on July 26, 2010 Permalink | Reply

      Hey, nice introduction to websockets thanks :)

      I have successfully implemented some examples but they only work from localhost.
      How can i tell apache/php to allow socket connections beyond localhost?

    • jsnoob 10:07 pm on July 28, 2010 Permalink | Reply

      I don’t understand the need for the eval:
      [ eval(‘var data = ‘ + msg.data + ‘;’); ]

      why can’t you just do a real var data = msg.data?

    • DerFichtl 10:23 pm on July 28, 2010 Permalink | Reply

      msg.data contains JSON as string … with eval i convert it to a real javascript object

    • deltaLeo 5:21 pm on September 13, 2010 Permalink | Reply

      Hi skybinary,

      Please ensure that the socket is not just listening for localhost calls.
      e.g., let’s say you are working with port 8181. Then if you type within a terminal ‘netstat -an | grep LISTEN’ and
      you see something like this ‘127.0.0.1:8181′ that’s the root of your problem.
      So if you want to permit any incoming connection you should do something like this:
      $webSocket = new WebSocketServer(“0.0.0.0″, 8181, ‘process’);

    • David 5:21 pm on October 13, 2010 Permalink | Reply

      opening two windows with the example doesn’t seem to work.
      The first Window works but the second one not.
      Is it required and possible to set any parameter for the concerned window?

    • David 5:32 pm on October 13, 2010 Permalink | Reply

      After reloading both Browser-Windows it works and I get both cursers shown while the active one is correctly changeable while the other one is passive.
      In a list on the pic the IPs (surely the same) and the cursors are shown.

      Question is:
      1) how are the windows divided by the script
      2) why both windows had to be reloaded and why in the beginning just reloading the 2nd window didn’t show any cursor?

    • DerFichtl 7:10 am on October 14, 2010 Permalink | Reply

      Hi David, which browser (+ version) do you use? If you try with one chrome-window and one chrome inkognito window it should work … or two different browsers.

    • Ldup 8:57 pm on November 14, 2010 Permalink | Reply

      Hello, very thanks you for this! work!
      But i’m too trying PHP WebSocket(http://code.google.com/p/phpwebsocket/) simple example(Chat) but don’t work and i’m get error: Error: INVALID_STATE_ERR: DOM Exception 11
      And status is: WebSocket – status 0

      Maybe know how to fix this ? :-)

      Thanks for this and Good Luck!

    • DerFichtl 12:39 am on November 15, 2010 Permalink | Reply

      Thanks Ldup for your question. I have nothing to do with this project, but i can see that the maintainer is working on the project and he usually answers questions very quick.

    • Yves 8:07 pm on December 17, 2010 Permalink | Reply

      Hi, i have a problem with a scripts that is almost the same as yours. The eval function of the very first message received from the server gives me an Unexpected token ILLEGAL error. But all the other messages after the first one work great. When I read the first message with a console.log(msg.data) there is absolutely nothing strange in this message. Is there something special with the first message sent by the server?

    • cyberbobjr 7:56 pm on January 7, 2011 Permalink | Reply

      Hi,
      i have the same problem as Yves : the first message sent by the server raise always a onerror event on the client, the others messages works fine after… really strange… (chrome version 8.0.552.224)
      Thank you

    • DerFichtl 1:54 pm on January 12, 2011 Permalink | Reply

      Thanks for the comments, i can reproduce the problem and a quickfix is to wrap the eval in a try/catch block. i will look into the problem later, there seems to be a “hidden” char in the response …

    • Macs 12:00 pm on January 20, 2011 Permalink | Reply

      Do you plan to ad “wss” feature?
      this is the only option working for me behind firewall, simple “ws” fail to connect

    • adailton 6:42 pm on January 23, 2011 Permalink | Reply

      an error is occurring on the server can not answer the socket.

      php_exif.dll disabled the dll file that was giving error zend parameter in the library.

      I am using windows xp and windowdows 7 the same error.

      I’m from Brazil my net is networked to another pc

      image the error : http://img218.imageshack.us/i/imagemyj.gif/

    • adailton 6:48 pm on January 25, 2011 Permalink | Reply

      solve the problems agora ta All ok

      thanks for posting can clear my doubts valew old ^ ^

    • adailton 6:21 pm on February 26, 2011 Permalink | Reply

      thanks for posting this beautiful work.
      is being dealt a new server database that connects with
      javascript
      his name is jwebsocket a very good api
      to be compatible with Internet Explorer 6,7,8,9.

      http://jwebsocket.org/

    • DigitalLife 12:41 pm on March 6, 2011 Permalink | Reply

      How does this work? From the little I know about php the script gets called each time a browser opens an page. I understand that the server.php calls run so it doesn’t return like simple php scripts, but why aren’t there server instances for every user calling this script? Is it that the “require_once” makes only the first call of the script work and the other silently fail so there is only one server object? I don’t understand why there are not many WebSocketServer objects with each having only 1 client.
      (Sorry for my bad english, I’m out of training)

      • DerFichtl 9:57 pm on March 15, 2011 Permalink | Reply

        that is not a”typical” php-script which is opened in the browser via http … its a command line script, you can run it for example under linux oder mac osx via “php -q server.php” (if php is installed on the computer) … in this script is a endless-loop, so it runs until it is stopped with Crtl-C … hope that helps :)

    • Edska 3:58 pm on March 11, 2011 Permalink | Reply

      I have problem with this function – private function wrap($msg=””) { return chr(0).$msg.chr(255); }

      I get all info and at the end is this char – ÿ which is chr(255).
      Therefore at the client side I get error – “Invalid char”. If I remove “chr(255)” char “ÿ” is removed, but client side doesn’t work either.

    • Roy 6:59 pm on March 16, 2011 Permalink | Reply

      Hey, i’m tryng to get this to work.
      It still doesnt, and the reason is that crappy ‘hidden character’ that prevents json to be effectively interpreted, thus not appearing in the reply itself.
      here is the discovery:
      http://stackoverflow.com/questions/4880273/character-in-front-of-websocket-message
      But not the solution.I’m still looking for a good one to implement, or a way to get rid of that piece.

    • Roy 7:30 pm on March 16, 2011 Permalink | Reply

      Found a solution: by js, just use the replace function of javascript example, assume msg is the string returned by websocket.message function

      msg = $.parseJSON(msg.data.replace(”, ”));

      or, without jquery:

      msg = JSON.parse(msg.data.replace(”, ”));

      Hope someone will find this helpful to someone.

    • Roy 7:32 pm on March 16, 2011 Permalink | Reply

      Sorry, but the ascii code got interpreted.
      Between the first ” in the code, insert
      0
      without the space between, it will work, giving back your Json content.

    • elennaro 9:39 pm on April 9, 2011 Permalink | Reply

      Fixed memory leak on message quantity:

      Class WebsocketChatMessage {

      ….
      // Added destructor
      public function __destruct() {
      echo “menya stiraut ” . $this->text . “n”;
      unset($this->text);
      unset($this->username);
      unset($this->timestamp);
      }
      // End of added destructor

      ….

      }

      and in

      Class WebsocketChat {


      //added message limit
      private $maxmessage = 10;
      //End of changes in variables

      ….
      if ($msg->action == ‘chat’) {
      $text = filter_var($msg->text, FILTER_SANITIZE_STRING);
      $lastMessage = new WebsocketChatMessage($user->data[‘username’], $text . ” memory state ” . memory_get_usage(), time());

      $user->data[‘message’][] = $this->messages[] = &$lastMessage;

      //Begin of cleaning Checking if messages is too much

      if (count($this->messages) > $this->maxmessage) {
      //Cleaning old messages
      array_splice($this->messages, 0, 1);
      array_splice($user->data[‘message’], 0, 1);
      }
      //End of Cleaning
      }
      }
      }

      now the memory usage is clean and correct the script will live!

    • elennaro 9:42 pm on April 9, 2011 Permalink | Reply

      now who can help me with wss?
      i mean SSL for web stocket workaround.

    • Sanjeev 12:18 pm on May 25, 2011 Permalink | Reply

      I got ‘StartListening: Unable to bind socket – Address already in use.’ error when php -q server.php command execute in terminal.So web socket is not working.

      Please give me direction how can i test web socket properly working or not.

      Thank You

    • Digitalpassion 8:02 am on October 14, 2011 Permalink | Reply

      How much better is this than Ajax JSON callbacks?

    • Digitalpassion 8:02 am on October 14, 2011 Permalink | Reply

      How much better is this than Ajax JSON callbacks?

    • Fili Wiese 2:20 pm on November 1, 2011 Permalink | Reply

      Could you please update the code to support the new hybi-10 draft?

    • Fili Wiese 2:20 pm on November 1, 2011 Permalink | Reply

      Could you please update the code to support the new hybi-10 draft?

    • Arturs Birzgals 10:02 am on November 15, 2011 Permalink | Reply

      function hybi_decode($data){
      $bytes = $data;
      $data_length = “”;
      $mask = “”;
      $coded_data = “” ;
      $decoded_data = “”;
      $data_length = $bytes[1] & 127;
      if($data_length === 126){
      $mask = substr($bytes, 4, 8);
      $coded_data = substr($bytes, 8);
      }else if($data_length === 127){
      $mask = substr($bytes, 10, 14);
      $coded_data = substr($bytes, 14);
      }else{
      $mask = substr($bytes, 2, 6);
      $coded_data = substr($bytes, 6);
      }
      for($i=0;$i<strlen($coded_data);$i++){
      $decoded_data .= $coded_data[$i] ^ $mask[$i%4];
      }
      return $decoded_data;
      }

      function hybi_encode($data)
      {
      $frame = Array();
      $encoded = "";
      $frame[0] = 0x81;
      $data_length = strlen($data); if($data_length > 8;
      $frame[3] = $data_length & 0xFF;
      } for($i=0;$i<sizeof($frame);$i++){
      $encoded .= chr($frame[$i]);
      } $encoded .= $data;
      return $encoded;
      }

    • Arturs Birzgals 10:02 am on November 15, 2011 Permalink | Reply

      function hybi_decode($data){
      $bytes = $data;
      $data_length = “”;
      $mask = “”;
      $coded_data = “” ;
      $decoded_data = “”;
      $data_length = $bytes[1] & 127;
      if($data_length === 126){
      $mask = substr($bytes, 4, 8);
      $coded_data = substr($bytes, 8);
      }else if($data_length === 127){
      $mask = substr($bytes, 10, 14);
      $coded_data = substr($bytes, 14);
      }else{
      $mask = substr($bytes, 2, 6);
      $coded_data = substr($bytes, 6);
      }
      for($i=0;$i<strlen($coded_data);$i++){
      $decoded_data .= $coded_data[$i] ^ $mask[$i%4];
      }
      return $decoded_data;
      }

      function hybi_encode($data)
      {
      $frame = Array();
      $encoded = "";
      $frame[0] = 0x81;
      $data_length = strlen($data); if($data_length > 8;
      $frame[3] = $data_length & 0xFF;
      } for($i=0;$i<sizeof($frame);$i++){
      $encoded .= chr($frame[$i]);
      } $encoded .= $data;
      return $encoded;
      }

    • Paromatt 7:36 pm on March 22, 2012 Permalink | Reply

      Hi
      Please anyone who knows post how to get the “New URL for Example” working.
      I love to see working things before troubleshooting it on my pc later.

      I love websockets!
      matt

    • Paromatt 7:36 pm on March 22, 2012 Permalink | Reply

      Hi
      Please anyone who knows post how to get the “New URL for Example” working.
      I love to see working things before troubleshooting it on my pc later.

      I love websockets!
      matt

    • Elbriga 12:31 am on January 27, 2013 Permalink | Reply

      source code not showing

    • m3ta 2:14 am on May 26, 2013 Permalink | Reply

      “rather good than”? Go lean some basic english, fucktard.

  • SproutCore Erfinder eröffnet HTML5-Firma 

    Der SproutCore Erfinder Charles Jolley verlässt Apple und gründet ein Unternehmen das sich mit der Entwicklung neuer Rich-Web Applikationen auf HTML5-basis beschäftigen wird.

    (More …)

    DerFichtl 7:39 am on July 9, 2010 Permalink
    Tags: , , , MobileMe, SproutCore   

     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel