• WP Jamie

    (@wp-jamie)


    I’m developing a WP site with custom user profiles I’ve created that will be viewable on the front end (and called via author.php).

    I want visitors to be able to search on user profiles through a search form I’ve created. The search form has checkboxes, plus a search box where you can input a text string to search on. The search is implemented by get_users and by a prepared SQL query, as shown in the code excerpt below.

    My question: Have I properly sanitized what needs to be sanitized in the code below?

    The code works, but I’m concerned about SQL injection because of the user input and the communication with the database. I’ve read a number of Codex pages and coding-blog posts, and watched several presentations on security issues from WP conferences. But I’m a coding amateur, and my knowledge is very spotty (probably obvious from my code).

    Thanks to any and all who respond!

    Jamie

    <h2>Search Results</h2>
    <p><strong>You searched for:</strong></p>
    <?php
    
    //$_POST values from checkboxes and a text input box
    foreach ($_POST as $key => $value){
    //$_POST values sanitized via esc_html
    echo "<ul class=\"srch-results\"><li>" . esc_html( $value ) . "</li></ul>";
    }
    
    global $wpdb;
    
    $array=array();
    	//$_POST value from checkbox
    	if (isset($_POST['lev-expert'])) {
    	$blogusers = get_users('meta_key=Level&meta_value=Expert');
    	foreach ($blogusers as $user) {
    	$url = 'http://www.mysite.com/author/' . $user->user_login;
    	//URL in $link sanitized via esc_url
    	$link = '<li><a href="' . esc_url($url) . '">' . $user->user_firstname . ' ' . $user->user_lastname . '</a></li>';
    	array_push ($array,$link); }
    	}
    
    	//Many more (isset($_POST... blocks like the above will follow here--one for each checkbox
    
    	//$_POST value from text input box
    	if ($_POST['search-terms'] == true) {
    	$metakey	= 'Description';
    	$metavalue = '%' . $_POST['search-terms'] . '%';
    	$results = $wpdb->get_results(
    		$wpdb->prepare(
    			"
    			SELECT * FROM $wpdb->usermeta
    			WHERE meta_key=%s
    			AND meta_value LIKE %s
    			",
    			$metakey,
    			$metavalue
    		) );
    	foreach ($results as $var) {
    	$userid = $var->user_id;
    	$user = get_userdata ($userid);
    	$linktext = $user->user_firstname . ' ' . $user->user_lastname;
    	//URL in $link sanitized via esc_url
    	$link = 'http://www.mysite.com/author/' . $user->user_login;
    	$print = '<li><a href="' . esc_url($link) . '">' . $linktext . '</a></li>';
    	array_push ($array,$print);}
    	}  
    
    // Returns a list of hyperlinks to user profiles
    echo '<p><strong>Users matching your search:</strong></p>';
    echo '<ul>';
    print_r (implode(array_unique($array)));
    echo '</ul>';
  • The topic ‘Esc_html, esc_url, and $wpdb->prepare used correctly?’ is closed to new replies.