Could not open socket error

Posted on 2012-04-07
Last Modified: 2012-08-13
If a user tries to submit a post on my website they encounter the error message 'Could not open socket'

The user is requested to enter in a CAPTCHA, I'm not sure if that's related.
Question by:Cosmic_Cake
  • 7
  • 5
  • 2
LVL 109

Expert Comment

by:Ray Paseur
ID: 37819215
If CAPTCHA is the issue, this article may help.

To have any hope of understanding the issue we would need to see the complete error messages, and we may need to see the code, too.  Please post the URL that shows the failure and give us instructions on how to reproduce the failure.

Thanks, ~Ray

Author Comment

ID: 37819236
Hi Ray,

Here is the URL

If you fill out this form it will reproduce the error message. The error message doesn't reveal much, just 'Could not open socket error'

I think I will have to post some php files on here.
LVL 12

Expert Comment

by:Patricia Siu-Lai Ho
ID: 37819347
Hi Cosmic_Cake,

Your form is in

Please check the file is right path and file in form action of your script

<form action="/post-a-story/" method="post">

Patricia / pslh
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!


Author Comment

ID: 37819415
I cannot find a 'post-a-story' page. I didn't develop the site. I'll keep looking.
LVL 12

Expert Comment

by:Patricia Siu-Lai Ho
ID: 37819425
Hi Cosmic_Cake

Now I inspect the element of your web page,

It is  stated in this line

<form action="/post-a-story/" method="post">

"/post-a-story/"  it is not specify any file to post to.  

So you get the error.

your web page is inside folder post-a-story/

if the destination file eg. destination.php is in the same folder, you just type

<form action="destination.php" method="post">

Otherwise, if it is in other folder

<form action="../otherfolder/destination.php" method="post">

or  subfolders

<form action="subfolder/destination.php" method="post">

Patricia / pslh

Author Comment

ID: 37819497
I think I located the file where the problem could be. See Below:

 Plugin Name: Anon Post
 Plugin URI:
 Description: This plugin allows anonymous users to write their own posts using special page. No access to wordpress panel is needed.
 Version: 1.3
 Author: Wojciech Langiewicz
 Author URI:

/* Copyright 2009  Wojciech Langiewicz  (email : wlang(dont spam me)
 * This script is relased under BSD license.

require_once ( ABSPATH . WPINC . '/registration.php' );

//------------------------- start of options section ---------------------------

 * You can change this options to suit you needs.
 * If you want to use reCAPTCHA you need to get API key,
 * for more information see:
 * then click: "Sign up Now!" or log into your account

$anonUserName = 'Anonymous'; // 'name' of anonymous user, don't have to exist
$category = array(1); //this array should contain IDs for categories you want anonymous post to be in, example: array(1,2,4). NOTE: create those categories first, and check their numbers

$captchaEnabled = true; // enable reCAPTCHA (set to: true/false), do not use ' or "
$publickey = '6Lfn18MSAAAAAIaXx1isTq_uCAsuTpT9LY-RICSj'; // enter your API keys here
$privatekey = '6Lfn18MSAAAAAMyD1u1ayJoBAhxFIEj1-mywB1_4';
$enableComments = true; // true if you want to enable comments under posts created with plugin
$my_post_type = 'draft'; // avaiable options: 'publish' for posts to be published directly
                                    // 'draft' if you want to validate posts (by admin for example), post will appear as draft
$enable_css = false;      // set to true/false if you want css or not (css can be edited at the end of this file)
$display_content_after_post_created = true; // set to true/false if you want to show content of page displayed above the form after post is sucessfully created on confirmation page
$use_anonComment = false; // set to true/false if you want to use Anonymous Comment plugin to allow users to comment posts creted with this plugin to be anonymously commented, remember about installing this plugin first

// ---------- end of options, DO NOT CHANGE CODE BELOW THIS LINE ------------


function addAnonContent(){
      global $wp_query;
      global $captchaEnabled;
      global $publickey, $enable_css, $display_content_after_post_created;
      $form = "<br>";
      $this_post_id = $wp_query->post->ID;

      if(get_post_meta($this_post_id, 'anonPost', true) == 'true'){
            //add css:
                  $form .= add_css();

                  $form .= enteredByPOST();
                  $form .= displayFormStart();
                        $form .= '<center>';
                        $form .= recaptcha_get_html($publickey);
                        $form .= '</center>';
                  $form .= displayFormEnd();
            return get_the_content();

            return get_the_content().$form;
            return $form;
      //this should not happen
      //return get_the_content();

function enteredByPOST(){
      global $captchaEnabled;
      global $privatekey, $publickey;
      global $anonUserName, $category, $enableComments, $my_post_type;
      $to_return = '';

      if ((!$captchaEnabled) || recaptcha_check_answer($privatekey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'])->is_valid) {
            //check if user exists, if not, add this user
                   $user_id = get_profile( 'ID', $anonUserName );
                  $user_id = wp_create_user($anonUserName, wp_generate_password(20, false), '' );

             $my_post = array(
                   'post_title' => $_POST['Title'],
                   'post_content' => $_POST['Message'],
                   'post_status' => $my_post_type,
                   'post_author' => $user_id,
                   'post_category' => $category,
             //this thing enables normal comments only when comments are open and using Anon Comment is turned off
                   'comment_status' => (($enableComments && !$use_anonComment)  ? 'open' : 'closed'),
                   'ping_status' => 'closed'
            // Insert the post into the database
            $post_id = wp_insert_post( $my_post );
            if($post_id === 0){
                  $to_return .= 'error adding post';
                  //add meta tag, so AnonComment could add its comment field
                        add_post_meta($post_id, 'AnonComment', 'true', true);
                  //display new post link
                  //mod_rewrite will work with normal url's, like ?p=123
                  $urlArray = explode('?', $_SERVER['REQUEST_URI']);
                  $url = $urlArray[0];
                  $to_return .= 'post sucessfully added to database, post page: <a href='.$url.'?p='.$post_id.'>is here</a>';
            //error validating captcha
            $error = $resp->error;
            $to_return .= $error;
            $to_return .= 'reCAPTCHA validation failed, try again';
            $to_return .= displayFormStart($_POST['Title'], $_POST['Message']);
            $to_return .= recaptcha_get_html($publickey);
            $to_return .= displayFormEnd();
      return $to_return;

function displayFormStart($title = '', $message = ''){
      $form =<<< FORMSTART
<form action="{$_SERVER['REQUEST_URI']}" method="post">
Post title:<br><input type="text" name="Title" value="{$title}" size="40" maxlength="200"><br>
Your message:<br><textarea name="Message" cols=50 rows=20>{$message}</textarea><br>
      return $form;

function displayFormEnd(){
      $form_end =<<< FORMEND
<input type="submit" name="submit" value="Submit">
      return $form_end;

function add_css(){
      $css =<<< CSS
      <style type="text/css">
      form {
            align: center;
      textarea {
            background-color: white;
            color: black;
            align: center;
      return $css;

add_action('the_content', 'addAnonContent');
LVL 109

Accepted Solution

Ray Paseur earned 500 total points
ID: 37819508
Here is the response page.  It looks like the programmer put in something like die('Could not open socket');
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" dir="ltr" lang="en-US">
<head profile="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Overheard in Dublin -   Post a story</title>

<link rel="stylesheet" href="" type="text/css" media="screen" />

<style type='text/css' media='screen'>body {
	font-family: Verdana, Arial, Times New Roman, sans-serif;
	font-size: 75%;

h1, h2, h3, h4, h5, h6 {
   font-family: Lucida Grande, Verdana, Tahoma, Trebuchet MS!important;

#rotateimg { height: 200px!important; }</style>

<!--[if !IE]>deleted this if you want the indexing for archives<![endif]-->

<link rel="alternate" type="application/rss+xml" title="Overheard in Dublin RSS Feed" href="" />
<link rel="pingback" href="" />

<link rel="alternate" type="application/rss+xml" title="Overheard in Dublin &raquo; Post a story Comments Feed" href="" />
<link rel='stylesheet' id='A2A_SHARE_SAVE-css'  href='' type='text/css' media='all' />
<link rel='stylesheet' id='wdfb_style-css'  href='' type='text/css' media='all' />
<script type='text/javascript' src=''></script>
<script type='text/javascript' src=''></script>
<script type='text/javascript' src=''></script>
<script type='text/javascript' src=''></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="" /> 
<link rel='index' title='Overheard in Dublin' href='' />
<link rel='canonical' href='' />

<script type="text/javascript"><!--
var a2a_config=a2a_config||{},wpa2a={done:false,html_done:false,script_ready:false,script_load:function(){var a=document.createElement('script'),s=document.getElementsByTagName('script')[0];a.type='text/javascript';a.async=true;a.src='';s.parentNode.insertBefore(a,s);wpa2a.script_load=function(){};},script_onready:function(){if(a2a.type=='page'){wpa2a.script_ready=true;if(wpa2a.html_done)wpa2a.init();}},init:function(){for(var i=0,el,target,targets=wpa2a.targets,length=targets.length;i<length;i++){el=document.getElementById('wpa2a_'+(i+1));target=targets[i];a2a_config.linkname=target.title;a2a_config.linkurl=target.url;if(el)a2a.init('page',{target:el});wpa2a.done=true;}}};a2a_config.tracking_callback=['ready',wpa2a.script_onready];
<script type="text/javascript">var _wdfb_ajaxurl="";</script><script type="text/javascript">var _wdfb_root_url="";</script>Could not open socket

Open in new window

Here is what I would do.  Since this site appears to be built on a WordPress platform, it is probably 100% PHP.  I would get a code scanner like Textpad "find in files" functionality and scan all of the scripts for the case-sensitive string Could not open socket and with each script that contains that string, I would look for conditional code - something testing a return value, perhaps from the fsockopen() function.  I am slightly suspicious of the reCaptcha implementation, but that's just an instinctive reaction.  Once you find the string in the script or scripts, we can dig a little deeper since we will be able to see the code that is in play.
LVL 109

Expert Comment

by:Ray Paseur
ID: 37819511
Ahh - just saw your post, I'll take a look at that now.
LVL 109

Expert Comment

by:Ray Paseur
ID: 37819535
Here is an additional symptom to consider while you're looking for the string "Could not open socket."  If you do not put anything into the reCaptcha box,  the site says that Captcha validation failed.  If you put something in, right or wrong, the site says "Could not open socket."

Author Comment

ID: 37819671
" I am slightly suspicious of the reCaptcha implementation" - I agree

I think it also slows down user input.

Thanks for your suggestion, I will use Textpad and do a scan. Let's see if anything comes up.
LVL 109

Expert Comment

by:Ray Paseur
ID: 37819679
10-4.  Post back here with the script that contains the culprit.  And if you want something that is effective but more client-friendly than reCaptcha see this article.

Best, ~Ray

Author Comment

ID: 37819777
I found it. It's in a files called recaptchalib.php.

Below is a segment. For the moment I would like to remove the captcha option on the website as all posts are monitored and hen put live, so no damage would be done.

 * Submits an HTTP POST to a reCAPTCHA server
 * @param string $host
 * @param string $path
 * @param array $data
 * @param int port
 * @return array response
function _recaptcha_http_post($host, $path, $data, $port = 80) {

        $req = _recaptcha_qsencode ($data);

        $http_request  = "POST $path HTTP/1.0\r\n";
        $http_request .= "Host: $host\r\n";
        $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
        $http_request .= "Content-Length: " . strlen($req) . "\r\n";
        $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
        $http_request .= "\r\n";
        $http_request .= $req;

        $response = '';
        if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
                die ('Could not open socket');

        fwrite($fs, $http_request);

        while ( !feof($fs) )
                $response .= fgets($fs, 1160); // One TCP-IP packet
        $response = explode("\r\n\r\n", $response, 2);

        return $response;

Author Comment

ID: 37819908
I finally got rid of the horrible CAPTCHA and the posting is working now.

I changed true to false

$captchaEnabled = false; // enable reCAPTCHA (set to: true/false), do not use ' or "

Author Closing Comment

ID: 37820190
Very practical answers, thank you.

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Creating and Managing Databases with phpMyAdmin in cPanel.
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question