How to send text/html data to a browser - php

Hi i asked a question before here : how-can-i-integrate-php-with-my-http-server
i programmed a personal web server and i tried to integrate it with PHP using the PHP-CGI , i run a system command ("PHP-CGI.exe path/to/php/script.php getvar=getValue") and i send the outputs to the browser , everything works cool except that the output shows in the browser as plain/text page like :
X-Powered-By: PHP/5.4.14 Set-Cookie:
PHPSESSID=9rurvleetdkucms44i4cac9a14; path=/ Expires: Thu, 19 Nov 1981
08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate,
post-check=0, pre-check=0 Pragma: no-cache Content-type: text/html
ID value = AAAA< /h1>
here's the PHP script :
<?php
session_start();
echo "< h1>ID value = < /h1>". $_GET['id'];
?>
and the command i used : php-cgi html_doc/index.php id=AAAA
my question is : why does it send data in plain/text instead of text/html i want?!
and why does it show the header information in the browser like above ?!
Thank you all in advance!
(Notice : i seperated < h1>so it can be appeared!)

this is a BASIC html_to_browser using C sockets
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <strings.h>
int main(int argc, char *argv[]){
char *reply =
"HTTP/1.1 200 OK\n"
"Date: Thu, 19 Feb 2009 12:27:04 GMT\n"
"Server: Apache/2.2.3\n"
"Last-Modified: Wed, 18 Jun 2003 16:05:58 GMT\n"
"ETag: \"56d-9989200-1132c580\"\n"
"Content-Type: text/html\n"
"Content-Length:156\n"
"Accept-Ranges: bytes\n"
"Connection: close\n"
"\n"
"o EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE GRANDE ___2 \n \r\n\r\n"
"THIS IS A HTTP RESPONSE TO BROWSER \n USING C SOCKETS _ \\_t 5 \n \r\n\r\n"
"\r\n\r\n \r\n\r\n \r\n\r\nNOT FINISHED AA _3\r\n\r\n";
int sd = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sd,(struct sockaddr*)&addr,sizeof(addr))!=0){
printf("bind error\n");
}
if (listen(sd, 16)!=0){
printf("listen error\n");
}
while(1){
socklen_t size = sizeof(addr);
int client = accept(sd,(struct sockaddr*)&addr, &size);
if (client > 0)
{
printf("client connected\n");
/*send(client, reply, sizeof(reply), 0);*/
send(client, reply, strlen(reply)+1, 0);
}
}
return 0;
}
compile + execute on a console with sudo(to allow port 80) OR change the addr.sin_port to something bigger than '1024'
...ctrl+z to finish

In php you would do header("Content-Type: text/html"); to set a default change the default_mimetype directive in php.INI to the correct mime type.

Related

I am reading a stream of bytes from server using esp8266 by running a .php script on the server but i do not get the correct data

This is the GET request & response which is sent/received to/from the server
Connecting to MD1
.......
WiFi connected
IP address:
192.168.43.135
connecting to smbbitumen.com
Requesting URL: http://www.smbbitumen.com/smbbitumen.com/myftp/API/Users/read.php
HTTP/1.1 200 OK
Date: Sat, 06 Jun 2020 03:00:17 GMT
Server: nginx/1.17.9
Content-Type: text/html
X-Powered-By: PHP/5.4.45
Vary: Accept-Encoding
Accept-Ranges: none
X-Server-Cache: true
X-Proxy-Cache: MISS
Transfer-Encoding: chunked
48
1111000019:30:0020:30:0019:40:0020:40:0019:45:0020:45:0019:50:0020:50:00
0
closing connection
1111000019:30:0020:30:0019:40:0020:40:0019:45:0020:45:0019:50:0020:50:00 -> This is the stream of data which i am reading into esp but it does not get updated in realtime, it remains same. Any ideas, ehy this is happening.....
Also one more thing, when i run the above php link in browser,everytime it returns correct data.
php script which i am using to read data
<?php
clearstatcache();
$myfile = fopen("TEST.txt", "r");
if($myFile === FALSE)
echo "ERROR";
else
echo fread($myfile,filesize("TEST.txt"));
fclose($myfile);
?>
ESP8266 code for connecting to server and running the above script using GET request
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WiFiClientSecure.h>
#include <Ticker.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
#include<ESP8266WiFiMulti.h>
const char *ssid = "***";
const char *password = "******";
HTTPClient myhttp;
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid,password);
while(WiFi.status()!= WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting...");
}
}
void loop()
{
if(WiFi.status() == WL_CONNECTED)
{
myhttp.begin("http://www.smbbitumen.com/smbbitumen.com/myftp/API/Users/read.php");
int httpCode = myhttp.GET();
if(httpCode > 0)
{
String payload = myhttp.getString();
Serial.println(myhttp.getString());
}
httpCode = 0;
myhttp.end();
}
delay(2000);
}
The issue is related to cache. Change the code in read.php as below
<?php
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
clearstatcache();
$myfile = fopen("TEST.txt", "r");
if($myFile === FALSE)
echo "ERROR";
else
echo fread($myfile,filesize("TEST.txt"));
fclose($myfile);
clearstatcache();
?>
The similar thing can be done by changing the settings for cache on the server.

call php-cgi from c++ with REQUEST_METHOD="POST"

i am want to convert a shell script to c++. Please help me.
this is my shell script file. it worked well, but when i move to c++, it is not work correctly
test.sh
#!/bin/sh
REQUEST_DATA="var_1=val_1&var_2=val_2"
export GATEWAY_INTERFACE="CGI/1.1"
export SERVER_PROTOCOL="HTTP/1.1"
export QUERY_STRING="test=querystring"
export REDIRECT_STATUS="200"
export SCRIPT_FILENAME="/test.php"
export REQUEST_METHOD="POST"
export CONTENT_LENGTH=${#REQUEST_DATA}
export CONTENT_TYPE="application/x-www-form-urlencoded;charset=utf-8"
echo $REQUEST_DATA | /usr/bin/php-cgi
and test.php is
<?php
print_r($_POST);
?>
when i run sh test.sh, i got response:
X-Powered-By: PHP/5.6.13
Set-Cookie: PHPSESSID=f4ntbasno365p08tf94drl7026; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/html; charset=UTF-8
Array
(
[var_1] => val_1
[var_2] => val_2
)
When i am trying to convert this to c++
char **sysCline = NULL;
char **sysEnv = NULL;
std::string sData = "var_1=val_1&var_2=val_2";
std::vector<std::string> aArgs;
aArgs.push_back("/usr/bin/php-cgi");
aArgs.push_back("/test.php");
sysCline = new char*[aArgs.size() + 1];
for (i=0; i<aArgs.size(); i++) {
sysCline[i] = new char[aArgs[i].size()+1];
::strncpy(sysCline[i], aArgs[i].c_str(), aArgs[i].size()+1);
}
sysCline[aArgs.size()] = NULL;
// Construct environment
std::vector<std::string> aEnv;
aEnv.push_back("GATEWAY_INTERFACE=CGI/1.1");
aEnv.push_back("SERVER_PROTOCOL=HTTP/1.1");
aEnv.push_back("QUERY_STRING=test=querystring");
aEnv.push_back("REDIRECT_STATUS=200");
aEnv.push_back("REQUEST_METHOD=POST");
aEnv.push_back("CONTENT_TYPE=application/x-www-form-urlencoded;charset=utf-8");
aEnv.push_back("SCRIPT_FILENAME=/test.php");
aEnv.push_back("CONTENT_LENGTH="+ to_string(sData.length()) );
sysEnv = new char*[aEnv.size() + 1];
for (i=0; i<aEnv.size(); i++) {
sysEnv[i] = new char[aEnv[i].size()+1];
::strncpy(sysEnv[i], aEnv[i].c_str(), aEnv[i].size() + 1);
}
sysEnv[aEnv.size()] = NULL;
execve(sysCline[0], sysCline, sysEnv);
When run, i got response:
X-Powered-By: PHP/5.6.13
Set-Cookie: PHPSESSID=2vdp947ghlg0h8st66c9ll3vt6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/html; charset=UTF-8
Array
(
)
It should be same response with sh test.sh
You need to create a pipe in order to pass the POST data to the script:
char *echocmd[] = {"echo", "var_1=val_1&var_2=val_2", NULL};
int pp[2];
int pid, res;
pipe(pp);
if ((pid = fork()) != 0)
{
dup2(pp[1], 1);
close(pp[0]);
res = execvp(echocmd[0], echocmd);
}
else
{
dup2(pp[0], 0);
close(pp[1]);
res = execve(sysCline[0], sysCline, sysEnv);
}
close(pp[1]);
return res;
Thank you #yacc, I found a way, this is demo the way i used
http://cpp.sh/4wgu
The idea is: we will fork current process, use 2 pipes: 1 for stdin and 1 for stdout. in parent process, we will use a pipe to write string to stdin of child process, and in child process, we will dum a pipe for output from child's stdout. with this way, we can write to stdin and read stdout of child process from parent process

fine-uploader can't read iframe response with IE7

I'm using the jquery.fineuploader-3.7.0 and Code igniter framework for the server side.
My js code :
$('#manual-fine-uploader').fineUploader({
request : { endpoint: 'declaration/uploadfile'},
autoUpload : false,
template : '<div class="qq-uploader span12">' +
' <pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
' <div class="qq-upload-button " style="width: auto;">{uploadButtonText}</div>' +
' <span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
' <ul id="qq-upload-list" class="qq-upload-list" style="margin-top:10px; text-align:center;"><li></li></ul>' +
' <ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
'</div>',
fileTemplate : '<li>' +
' <div class="qq-progress-bar"></div>' +
' <span class="qq-upload-spinner"></span>' +
' <span class="qq-upload-finished"></span>' +
' <span class="qq-upload-file"></span>' +
' <span class="qq-upload-size"></span>' +
' <a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
' <a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
' <a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
' <span class="qq-upload-status-text">{statusText}</span>' +
'</li>',
failedUploadTextDisplay : {
mode : 'custom',
maxChars : 1500,
responseProperty : 'error',
enableTooltip : true
},
text : {
uploadButton : '<color=#2E6E9E><b>Selectionnez le fichier à déposer</b></color>',
failUpload : 'Le chargement a échoué'
} });
$('#triggerUpload').click(function() {
$('#manual-fine-uploader').fineUploader('setParams', {'id_fait':$('#id_fait').attr('value') });
$('#manual-fine-uploader').fineUploader('uploadStoredFiles'); });
My server side response are :
>HTTP/1.0 200 OK
>Date: Fri, 26 Jul 2013 08:12:09 GMT
>Server: Apache/2.2.15 (CentOS)
>X-Powered-By: PHP/5.3.3
>Expires: Thu, 19 Nov 1981 08:52:00 GMT
>Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
>Pragma: no-cache
>Connection: close
>Content-Type: text/html; charset=UTF-8
content :
{"success":true,"file_inner":"<a href='pj\/'116810_116810_cimpa_insertion.xls' target='_blank'>116810_cimpa_insertion.xls<\/a>"}
Under FF, Chrome i have a sucess message on my web page (the green)
but under IE7 or IE8 i have a message who said in my debug bar console:
[FineUploader 3.7.0] Error when attempting to parse iframe upload response ([object Error])
[FineUploader 3.7.0] 'error' is not a valid property on the server response.
and web page error message(the red ).
But the upload are ok (the file are correctly on my server)
I'm a beginner under fine-uploader, could you help me to find where i have make an error please ?
code of the server side:
/**
* uploadfile
* #access public
* #return string
*/
public function uploadfile() {
$post['id_fait'] = $this->input->post('id_fait');
if ( empty($post['id_fait']) ) {
$return['error'] = 'ID_FAIT manquant';
return true;
}
else {
$_FILES['qqfile']['name'] = $post['id_fait']."_".$_FILES['qqfile']['name'];
$config['upload_path'] = DOCUMENT_PATH;
$config['max_size'] = UPLOAD_MAX_SIZE;
$config['overwrite'] = FALSE;
$config['allowed_types'] = ALLOWED_EXT;
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('qqfile')) { $return['error'] = $this->upload->error_msg[0]; }
else {
$data = $this->upload->data();
$post['fichier'] = $data['file_name'];
$insert = $this->db->insert('senla_faits_piece_jointe',$post);
$return['success'] = $insert;
$return['file_inner'] = "<a href='pj/'".$post['id_fait']."_".$data['file_name']."' target='_blank'>".$data['file_name']."</a>";
}
}
echo json_encode( $return, JSON_FORCE_OBJECT );
}
UPDATE :
After i make the change my server response :
HTTP/1.0 200 OK
Date: Fri, 26 Jul 2013 20:21:01 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 124
Connection: close
Content-Type: text/html; charset=UTF-8
and the content :
{"success":true,"file_inner":"<a href=\"pj\/116842_116842_brochure 12.pdf\" target=\"_blank\">116842_brochure 12.pdf<\/a>"}
I have always a red web message who said : upload fail (in french) and this message in my debug bar console :
[FineUploader 3.7.0] Error when attempting to parse iframe upload response ([object Error])
[FineUploader 3.7.0] 'error' is not a valid property on the server response.
Thank a lot for your help
Stéphane
Update 2 after change the content type, always the same problem :
The server response :
HTTP/1.0 200 OK
Date: Sat, 27 Jul 2013 20:14:38 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=7riosh2q9edldanjp9vtg4ili3; path=/
Set-Cookie: PHPSESSID=7riosh2q9edldanjp9vtg4ili3; path=/
Connection: close
Content-Type: text/plain; charset=UTF-8
The content :
{"success":true,"file_inner":"<a href=\"pj\/116841_116841_capture_portail_sonacotra.doc\" target=\"_blank\">116841_capture_portail_sonacotra.doc<\/a>"}
I think it's not a problem of content, perhaps it's a problem of IE who can't read the response send by the server across the iframe, but i don't know sufficiently the javascript to find the solution
UPDATE 29/07/2013 :
I have make a test :
If i delete my $return['file_inner']
And i keep only the sucess or error message then that's ok
My $return['file_inner'] are just here because user could be verify the document upload by clicking on the link. But it's not a very important fonction, i could delete it.
Perhaps i have forget something when they are severals attributes in my object "response". or perhaps fine uploader code wait only one attribut.
After having a closer look, there are a few odd properties of your JSON response.
I have very little professional experience with PHP, but I can say that your response content is not correct. You should probably be using json_encode to format your response content. Fine Uploader has an example PHP script that already does this. Perhaps you should have a look.
Either way, your response content should look like this:
{"success":"true","file_inner":"116841_capture_portail_sonacotra.doc"}
Solution by OP.
The solution are in the example php script, my error are to make a url in my object without the htmlspecialchars conversion. With this php code on the server side it's OK
/**
* uploadfile
* #access public
* #return string
*/
public function uploadfile() {
$post['id_fait'] = $this->input->post('id_fait');
if ( empty($post['id_fait']) ) {
$return['error'] = 'ID_FAIT manquant';
return true;
}
else {
$_FILES['qqfile']['name'] = $post['id_fait']."_".$_FILES['qqfile']['name'];
$config['upload_path'] = DOCUMENT_PATH;
$config['max_size'] = UPLOAD_MAX_SIZE;
$config['overwrite'] = FALSE;
$config['allowed_types'] = ALLOWED_EXT;
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('qqfile')) { $return['error'] = $this->upload->error_msg[0]; }
else {
$data = $this->upload->data();
$post['fichier'] = $data['file_name'];
$insert = $this->db->insert('senla_faits_piece_jointe',$post);
$return['success'] = $insert;
$return['file_inner'] = "".$data['file_name']."";
}
}
// log_askel($this->upload);
header('Content-type: text/plain');
echo htmlspecialchars(json_encode($return), ENT_NOQUOTES);
}

php picasa api show large image

Ok so far I have been able to show thumbnails from user/album using the google feed. Everything displays ok, except when I want to show the thumbnail image larger. I can't seem to get the large image to show, not sure what to use here..here's my code:
<?php
$user = '100483307985144997386';
$albumid = '5092093264124561713';
$picasaURL = "http://picasaweb.google.com/$user/";
$albumfeedURL = "http://picasaweb.google.com/data/feed/api/user/$user/albumid/$albumid";
$sxml_album = simplexml_load_file($albumfeedURL);
echo '<table cellpadding="3" cellspacing="3">';
echo "<tr>";
$i = 0;
foreach( $sxml_album->entry as $album_photo )
{
//$title = $album_photo->title;
$summary = $album_photo->summary;
// Write thumbnail to file
$media = $album_photo->children('http://search.yahoo.com/mrss/');
$thumbnail = $media->group->thumbnail[1];
$gphoto = $album_photo->children('http://schemas.google.com/photos/2007/');
$linkName = $gphoto->group->attributes()->{'url'};
// Direct address to thumbnail
$thumbAddy = $thumbnail->attributes()->{'url'};
if($i%4==0) { echo '</tr><tr>'; }
echo '<td style="width:90px; overflow:hidden; word-wrap:break-word; font-size:12px;">';
echo '<a class="fancybox-buttons" data-fancybox-group="button" href="'. $linkName . '"><img src="'. $thumbAddy . '" /></a>';
echo '<p>'. $summary . '</p></td>';
$i++;
}
echo '</tr></table>';
the feed/api for each photo contains 3 thumbs and a large picture which are accessible on the native http rest api in the following:
"media$thumbnail":[
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s72/DSC01612.JPG",
"height":72,
"width":48
},
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s144/DSC01612.JPG",
"height":144,
"width":96
},
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s288/DSC01612.JPG",
"height":288,
"width":192
}
],
LARGE ONE:
"media$group":{
"media$content":[
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/DSC01612.JPG",
"height":512,
"width":341,
"type":"image/jpeg",
"medium":"image"
}
similar reference
When coding clients to an underlying REST api it can often help to have a good grasp on the native protocol and what character streams ( request / response ) are on the wire. Then you adapt PHP/Curl to what is there in http protocol.
The google oauth playground is a great tool for testing the back and forth dialogs involved in development against any of the gdata apis ( including picasa )...
playground
here is the playground request code to get the thumbs and the large pic for a given album/photo...
GET //data/entry/api/user/rowntreerob/albumid/5682316071017984417/photoid/5682316083381958690?fields=media%3Agroup%2Fmedia%3Athumbnail%5B%40url%5D%2Cmedia%3Agroup%2Fmedia%3Acontent%5B%40url%5D&alt=json HTTP/1.1
Host: picasaweb.google.com
Authorization: OAuth ya29.AHES6ZT123y3Y5Cy3rILYg4Ah4q....
HTTP/1.1 200 OK
status: 200
gdata-version: 1.0
content-length: 756
x-xss-protection: 1; mode=block
content-location: https://picasaweb.google.com//data/entry/api/user/rowntreerob/albumid/5682316071017984417/photoid/5682316083381958690?fields=media%3Agroup%2Fmedia%3Athumbnail%5B%40url%5D%2Cmedia%3Agroup%2Fmedia%3Acontent%5B%40url%5D&alt=json
x-content-type-options: nosniff
set-cookie: _rtok=a1p2m3PiHFkc; Path=/; Secure; HttpOnly, S=photos_html=sX3EHuLxGEre_OMvR0LTPg; Domain=.google.com; Path=/; Secure; HttpOnly
expires: Wed, 16 May 2012 03:23:51 GMT
vary: Accept, X-GData-Authorization, GData-Version, Cookie
x-google-cache-control: remote-fetch
-content-encoding: gzip
server: GSE
last-modified: Fri, 06 Jan 2012 17:57:33 GMT
via: HTTP/1.1 GWA
cache-control: private, max-age=0, must-revalidate, no-transform
date: Wed, 16 May 2012 03:23:51 GMT
access-control-allow-origin: *
content-type: application/json; charset=UTF-8
x-frame-options: SAMEORIGIN
and the response to the above run thru a prettyprint...
"version":"1.0",
"encoding":"UTF-8",
"entry":{
"xmlns":"http://www.w3.org/2005/Atom",
"xmlns$media":"http://search.yahoo.com/mrss/",
"media$group":{
"media$content":[
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/DSC01612.JPG",
"height":512,
"width":341,
"type":"image/jpeg",
"medium":"image"
}
],
"media$thumbnail":[
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s72/DSC01612.JPG",
"height":72,
"width":48
},
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s144/DSC01612.JPG",
"height":144,
"width":96
},
{
"url":"https://lh3.googleusercontent.com/-_FFMNGPU1TQ/TtukXyN4eCI/AAAAAAAACso/EzPmut2iKVQ/s288/DSC01612.JPG",
"height":288,
"width":192
You can specify the size by using imgmax parameter (imgmax=d means original image).
https://developers.google.com/picasa-web/docs/2.0/reference#Parameters
Have you tried a print_r( $album_photo ) to check the exact format of the object and what it contains?
I'm pretty sure that there are a bunch of other parameters you can specify in that API to get access to different sizes of pictures and thumbnails. Check the docs.
I've accessed this API using json-script format a while ago and from memory there are a lot of options you can specify.
I have scoured the entire internet trying to find an answer to this problem. Nobody actually answered the question. For future reference to anyone else reading, or my future self, to get the large image do this:
echo $album_photo->content->attributes()->{'src'};
That was WAAAAYY more complicated than it should have been, and the normal XML user probably would have already known how to do that. :/

Send Http "Post" Request To Php Code in C or C++

I'm trying to send a "post" reguest to my php file and get the info back, it works fine, but
it also print something before printing my response from the php file. this is what it print
first:
HTTP/1.1 200 OK
Date: Fri, 20 Apr 2012 10:19:12 GMT
Server: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
X-Powered-By: PHP/5.3.6
Content-Length: 12
Connection: close
Content-Type: text/html
and then my response:
hello world
how can i only print what i'm getting from myphp code, without:
HTTP/1.1 200 OK
Date: Fri, 20 Apr 2012 10:19:12 GMT
Server: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
X-Powered-By: PHP/5.3.6
Content-Length: 12
Connection: close
Content-Type: text/html
the code i'm using is:
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <unistd.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define MAXSUB 200
#define LISTENQ 1024
extern int h_errno;
ssize_t process_http(int sockfd, char *host, char *page, char *poststr)
{
char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
ssize_t n;
snprintf(sendline, MAXSUB,
"POST %s HTTP/1.0\r\n"
"Host: %s\r\n"
"Content-type: application/x-www-form-urlencoded\r\n"
"Content-length: %d\r\n\r\n"
"%s", page, host, strlen(poststr), poststr);
write(sockfd, sendline, strlen(sendline));
while ((n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = '\0';
printf("%s", recvline); // <-- this
}
return n;
}
int main(void)
{
int sockfd;
struct sockaddr_in servaddr;
char **pptr;
//********** You can change. Puy any values here *******
char *hname = "localhost";
char *page = "/mysql_update.php";
char *poststr = "server=dd sd sdsdt\n";
//*******************************************************
char str[50];
struct hostent *hptr;
if ((hptr = gethostbyname(hname)) == NULL) {
fprintf(stderr, " Server down error for host: %s: %s",
hname, hstrerror(h_errno));
exit(1);
}
printf("hostname: %s \n", hptr->h_name);
if (hptr->h_addrtype == AF_INET
&& (pptr = hptr->h_addr_list) != NULL) {
printf("address: %s\n",
inet_ntop(hptr->h_addrtype, *pptr, str,
sizeof(str)));
} else {
fprintf(stderr, "Error call inet_ntop \n");
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(80);
inet_pton(AF_INET, str, &servaddr.sin_addr);
connect(sockfd, (SA *) & servaddr, sizeof(servaddr));
process_http(sockfd, hname, page, poststr);
close(sockfd);
exit(0);
}
Please help me to fix this problem, step by step so' i can understand it, give me information and please if you can' show me a example. ( this will help me and others )
First part of the response you received is made up of HTTP version, Server Response Status Code and various HTTP response headers.
HTTP/1.1 200 OK Date: Fri, 20 Apr 2012 10:19:12 GMT Server:
Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
X-Powered-By: PHP/5.3.6 Content-Length: 12 Connection: close
Content-Type: text/html
After headers follows HTTP response body (which you need to extract):
hello world
HTTP headers and body are separated with the following sequence of characters: \r\n\r\n. So all you need to do is to search for it and extract everything that is behind it.
You can do this yourself (sockets, parsing...) but my advice is to use some of HTTP libraries: WinInet, WinHttp (both are Microsoft's) or libCurl (open source).
The responses header bit is separated from the content by a blank line.
Need to take into account different line endings. Basically ignore \rs.
So 1st read lines until you get a blank one then start printing them!
EDIT
You have a response as follows
HTTP/1.1 200 OK
Date: Fri, 20 Apr 2012 10:19:12 GMT
...
Content-Type: text/html
Hello World
Notice that there is a blank line between the HTTP headers and the response (HTML in this case).

Categories