Click here to Skip to main content
15,903,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am trying to use an API offered by a website in PHP however I am facing problems. I can use the API very fine in C#. The following code in C3 works:

C#
string result = wb.UploadString(apiurl, "POST", "Hello, where do you live");
            MessageBox.Show(result);


The above code works perfectly find. But I want to make the same code in PHP. In PHP I am utilizing HTTP POST from PHP without CURL , I have tried with CURL as well but it just doesn't work, I do not get anything returned from the API.

The following is the PHP code:

PHP
function do_post_request($url, $data, $optional_headers = null)
{
    $params = array('http' => array('method' => 'POST','content' => $data));

    if ($optional_headers !== null) 
    {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    
    echo $ctx['content'];
                                                   
    $fp = @fopen($url, 'rb', false, $ctx);          
    
    if (!$fp) 
    {              
        throw new Exception("Problem with $url, $php_errormsg");
    }
         
    $response = @stream_get_contents($fp);          
    
    if ($response === false) 
    {
        throw new Exception("Problem reading data from $url, $php_errormsg");
    }  
    return $response;
}

$result = do_post_request($apiurl,$txtstr);
echo $result;


I get no result, Neither do I get any error.

The API has strict condition that:
you should put your content as the POST DATA, and don’t write any other content or parameters in the POST DATA

Any one have any idea and can help me?

Regards
Posted

1 solution

Get Wireshark on the job. Record the messages exchanged with your C# code (that works), and do the same with your PHP (that doesn't). Find out what's different, then work from there. My wild guess is a missing header in the request. Oh, and read the PHP Manual carefully.

Peter
 
Share this answer
 
Comments
dahacked1 16-Aug-11 10:43am    
Thanks, Your suggestion indirectly solved the problem. I ran Wireshark on c# and then to check php on my own PC I installed webserver on my PC and I saw the script worked perfectly fine. I have been wasting my time useless for the whole day.

I guess the API ports are blocked on my hosting company, Have emailed them.

Regards

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900