url.c
/**
 * Simplistic "URL parameter" parsing.
 * Only returns the first found parameter.
 * Currently does not parse percent-encoded values.
 *
 * Returns:
 *  - newly allocated string with value for parameter when found
 *  - NULL when the parameter is not found
 *
 * Consumer must free.
 */
Simplistic "URL parameter" parsing.
Only returns the first found parameter.
Currently does not parse percent-encoded values.

- newly allocated string with value for parameter when found
- NULL when the parameter is not found

Consumer must free.
Simplistic " URL parameter " parsing . Only returns the first found parameter . Currently does not parse percent - encoded values . - newly allocated string with value for parameter when found - NULL when the parameter is not found Consumer must free .
char* url_get_param(const char* url, const char* name)
{
	if (url == NULL || name == NULL || strlen(name) == 0) {
		return NULL;
	}
	char* start = strchr(url, '?');
	if (start == NULL) {
		return NULL;
	}
	start += 1;
	char* needle = calloc(strlen(name)+2, 1);
	strcat(needle, name);
	strcat(needle, "=");
	unsigned int needle_skip = strlen(needle);
	char* candidate = start;
	char* end = NULL;
	while((candidate = strstr(candidate, needle)) != NULL) {
		if (candidate == start || *(candidate-1) == '&') {
			candidate += needle_skip;
			end = strchr(candidate, '&');
			if (end == NULL) {
				end = candidate+strlen(candidate);
			}
			char* ret = calloc(end-candidate+1, 1);
			strncpy(ret, candidate, end-candidate);
			return ret;
		}
		candidate += needle_skip;
	}
	return NULL;
}
char * url_get_param ( const char * url , const char * name ) { if ( url == NULL || name == NULL || strlen ( name ) == 0 ) { return NULL ; } char * start = strchr ( url , ' ' ) ; if ( start == NULL ) { return NULL ; } start += 1 ; char * needle = calloc ( strlen ( name ) + 2 , 1 ) ; strcat ( needle , name ) ; strcat ( needle , " " ) ; unsigned int needle_skip = strlen ( needle ) ; char * candidate = start ; char * end = NULL ; while ( ( candidate = strstr ( candidate , needle ) ) != NULL ) { if ( candidate == start || * ( candidate - 1 ) == ' ' ) { candidate += needle_skip ; end = strchr ( candidate , ' ' ) ; if ( end == NULL ) { end = candidate + strlen ( candidate ) ; } char * ret = calloc ( end - candidate + 1 , 1 ) ; strncpy ( ret , candidate , end - candidate ) ; return ret ; } candidate += needle_skip ; } return NULL ; }
Simplistic "URL parameter" parsing.
Simplistic " URL parameter " parsing .
// No valid inputs? // Find the URL parameters; which here is assumed to be the first // instance of '?' // No URL params? No params! // Parameters start *after* the question mark. // Search forward for the needle // Either first param, or after a separator (&) // Skip the needle in the result // Get to the next separator // Oh, or maybe we're at the end! // Copy the string // Skip further than the needle we found. // No candidate found :(