2013.11.24 16:05

[CGI 개발] html 전송 방식 CGI 로 처리하기

출처 : http://www.tutorialspoint.com/cplusplus/cpp_web_programming.htm


[ keyword  : cgi get post file dropbox 처리법 ] 

What is CGI?

  • The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.

  • The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:

  • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.

  • The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

To understand the concept of CGI, let's see what happens when we click a hyperlink to browse a particular web page or URL.

  • Your browser contacts the HTTP web server and demand for the URL ie. filename.

  • Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.

  • Web browser takes response from web server and displays either the received file or error message based on the received response.

However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display.

The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.

CGI Architecture Diagram

The following simple program shows a simple architecture of CGI:

CGI Architecture

Web Server Configuration

Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.

By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file:

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>
 
<Directory "/var/www/cgi-bin">
Options All
</Directory>

Here, I assumed that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc.

First CGI Program

Consider the following C++ Program content:

#include <iostream>
using namespace std;
 
int main ()
{
    
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Hello World - First CGI Program</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<h2>Hello World! This is my first CGI program</h2>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable. Now if you click cplusplus.cgi then this produces the following output:

Hello World! This is my first CGI program

Above C++ program is a simple program which is writing its output on STDOUT file ie. screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other exernal system, such as RDBMS, to exchange information.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form

HTTP Field Name: Field Content
 
For Example
Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in your CGI Programming.

HeaderDescription
Content-type:A MIME string defining the format of the file being returned. Example is Content-type:text/html
Expires: DateThe date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.
Location: URLThe URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file.
Last-modified: DateThe date of last modification of the resource.
Content-length: NThe length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
Set-Cookie: StringSet the cookie passed through the string

CGI Environment Variables

All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.

Variable NameDescription
CONTENT_TYPEThe data type of the content. Used when the client is sending attached content to the server. For example file upload etc.
CONTENT_LENGTHThe length of the query information. It's available only for POST requests
HTTP_COOKIEReturn the set cookies in the form of key & value pair.
HTTP_USER_AGENTThe User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser.
PATH_INFOThe path for the CGI script.
QUERY_STRINGThe URL-encoded information that is sent with GET method request.
REMOTE_ADDRThe IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
REMOTE_HOSTThe fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHODThe method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAMEThe full path to the CGI script.
SCRIPT_NAMEThe name of the CGI script.
SERVER_NAMEThe server's hostname or IP Address
SERVER_SOFTWAREThe name and version of the software the server is running.


Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment


#include <iostream>
#include <stdlib.h>
using namespace std;

const string ENV[ 24 ] = {                 
        "COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",   
        "HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",             
        "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",         
        "HTTP_HOST", "HTTP_USER_AGENT", "PATH",            
        "QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",      
        "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
        "SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",      
        "SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",     
        "SERVER_SIGNATURE","SERVER_SOFTWARE" };   

int main ()
{
    
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>CGI Envrionment Variables</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<table border = \"0\" cellspacing = \"2\">";

   for ( int i = 0; i < 24; i++ )
   {
       cout << "<tr><td>" << ENV[ i ] << "</td><td>";
       // attempt to retrieve value of environment variable
       char *value = getenv( ENV[ i ].c_str() );  
       if ( value != 0 ){
         cout << value;                                 
       }else{
         cout << "Environment variable does not exist.";
       }
       cout << "</td></tr>\n";
   }
   cout << "</table><\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

C++ CGI Library

For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and following the following steps to install the library:

$tar xzf cgicc-X.X.X.tar.gz 
$cd cgicc-X.X.X/ 
$./configure --prefix=/usr 
$make
$make install

You can check related documentation available at C++ CGI Lib Documentation.

GET and POST Methods

You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.

Passing Information using GET method:

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:

http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string.

When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable

You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method.

Simple URL Example : Get Method

Here is a simple URL which will pass two values to hello_get.py program using GET method.

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

Below is program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information:

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>  

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET and POST Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("first_name");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "First name: " << **fi << endl;  
   }else{
      cout << "No text entered for first name" << endl;  
   }
   cout << "<br/>\n";
   fi = formData.getElement("last_name");  
   if( !fi->isEmpty() &&fi != (*formData).end()) {  
      cout << "Last name: " << **fi << endl;  
   }else{
      cout << "No text entered for last name" << endl;  
   }
   cout << "<br/>\n";

   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Now, compile the above program as follows:

$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc

Generate cpp_get.cgi and put it in your CGI directory and try to access using following link:

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

This would generate following result:

First name: ZARA 
Last name: ALI 

Simple FORM Example: GET Method

Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input.

<form action="/cgi-bin/cpp_get.cgi" method="get">
First Name: <input type="text" name="first_name">  <br />
 
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>

Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.


First Name:  
Last Name:  

Passing Information using POST method:

A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.

The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows:

<form action="/cgi-bin/cpp_get.cgi" method="post">
First Name: <input type="text" name="first_name"><br />
Last Name: <input type="text" name="last_name" />
 
<input type="submit" value="Submit" />
</form>

Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.


First Name:  
Last Name:  

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes

<form action="/cgi-bin/cpp_checkbox.cgi" 
         method="POST" 
         target="_blank">
<input type="checkbox" name="maths" value="on" /> Maths
<input type="checkbox" name="physics" value="on" /> Physics
<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form

 Maths  Physics 

Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
   bool maths_flag, physics_flag;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Checkbox Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   maths_flag = formData.queryCheckbox("maths");
   if( maths_flag ) {  
      cout << "Maths Flag: ON " << endl;  
   }else{
      cout << "Maths Flag: OFF " << endl;  
   }
   cout << "<br/>\n";

   physics_flag = formData.queryCheckbox("physics");
   if( physics_flag ) {  
      cout << "Physics Flag: ON " << endl;  
   }else{
      cout << "Physics Flag: OFF " << endl;  
   }
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Radio Button Data to CGI Program

Radio Buttons are used when only one option is required to be selected.

Here is example HTML code for a form with two radio button:

<form action="/cgi-bin/cpp_radiobutton.cgi" 
         method="post" 
         target="_blank">
<input type="radio" name="subject" value="maths" 
                                    checked="checked"/> Maths 
<input type="radio" name="subject" value="physics" /> Physics
<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form

 Maths  Physics 

Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Radio Button Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("subject");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Radio box selected: " << **fi << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Text Area Data to CGI Program

TEXTAREA element is used when multiline text has to be passed to the CGI Program.

Here is example HTML code for a form with a TEXTAREA box:

<form action="/cgi-bin/cpp_textarea.cgi" 
         method="post" 
         target="_blank">
<textarea name="textcontent" cols="40" rows="4">
Type your text here...
</textarea>
<input type="submit" value="Submit" />
</form>

The result of this code is the following form

 

Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Text Area Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("textcontent");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Text Content: " << **fi << endl;  
   }else{
      cout << "No text entered" << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Drop Down Box Data to CGI Program

Drop Down Box is used when we have many options available but only one or two will be selected.

Here is example HTML code for a form with one drop down box

<form action="/cgi-bin/cpp_dropdown.cgi" 
                       method="post" target="_blank">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit"/>
</form>

The result of this code is the following form

 

Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Drop Down Box Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("dropdown");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Value Selected: " << **fi << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Using Cookies in CGI

HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

How It Works

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.

Cookies are a plain text data record of 5 variable-length fields:

  • Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

  • Domain : The domain name of your site.

  • Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

  • Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

  • Name=Value : Cookies are set and retrieved in the form of key and value pairs.

Setting up Cookies

This is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before to Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows

#include <iostream>
using namespace std;

int main ()
{
 
   cout << "Set-Cookie:UserID=XYZ;\r\n";
   cout << "Set-Cookie:Password=XYZ123;\r\n";
   cout << "Set-Cookie:Domain=www.tutorialspoint.com;\r\n";
   cout << "Set-Cookie:Path=/perl;\n";
   cout << "Content-type:text/html\r\n\r\n";

   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Cookies in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   cout << "Setting cookies" << endl;  
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.

Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.

Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer:

/cgi-bin/setcookies.cgi

Retrieving Cookies

This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.

key1=value1;key2=value2;key3=value3....

Here is an example of how to retrieving cookies.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc cgi;
   const_cookie_iterator cci;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Cookies in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<table border = \"0\" cellspacing = \"2\">";
   
   // get environment variables
   const CgiEnvironment& env = cgi.getEnvironment();

   for( cci = env.getCookieList().begin();
        cci != env.getCookieList().end(); 
        ++cci )
   {
      cout << "<tr><td>" << cci->getName() << "</td><td>";
      cout << cci->getValue();                                 
      cout << "</td></tr>\n";
   }
   cout << "</table><\n";
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer:

/cgi-bin/getcookies.cgi

This will produce a list of all the four cookies set in previous section and all other cookies set at your computer:

UserID XYZ 
Password XYZ123 
Domain www.tutorialspoint.com 
Path /perl 

File Upload Example:

To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button.

<html>
<body>
   <form enctype="multipart/form-data" 
            action="/cgi-bin/cpp_uploadfile.cgi" 
            method="post">
   <p>File: <input type="file" name="userfile" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>
</body>
</html>

The result of this code is the following form:

File: 

Note: Above example has been disabled intentionally to save people uploading files on our server. But you can try above code with your server.

Here is the script cpp_uploadfile.cpp to handle file upload:

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc cgi;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>File Upload in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   // get list of files to be uploaded
   const_file_iterator file = cgi.getFile("userfile");
   if(file != cgi.getFiles().end()) {
      // send data type at cout.
      cout << HTTPContentHeader(file->getDataType());
      // write content at cout.
      file->writeToStream(cout);
   }
   cout << "<File uploaded successfully>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

The above example is writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location.

Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us

Posted by k1rha
2013.11.18 23:40

form.html

<html>
 <head>  <title> POST example</title> </head>
 <body>
  <center>
 <form action="http://localhost/cgi-bin/posttest.exe" method="POST">
  <input type="text" name="m"/> x 
  <input type="text" name="n"/> = 
  <input type="text" value=""/><br>
  <input type="submit" value="보여주세요"/>
 </form>
  </center>
 </body>
</html>


posttest.exe

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
 char content[32];
 long m,n;
 long length;

 /* POST방식으로 요청한 문자열의 크기를 구한다 */
 char *content_len = getenv("CONTENT_LENGTH");

 /* 문자열의 크기는 문자열 형식이므로 정수로 변환한다 */
 sscanf(content_len, "%ld", &length);

 /* 표준입력스트림(stdin)으로부터 요청 문자열을 읽어온다 */
 fgets(content, length+2, stdin);

 printf("Content-Type:text/html;charset=euc-kr\n\n");

 printf("<html><head><title> POST요청, 곱셈결과 </title></head>\n");
 printf("<body><center>\n");
 printf("<h3>POST요청, 곱셈결과</h3>\n");

 printf("전달된 파라미터 : %s <br>\n 문자수 : %d \n", content, strlen(content));

 if(content==NULL) {
  printf("<p>웹브라우저에서 전달된 파라미터 문자열이 없습니다.<br>\n");
  printf("<p>요청폼에 2개의 수를 입력하고 다시 해보세요.<br>\n");
 }
 else if(sscanf(content, "m=%ld&n=%ld", &m, &n)!=2) 
  printf("<p>파라미터의 값은 정수이어야 합니다<br>.\n");
 else
  printf("<p>계산 결과: %ld * %ld = %ld.\n", m,n,m*n);

 printf("</center></body>\n");

 return 0;

}



Posted by k1rha
2013.07.10 00:02

<script language="javascript">


function commify(n) {

  var reg = /(^[+-]?\d+)(\d{3})/;   // 정규식

  n += '';                          // 숫자를 문자열로 변환


  while (reg.test(n))

    n = n.replace(reg, '$1' + ',' + '$2');


  return n;

}



정규 표현식 으로 금액 (,) 표기 하기 금액을 표기해주는 함수는 없는듯하다.

이렇게해서 그때그때 잘 써먹어야지..





Posted by k1rha
2013.03.10 23:39

PHP XSS (cross site scripting) filter function Web hacking

출처 : http://kallahar.com/smallprojects/php_xss_filter_function.php

function RemoveXSS($val) {
 
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed 
   // this prevents some character re-spacing such as <java\0script> 
   
// note that you have to handle splits with \n, \r, and \t later since they *are* 
   // allowed in some inputs
 
   $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/''', $val); 
    
   // straight replacements, the user should never need these since they're normal characters 
   
// this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&
   // #X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
 
   $search = 'abcdefghijklmnopqrstuvwxyz'
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
   $search .= '1234567890!@#$%^&*()'
   $search .= '~`";:?+/={}[]-_|\'\\'
   for ($i = 0; $i < strlen($search); $i++) { 
   // ;? matches the ;, which is optional 
   // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars 
    
   // &#x0040 @ search for the hex values 
      $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); 
      // with a ; 

      // &#00064 @ 0{0,7} matches '0' zero to seven times 
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; 
   } 
    
   // now the only remaining whitespace attacks are \t, \n, and \r 
   $ra1 = Array('javascript''vbscript''expression''applet''meta''xml''blink''link''style'
'script''embed''object''iframe''frame''frameset''ilayer''layer''bgsound''title''base'); 
   $ra2 = Array('onabort''onactivate''onafterprint''onafterupdate''onbeforeactivate','onbeforecopy''onbeforecut''onbeforedeactivate''onbeforeeditfocus''onbeforepaste','onbeforeprint''onbeforeunload''onbeforeupdate''onblur''onbounce''oncellchange''onchange','onclick''oncontextmenu''oncontrolselect''oncopy''oncut''ondataavailable''ondatasetchanged','ondatasetcomplete''ondblclick''ondeactivate''ondrag''ondragend''ondragenter''ondragleave','ondragover''ondragstart''ondrop''onerror''onerrorupdate''onfilterchange''onfinish''onfocus','onfocusin''onfocusout''onhelp''onkeydown''onkeypress''onkeyup''onlayoutcomplete','onload''onlosecapture''onmousedown''onmouseenter''onmouseleave''onmousemove','onmouseout''onmouseover''onmouseup''onmousewheel''onmove''onmoveend','onmovestart''onpaste''onpropertychange''onreadystatechange''onreset''onresize','onresizeend''onresizestart''onrowenter''onrowexit''onrowsdelete''onrowsinserted''onscroll','onselect''onselectionchange''onselectstart''onstart''onstop''onsubmit''onunload'); 
   $ra = array_merge($ra1, $ra2); 
    
   $found = true; // keep replacing as long as the previous round replaced something 
   while ($found == true) { 
      $val_before = $val; 
      for ($i = 0; $i < sizeof($ra); $i++) { 
         $pattern = '/'
         for ($j = 0; $j < strlen($ra[$i]); $j++) { 
            if ($j > 0) { 
               $pattern .= '('
               $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?'
               $pattern .= '|(&#0{0,8}([9][10][13]);?)?'
               $pattern .= ')?'
            } 
            $pattern .= $ra[$i][$j]; 
         } 
         $pattern .= '/i'
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag 
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags 
         if ($val_before == $val) { 
            // no replacements were made, so exit the loop 
            $found = false; 
         } 
      } 
   } 
   return $val; 

Posted by k1rha
2012.12.03 12:18

function initialize(){

mytext=$("#"+i).html();

$("#typing").html("");

typeit();


}


function typeit(){


temp = mytext.charAt(it);   //여기서 몇번재 문자열을 문자열을 가져올지 정한다.

if(temp == "^")$("#typing").html($("#typing").html()+"<br>");  //특정 문자열이 나오면 개행


else typing.insertAdjacentText("beforeEnd",temp) ;   //타이핑되는 함수


if (it<mytext.length){

it++ ;

setTimeout("typeit()",70);   //시간 주기 타이핑되는 시간주기

}

}


 
타이핑 효과 내는 자바스크립트 코드  (Javascript Code to typing effect)

한글짜식 타이핑 효과를 내주는 Jquery를 사용한 구문.. 

typing.insertAdjacentText  에 대한 어느 위치에 타이핑 되게 할지 결정

▶ beforeBegin : 택의 외부에서 택의 바로 앞

▶ afterBegin : 택의 내부에서 내용물의 시작

▶ beforeEnd : 택의 내부에서 내용물의 끝

▶ afterEnd : 택의 외부에서 택의 바로 뒤

Posted by k1rha
2012.10.24 00:24

!ereg("^[\xa1-\xfe0-9a-zA-Z]+$",$name)


else if(!ereg("^[\xa1-\xfe0-9a-zA-Z]+$",$name)){
echo"
<script>
window.alert('아이디는 한글과 영문,숫자만 입력할 수 있습니다')
history.go(-1)
</script>
";
}

Posted by k1rha
2012.06.26 22:12

//정은이(Scar) 가 쓴 인코딩 디코딩 페이지 php 소스.



<?php 

//error_reporting(E_ALL); 
//ini_set('display_errors','1'); 

if ($_POST['value']){ 
    
$value=$_POST['value']; 
    
$select=$_POST['select']; 

else{ 
    
$value=''
    
$select=''


switch (
$select){ 
    case 
'URL encode'
        
$result=urlencode($value); 
        break; 
    case 
'BASE64 encode'
        
$result=base64_encode($value); 
        break; 
    case 
'URL decode'
        
$result=urldecode($value); 
        break; 
    case 
'BASE64 decode'
        
$result=base64_decode($value); 
        break; 
    case 
'MD5 hash'
        
$result=md5($value); 
        break; 
    case 
'SHA1 hash'
        
$result=sha1($value); 
        break; 
    default: 
        
$array=1
        
$size=1
        
$div[0]=$value
        if (
strstr($value,' ')){ 
            
$div=explode(' ',$value); 
            
$size=count($div); 
        } 
        switch (
$select){ 
            case 
'Hex to Dec'
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=' '.hexdec($div[$i]); 
                } 
                break; 
            case 
'Hex to Ascii'
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=chr(hexdec($div[$i])); 
                } 
                break; 
            case 
'Dec to Hex'
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=' '.dechex($div[$i]); 
//                    if($result[$i]==7fffffff) 
                

                
$result[0]=dechex($div[0]); 
                break; 
            case 
'Dec to Ascii'
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=chr($div[$i]); 
                } 
                break; 
            case 
'Ascii to Hex'
                
$size=strlen($value); 
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=' '.dechex(ord($value[$i])); 
                } 
                break; 
            case 
'Ascii to Dec'
                
$size=strlen($value); 
                for (
$i=0;$i<$size;$i++){ 
                    
$result[$i]=' '.ord($value[$i]); 
                } 
                break; 
            default: 
                
$result=''
        } 


?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
    <HEAD> 
        <TITLE> encode/decode </TITLE> 
        <link type='text/css' rel='stylesheet' href='../style.css'> 
    </HEAD> 
    <BODY> 
        <form action='index.php' method='POST'> 
            <div class='crypto_input'> 
                <textarea class='crypto_input' name='value'><? 
                
if ($array==1){ 
                    
$result[0]=trim($result[0]); 
                    for (
$i=0;$i<count($result);$i++){ 
                        echo (
$result[$i]); 
                    } 
                } 
                else{ 
                    echo (
$result); 
                } 
                
?></textarea> 
                dec, hex는 공백 기호로 분리됩니다. 
            </div> 
            <br><br> 
            <div class='crypto_menu'> 
                <div class='crypto_content_box encode'> 
                    <input class='button' type='submit' name='select' value='URL encode'><br> 
                    <input class='button' type='submit' name='select' value='BASE64 encode'><br> 
                </div> 
                <div class='crypto_content_box decode'> 
                    <input class='button' type='submit' name='select' value='URL decode'><br> 
                    <input class='button' type='submit' name='select' value='BASE64 decode'><br> 
                </div> 
                <div class='crypto_content_box hash'> 
                    <input class='button' type='submit' name='select' value='MD5 hash'><br> 
                    <input class='button' type='submit' name='select' value='SHA1 hash'> 
                </div> 
                <div class='crypto_content_box hex'> 
                    <input class='button' type='submit' name='select' value='Hex to Dec'><br> 
                    <input class='button' type='submit' name='select' value='Hex to Ascii'> 
                </div> 
                <div class='crypto_content_box dec'> 
                    <input class='button' type='submit' name='select' value='Dec to Hex'><br> 
                    <input class='button' type='submit' name='select' value='Dec to Ascii'> 
                </div> 
                <div class='crypto_content_box ascii'> 
                    <input class='button' type='submit' name='select' value='Ascii to Hex'><br> 
                    <input class='button' type='submit' name='select' value='Ascii to Dec'> 
                </div> 
            </div> 
        </form> 
    </BODY> 
</HTML> 

Posted by k1rha
2012.04.22 17:20

function CheckEmail(){
str=document.musimm.email.value
var t = escape(str);
//sung2li@naver.com 일때와 sung2li@naver.co.kr일때의 형식 체크
if(t.match(/^(\w+)@(\w+)[.](\w+)$/ig) == null && t.match(/^(\w+)@(\w+)[.](\w+)[.](\w+)$/ig) == null){
alert("E-mail 형식이 잘못되었습니다.");
document.musimm.email.focus();
} else {
return true;
}
}



Posted by k1rha
2012.03.25 12:01


<?
include_once "../common/common.php";

 

 $title=htmlspecialchars($_POST['write_info']);
 $currentTime = date("Y-m-d",time());

 

if(!$title){

?> <script>
 alert("Plz insert title or file");
 location.href="./index.php";
 </script>
<?
  
}

else{

 $FILE=$_FILES['FILE']['name'];
  $cut=explode('.',$FILE);
  $size=sizeof($cut);
  $extension=$cut[$size-1];
  $result=strtolower($extension);

 $addr='javascript:history.back()';

 if ($FILE){
  $SVFILE=date('y-m-d H:i:s').md5($FILE).'.'.$result;
  $img_flag_1=($result=='bmp' or $result=='dib' or $result=='jpg' or $result=='jpeg' or $result=='jpe' or $result=='jfif' or $result=='gif' or $result=='tif' or $result=='tiff' or $result=='png');
  $img_flag_2=($_FILES['FILE']['type']=='image/bmp' or $_FILES['FILE']['type']=='image/dib' or $_FILES['FILE']['type']=='image/jpg' or $_FILES['FILE']['type']=='image/jpeg' or $_FILES['FILE']['type']=='image/pjpeg' or $_FILES['FILE']['type']=='image/jpe' or $_FILES['FILE']['type']=='image/jfif' or $_FILES['FILE']['type']=='image/gif' or $_FILES['FILE']['type']=='image/tif' or $_FILES['FILE']['type']=='image/tiff' or $_FILES['FILE']['type']=='image/png' or $_FILES['FILE']['type']=='image/x-png');
  if ($img_flag_1){
   if ($img_flag_2){
    if($_FILES['FILE']['error']>0){
     $msg='파일을 업로드 할 수 없습니다.';
    }
    if (file_exists('./upload/'.$SVFILE)){
     $msg='파일을 업로드 할 수 없습니다.';
    }
    else{
     move_uploaded_file($_FILES['FILE']['tmp_name'],'./upload/'.$SVFILE);
    }
   }
   else{
    $msg='파일을 업로드 할 수 없습니다.<br>'.$_FILES['FILE']['type'];
   }
  }
  else{
   $msg='파일을 업로드 할 수 없습니다.';
  }
 }
 else{
  $SVFILE='';
  echo("file error");
  echo("<script>
  location.href='./index.php';
  </script>");
 }

 


 $sql="insert into trip (memo,file,date) values ('$title','$SVFILE','$currentTime')";

 mysql_query ($sql);


 //die($sql);


 ?>


 <script>
  location.href="./index.php";
 </script>
 <?

}

 

?>

Posted by k1rha
2012.03.21 02:51
나름대루 썸네일 함수를 만들어 봤습니다. 잘 되더군염..
gif, jpg, png 파일이 가능하구염..

function thumnail($file, $save_filename, $save_path, $max_width, $max_height) {

// 전송받은 이미지 정보를 받는다
$img_info = getImageSize($file);

// 전송받은 이미지의 포맷값 얻기 (gif, jpg png)
if($img_info[2] == 1) {
$src_img = ImageCreateFromGif($file);
} else if($img_info[2] == 2) {
$src_img = ImageCreateFromJPEG($file);
} else if($img_info[2] == 3) {
$src_img = ImageCreateFromPNG($file);
} else {
return 0;
}

// 전송받은 이미지의 실제 사이즈 값얻기
$img_width = $img_info[0];
$img_height = $img_info[1];

if($img_width <= $max_width) {
$max_width = $img_width;
$max_height = $img_height;
}

if($img_width > $max_width){
$max_height = ceil(($max_width / $img_width) * $img_height);
}

// 새로운 트루타입 이미지를 생성
$dst_img = imagecreatetruecolor($max_width, $max_height);

// R255, G255, B255 값의 색상 인덱스를 만든다
ImageColorAllocate($dst_img, 255, 255, 255);

// 이미지를 비율별로 만든후 새로운 이미지 생성
ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, ImageSX($src_img),ImageSY($src_img));

// 알맞는 포맷으로 저장
if($img_info[2] == 1) {
ImageInterlace($dst_img);
ImageGif($dst_img, $save_path.$save_filename);
} else if($img_info[2] == 2) {
ImageInterlace($dst_img);
ImageJPEG($dst_img, $save_path.$save_filename);
} else if($img_info[2] == 3) {
ImagePNG($dst_img, $save_path.$save_filename);
}

// 임시 이미지 삭제
ImageDestroy($dst_img);
ImageDestroy($src_img);
Posted by k1rha
2012.03.21 02:48

http://blog.naver.com/cache798?Redirect=Log&logNo=130062020309

mysql 설정을 해주고

$string = iconv("UTF-8","CP949",$_POST['cmd']);

Posted by k1rha
2012.03.21 02:38

phpinfo() [function.phpinfo]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you

most likely misspelled the timezone identifier. We selected 'Asia/Seoul' for 'KST/9.0/no DST' instead

원인이 먼지 삽질하다 찾아내었다..

php5.3은 date.timezone을 설정하지 않으면 php warning 이 출력된다...

그래서 php.ini 화일에서 date.timezone =Asia/Seroul 로 설정해야 한다 

Posted by k1rha
2012.03.21 02:35

This plugin was originally written by Dave Methvin.
Dave and I collaborated on several improvements and the project is now hosted on github.
The most recent version is also available here: jquery.corner.js.

Absolute Position
It's important to understand that this corner plugin is pulling off its magic by adding more elements to the page. Specifically, it adds div "strips" to the item to be cornered and sets a solid background color on these strips in order to hide the actual corners of the real item. So if you step back and look at the cornered element, think of there being solid colored divs hiding the true squared off corners of the item you wish to be changed. This helps you understand the inherent limitations of this small plugin. It's best suited for rounding off block-level elements (divs, paragraphs, etc) and may present more challenges when trying to round off inline elements (spans, anchors, etc).
Recently I added support for native border-radius rounding in browsers that support it (Opera 10.5+, Firefox, Safari, and Chrome). So in those browsers the plugin simply sets a css property on the element. But in IE, we'll have to wait for version 9 before that is supported. And for all browsers, choosing a pattern other than "round" requires the use of the "div stips" method.
Auto-Ready!

Available Patterns

The default pattern is round

Round

$(this).corner();

Bevel

$(this).corner("bevel");

Notch

$(this).corner("notch");

Bite

$(this).corner("bite");

Cool

$(this).corner("cool");

Sharp

$(this).corner("sharp");

Slide

$(this).corner("slide");

Jut

$(this).corner("jut");

Curl

$(this).corner("curl");

Tear

$(this).corner("tear");

Fray

$(this).corner("fray");

Wicked

$(this).corner("wicked");

Sculpt

$(this).corner("sculpt");

Long

$(this).corner("long");

Dog Ear

$(this).corner("dog");

Dog2

$(this).corner("dog2");

Dog3

$(this).corner("dog3");

Dogfold*

$(this).corner("dogfold");

Bevelfold*

$(this).corner("bevelfold");

Steep

$(this).corner("steep");

InvSteep

$(this).corner("invsteep");

* Fold lines are not supported in Internet Explorer for pages rendered in quirksmode.
* Fold lines are only supported on top corners in Internet Explorer, unless running in IE8 standards-mode.

Choose Your Corner

Use top, bottom, left, right, tl, tr, bl, br to identify which corner to style

Top Bevel

$(this).corner("bevel top");

Top-Left Bite

$(this).corner("bite tl");

Round Bottom

$(this).corner("bottom");

Left Notch

$(this).corner("notch left");

Top-Right Dog Ear

$(this).corner("dog tr");

Top-Left, Bottom-Right Cool

$(this).corner("cool tl br");

Right Bevelfold

$(this).corner("bevelfold right");

Specify Size

Include a px value to specify the corner size

Round 30px

$(this).corner("30px");

Round 5px

$(this).corner("5px");

Cool 20px

$(this).corner("cool 20px");

Sharp 20px

$(this).corner("sharp 20px");

Bite 30px

$(this).corner("bite 30px");

Wicked 20px

$(this).corner("wicked 20px");

Dog 20px

$(this).corner("dog 20px");

Dog2 30px

$(this).corner("dog2 30px");

Dog3 30px

$(this).corner("dog3 30px");

Mix and Match

Chain corner calls to achieve combined effects

Round and Bevel

$(this).corner( "bottom").corner("top bevel");

Round and Notch

$(this).corner( "br top").corner("notch bl 20px");

Crazy

$(this).corner("jut tl 20px").corner("dog tr 20px").corner("bite bl 15px").corner("notch br");

Adornment

Effects Using Nested Cornered Elements (Thanks to Kevin Scholl for this idea)

Round

$(this).corner("round 8px").parent().css('padding', '4px').corner("round 10px")

Round

$(this).corner("round 8px").parent().css('padding', '8px').corner("round 14px")

Round

$(this).corner("round 14px").parent().css('padding', '15px').corner("round 14px")

Bevel

$(this).corner("bevel 8px").parent().css('padding', '5px').corner("bevel 10px")

Bevel

$(this).corner("bevel 8px").parent().css('padding', '10px').corner("bevel 14px")

Bite

$(this).corner("bite 10px").parent().css('padding', '8px').corner("bite 10px")

Bite

$(this).corner("bite 20px").parent().css('padding', '15px').corner("bite 20px")

Fray

$(this).corner("fray 10px").parent().css('padding', '10px').corner("fray 10px")

Tear

$(this).corner("tear 20px").parent().css('padding', '15px').corner("tear 20px")