C++ and PHP [Solved]

Posts 1–15 of 16 · Page 1 of 2
C++ and PHP [Solved]
Ok, so i have been doing research on this topic for a long time and haven't gotten any results. I have a website set up and it has php installed and all I want to do is send my php script on the site some information like login info or something, and then have the site return a response to my c++ program. The issue is that idk how to properly send the info over the socket using the http protocol. And then I don't know how to return a response from a php script to a connection (aka my c++ app). Some help is greatly appreciated. Thanks, and hopefully this thread will get more attention to this part of the site cuz c++ is dead for some reason.
For this kind of thing Its where I would actually use Webservices .. =\ Give it a look btw

.NET has a generic one, but since you are using cpp, you should find a couple of other libs around web.
Isn't it just a POST to give the info to the php file from my cpp? So couldn't I just open a socket to the website on port 80 and then post the info? After that i want my php file on the site to process that info. That's what I am trying to do.
Quote Originally Posted by 258456 View Post
Isn't it just a POST to give the info to the php file from my cpp? So couldn't I just open a socket to the website on port 80 and then post the info? After that i want my php file on the site to process that info. That's what I am trying to do.
No, it's not like that. You'll have to use Web Requests for posting and retrieving info. As Brinuz suggested, use 3rd party libraries for that.
Why do you want to use the http side anyway? Php supports sockets, so if you don't want to go through the hassle of posting your information through http you can just open a socket through php and dump your data there.
Quote Originally Posted by .::SCHiM::. View Post
Why do you want to use the http side anyway? Php supports sockets, so if you don't want to go through the hassle of posting your information through http you can just open a socket through php and dump your data there.
The issue is that my client will be a c++ program not a php, so if I am not horribly mistaken i don't think that a c++ app could conncect to a php server.

---------- Post added at 07:58 PM ---------- Previous post was at 06:45 PM ----------

EDIT:

It turns out i can do that, thanks schim, but I posted the code to make a socket in my website on 000webhost.com and it doesn't give me permission? Probably @Hassan can help me out since he has experience with this website host

Code:




    Normal textarea CodePress 

File: /php.php
   

Status: Saved on 2012-01-25 19:50:58 using mode FTP_ASCII




<HTML>

<HEAD>



</HEAD>


<?

	$host = "31.170.160.86";
	$port = 5;
	set_time_limit(0);

	$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Couldn't Create Socket");
	$result = socket_bind($socket, $host, $port) or die("Couldn't bind to socket");
	$result = socket_listen($socket, 3) or die("Couldn't listen to connection");
	
	$spawn = socket_accept($socket) or die("Couldn't accept connection");
	
	$output = "Thank God, your first PHP Socket Server";
	socket_write($spawn, $output, strlen($output)) or die("Couldn't Write message");

	socket_close($spawn);
	socket_close($socket);

?>


</body>

</HTML>
I don't know in what scenario you are going to use it but here's an alternative. Basically, you use PHP's Execution Operators to execute a c++ program. You can also pass optional parameters so c++ can process them and return something useful. Here's how you can pass data to PHP and from PHP to C++:

Create a simple c++ program that uses a std::cout statement to print something:

Code:
#include<iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
	if(argv[1]=="DoSomething") //Parameter passed. Process it and return it using std::cout
	{
		//Do some processing on the arguments passed here...
		string ReturnProcessedOutput = "Thank God, I am not an atheist !";
		cout << ReturnProcessedOutput; //Return it to PHP
	}
	else
	{
		cout << "Some raw data for PHP script..."; //Return to PHP
	}
	return 0;
}
Build and save the executable in the same directory where you are going to save your PHP script.

Next, create a new PHP file and store a simple script like this in it:

Code:
<?php
    $Parameter1 = "DoSomething"; //Our first parameter
    $output=`PHPTesting.exe $Parameter1`; //Execute PHPTesting.exe (name of my cpp exe) passing our first parameter.
    echo "<strong>$output</strong>"; //Output what you recieved from your cpp program (output variable).
?>
Now when you will call your php script, it will pass Parameter1 to the c++ program. C++ program can then process it and return something. This way you can move data back and forth.
I think the problem is that your webhost does not allow you to open a socket, it'd be weird if they'd let you. What you really need is a dedicated host that you can install and configure the way to you want.
I was messing with $_GET yestarday and it turns out you can enter the value of a variable you want to process into the URL like: "site.com/php.php?variable=bla" so that's probably what i am going to do by mistake a socket in c++ connected to the site on port 80 and then it will make a GET request from the site and then the php file will just "echo "response"; " to my c++ app which i will recover with recv(). Do you guys think it will work?
There's a shit-tonne of literature on the subject of sending HTTP requests. Personally I'd just send a GET request to the server and use PHP's $_GET superglobal to set your variables (be sure to URLencode any variables you're sending to the server)

Otherwise, the POST code isn't very complex either. After you send the request to the server you just read back the response and done.
so basically would this be the form?

(I am doing it in telnet just to test before i use winsock in c++)

o www.site.com 80

GET /php.php?name=bla HTTP/1.1
HOST: Internet Explorer 8

Would this be the form (not so sure about host, i think i have it wrong)?
Quote Originally Posted by 258456 View Post
so basically would this be the form?

(I am doing it in telnet just to test before i use winsock in c++)

o www.site.com 80

GET /php.php?name=bla HTTP/1.1
HOST: Internet Explorer 8

Would this be the form (not so sure about host, i think i have it wrong)?

Here's a rough outline of a GET request builder (sorry, it's ugly as fuck. Not used to string manip in C so yeah, things got messeh.)

Code:
typedef struct _http_header
{
  char *header;
  char *value;
} HTTP_HEADER;

static int strpos(const char *haystack, const char *needle)
{
  const char *ind = strstr(haystack, needle);
  return (ind != NULL ? (int)(ind - haystack) : -1);
}

static char *substr(const char *subject, int start, int len)
{
  char *substring = NULL;
  if (start >= 0 && start < (int)strlen(subject))
  {
    len = ((start + len) > (int)strlen(subject) ? (int)(strlen(subject) - start) : len);
    substring = (char*)calloc(len + 1, sizeof(char));
    for(int i = 0; i < len; i++)
      substring[i] = subject[start + i];
  }
  return substring;
}

static char* CreateHttpGetString(char *url, HTTP_HEADER *headers, int nheaders)
{
  const char *crlf = "\r\n";
  const size_t szlf = 2;
  char *request = NULL;

  if (strncmp(url, "http://", strlen("http://")) == 0)
    url += strlen("http://");
    
  int fslash = strpos(url, "/");
  if (fslash == -1)
    fslash = (int)(strlen(url));

  char *domain = substr(url, 0, fslash);
  char *relpath = substr(url, fslash, (int)strlen(url));
  
  if (domain != NULL)
  {
    if (relpath == NULL) 
      relpath = "/"; //no relative path, get the base path.

    //gets the size of the request before building it.
    size_t szRequest = strlen("GET  HTTP/1.1") + strlen(relpath) + (3 * szlf) + strlen("Host: ") + strlen(domain);
    for(int i = 0; i < nheaders; i++) //loop through the headers to get their lengths (CRLFheader: value)
      szRequest += szlf + strlen(headers[i].header) + 2 + strlen(headers[i].value);

    request = (char*)calloc(szRequest + 1, sizeof(char)); //allocate some memory for the request string.
    sprintf(request, "GET %s HTTP/1.1%sHost: %s", relpath, crlf, domain); //copy over the basics of the request.

    for(int i = 0; i < nheaders; i++) //loop through the headers and append each one.
    {
      strcat(request, crlf);
      strcat(request, headers[i].header);
      strcat(request, ": ");
      strcat(request, headers[i].value);
    }
    strcat(strcat(request, crlf), crlf);
  }

  if (strcmp(relpath, "/") != 0) //if there was no original relpath, we set the path to "/" which is constant and cannot be freed.
    free(relpath);
  free(domain);
  return request;
}
So for example:
Code:
  HTTP_HEADER headers[5];
  headers[0].header = "User-Agent"; headers[0].value = "Mozilla/5.0 Firefox/3.6.12";
  headers[1].header = "Accept"; headers[1].value = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  headers[2].header = "Accept-Language"; headers[2].value = "en-us,en;q=0.5";
  headers[3].header = "Accept-Encoding"; headers[3].value = "deflate";
  headers[4].header = "Accept-Charset"; headers[4].value = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";

  printf("%s", CreateHttpGetString("http://www.mpgh.net/forum/31-c-c-programming/419473-c-php.html", headers, 5));
Would print the following to the console:
Code:
GET /forum/31-c-c-programming/419473-c-php.html HTTP/1.1
Host: www.mpgh.net
User-Agent: Mozilla/5.0 Firefox/3.6.12
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
@Jason

This is a little less work I think:

EDIT: never mind, I wasn't looking at your code close enough.

Code:
void SendGet( char* Host, char* ParamName, char* Param ){

char* Request = new char[ BufferSize ];
// the rfc only requires you have the Host header and (obiously) the request itself I believe. 
sprintf( Request, "GET /php.php?%s=%s HTTP/1.1\r\n\HOST: %s\r\n\r\n", ParamName, Param, Host);

//now request holds the GET request with all headers and stuff...
}
Thanks so much guys, I greatly appreciate your guys' effort to help me, it's really touching.

Sorry for the frutiness i just had to say it hehe,

Anyways Here is how i fixed it:

The host was just wrong, i was writing a different website for my host and that was stupid. Thanks so much guys.
Posts 1–15 of 16 · Page 1 of 2

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us