URL encoding feature

I've ran into this problem a few times so I decided to fix it and send it in. I though something like this would be found in glib, but I didn't find it anywhere. gtkhtml uses libwww and it's a big mess for what I wanted to do.

gchar* url_encode( gchar* source )

source :    The raw URL string.
returns:    A new allocated URL encoded string, must free with g_free when done.

This function follows RFC 2396 (Query Component)

tts = g_strdup("www.BitBuilder.com/query.php?text=Abbas Bin Fernas, huh?" );
tts = url_encode( tts );
g_print("%s\n", tts);
g_free( tts );

This would be neat in glib string utilities. The files attached are url_encode.h and url_encode.c

Have fun,


/* From RFC 2396 : ------------------------------------------------- /

 The query component is a string of information to be interpreted by
   the resource.

      query         = *uric

   Within a query component, the characters ";", "/", "?", ":", "@",
   "&", "=", "+", ",", and "$" are reserved.


#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#include <gnome.h>
#include "url_encode.h"

#define RESERVED_CHARS	"!\"'()*+-.<>[]\\^_`{}|~\t#;/?:@&=+,$% \r\n\v\x7f"

   Not the most effecient way of doing this,
   If you can come up with something better
   let me know,
   Ahmad Baitalmal <ahmad@bitbuilder.com>
gchar* url_encode( gchar* source ){
	gint length = strlen( source );
	gint i;
	gchar*	encoded;

	g_return_val_if_fail( source != NULL, source );
	encoded = g_strdup("");
	for( i=0; i<length; i++ ){
		encoded = append_char( encoded, source[i], (gboolean) strchr( RESERVED_CHARS, source[i] ) );
	g_free( source );
	return encoded;

gchar* append_char( gchar* url_string, gchar char_to_append, gboolean convert_to_hex )
	gchar* new_string;
	if( convert_to_hex )
		new_string = g_strdup_printf("%s%%%x", url_string, char_to_append);
		new_string = g_strdup_printf("%s%c", url_string, char_to_append);
	g_free( url_string );
	return new_string;

gchar* url_encode( gchar* source );
gchar* append_char( gchar* url_string, gchar char_to_append, gboolean convert_to_hex );

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]