Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - URL encoding

Is there a simple way to do URL encode in C? I'm using libcurl but I haven't found a method. Specifically, I need to do percent escapes.

like image 981
ryyst Avatar asked Apr 30 '11 14:04

ryyst


People also ask

What does %2f mean in URL?

URL encoding converts characters into a format that can be transmitted over the Internet. - w3Schools. So, "/" is actually a seperator, but "%2f" becomes an ordinary character that simply represents "/" character in element of your url.

What does %20 do in URL?

A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.

What is %23 in a URL?

%23 is the URL encoded representation of # . I suspect your rewrite rules will not satisfy %23 . You ought to investigate how the response is being constructed. Specifically, any URL encoding functions.


2 Answers

In C based on wikipedia, without having to alloc and free. Make sure output buffer is at least 3X input URL string. Usually you only need to encode up to maybe 4K as URLs tend to be short so just do it on the stack.

char rfc3986[256] = {0};
char html5[256] = {0};

void url_encoder_rfc_tables_init(){

    int i;

    for (i = 0; i < 256; i++){

        rfc3986[i] = isalnum( i) || i == '~' || i == '-' || i == '.' || i == '_' ? i : 0;
        html5[i] = isalnum( i) || i == '*' || i == '-' || i == '.' || i == '_' ? i : (i == ' ') ? '+' : 0;
    }
}

char *url_encode( char *table, unsigned char *s, char *enc){

    for (; *s; s++){

        if (table[*s]) *enc = table[*s];
        else sprintf( enc, "%%%02X", *s);
        while (*++enc);
    }

    return( enc);
}

Use it like this

url_encoder_rfc_tables_init();

url_encode( html5, url, url_encoded);
like image 166
alian Avatar answered Oct 07 '22 06:10

alian


curl_escape

which apparently has been superseded by

curl_easy_escape

like image 37
Oliver Charlesworth Avatar answered Oct 07 '22 06:10

Oliver Charlesworth