php - 如何将 text/html 数据发送到浏览器

标签 php c http browser http-headers

嗨,我之前在这里问过一个问题:how-can-i-integrate-php-with-my-http-server 我编写了一个个人 Web 服务器,并尝试使用 PHP-CGI 将其与 PHP 集成,我运行一个系统命令(“PHP-CGI.exe path/to/php/script.php getvar=getValue”),然后发送输出到浏览器,一切正常,除了输出在浏览器中显示为纯文本页面,如:

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>

这是 PHP 脚本:

<?php
session_start();
echo "< h1>ID value = < /h1>". $_GET['id'];
?>

和我使用的命令:php-cgi html_doc/index.php id=AAAA

我的问题是:为什么它以纯文本/文本而不是我想要的文本/html 发送数据?! 为什么它会像上面那样在浏览器中显示标题信息?! 谢谢大家! (注意:我把

分开了,所以它可以出现!)

最佳答案

这是一个使用 C 套接字的 BASIC html_to_browser

#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;
}

使用 sudo(允许端口 80) 在控制台上编译 + 执行,或者将 addr.sin_port 更改为大于“1024”的值

...ctrl+z 完成

关于php - 如何将 text/html 数据发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608605/

相关文章:

从 C 函数中清除结构内部动态内存的内容

node.js - HTTP2 - 如何拥有类似 WebSocket 的功能(Keep-Alive、EventSource 等)

spring - 使用 spring 和 restful webservice 自定义 HTTP 状态代码

http - 我什么时候应该在响应 header 中真正将 "Access-Control-Allow-Credentials"设置为 "true"?

PHP while 循环在 while 循环中运行一次

javascript - FPDF 提交表单至 PDF 问题

php - 使用php和mysql的通知系统

c++ - C - 在控制台应用程序中使用鼠标和键盘,无需等待按任意键

php - MeekroDB 错误 "Commands out of sync; you can' t 现在运行此命令”

c - 一次在一个文件中写入一个结构