1

I have a custom developed plugin for a wordpress website that is an online car community on php5.6. I didn't develop the site originally but am now the custodian. I have limited programming knowledge. My plugin has about 6 lines in various places like these:

$title = mysql_escape_string(stripslashes($_POST['title']));

$content = mysql_escape_string(stripslashes($_POST['article']));

return mysql_escape_string(stripslashes($_POST[$value]));

I need to move to PHP7 but of course this is a deprecated and obsolete method of interacting with the database.

I'd love someone's help to propose the cleanest most reliable way of replacing this exact line with either a wpdb query or a esq_sql method. I've seen this referenced in many articles but I do not know the correct syntax or security implications given that my lines also have 'stripslashes' in there.

Thanks in advance.

An example of the lines inside functions of my plugin are as follows:

function getPostValueOrNothing($value) {
if (isset($_POST[$value])) {
return mysql_escape_string(stripslashes($_POST[$value]));
} else {
return "";
}
}

and you can see the repeated dependency on this in the following snippet:

<?php global $post;
$author_id = bp_displayed_user_id();
$user = get_user_by('id', $author_id);

if (is_user_logged_in() && $author_id == get_current_user_id() && isset($_POST['userpinfield'])) {
    if ($_POST['userpinfield'] != "") {
        echo "<p>Validation error</p>";
    } else {
        $post_id = -1;
        $attach_id = -1;
        $meta_key = "car_id";

        $title = getPostValueOrNothing('title');
        $content = $_POST['article'];
        $year = getPostValueOrNothing('year');
        $pdate = getPostValueOrNothing('pdate');
        $reg = getPostValueOrNothing('reg');
        $commNo = getPostValueOrNothing('commNo');
        $engineNo = getPostValueOrNothing('engineNo');
        $vin = getPostValueOrNothing('vin');
        $colour = getPostValueOrNothing('colour');
        $ccolour = getPostValueOrNothing('to_close_colour');
        $mileage = getPostValueOrNothing('mileage');
        $location = getPostValueOrNothing('location');

        if (isset($_POST['post_id']) && $_POST['post_id'] == -1) {
            if (null == get_page_by_title($title)) {
                $slug = str_replace(" ", "-", strtolower($title));
            } else {
                $titleSlug = $title . "" . rand(1, 9);

                while (null != get_page_by_title($title)) {
                    $titleSlug = $titleSlug . "" . rand(1, 9);
                }

                $slug = str_replace(" ", "-", strtolower($titleSlug));
            }

            //Generate post             
            $post_id = wp_insert_post(
                    array(
                        'comment_status' => (!empty($_POST['comment_status']))? $_POST['comment_status'] : 'closed',
                        'ping_status' => 'closed',
                        'post_author' => $author_id,
                        'post_name' => $slug,
                        'post_title' => $title,
                        'post_content' => $content,
                        'post_status' => 'publish',
                        'post_type' => 'to_car'
                    )
            );

            //Generate Topic post                   
            $topic_id = wp_insert_post(
                    array(
                        'comment_status' => 'closed',
                        'ping_status' => 'closed',
                        'post_author' => $author_id,
                        'post_name' => $slug . 'topic',
                        'post_title' => $title,
                        'post_content' => $content,
                        'post_status' => 'publish',
                        'comment_stattus' => 'open',
                        'post_type' => 'topic'
                    )
            );


            add_post_meta($topic_id, $meta_key, $post_id);
            add_post_meta($topic_id, '_bbp_forum_id', $topic_id);
            add_post_meta($topic_id, '_bbp_topic_id', $topic_id);
            add_post_meta($topic_id, '_bbp_last_active_time', date('Y-m-d H:m:s'));
            add_post_meta($topic_id, '_bbp_author_ip', $_SERVER['REMOTE_ADDR']);

            add_post_meta($post_id, 'topic_id', $topic_id);
            add_post_meta($post_id, 'to_year', $year);
            add_post_meta($post_id, 'to_vin', $vin);
            add_post_meta($post_id, 'to_comm', $commNo);
            add_post_meta($post_id, 'to_engine_no', $engineNo);
            add_post_meta($post_id, 'to_reg', $reg);
            add_post_meta($post_id, 'to_date', $pdate);
            add_post_meta($post_id, 'to_mileage', $mileage);
            add_post_meta($post_id, 'to_colour', $colour);
            add_post_meta($post_id, 'to_close_colour', $ccolour);
            add_post_meta($post_id, 'to_views', 0);

            if (!function_exists('media_handle_upload')) {
                require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                require_once(ABSPATH . "wp-admin" . '/includes/media.php');
            }

            if ($_FILES) {
                foreach ($_FILES as $file => $array) {
                    if ($_FILES['feature']['error'] !== UPLOAD_ERR_OK) {
                        if ($_FILES['feature']['error'] != 4) {
                            echo "upload error : " . $_FILES['feature']['error'];
                        }
                    } else {
                        $attach_id = media_handle_upload('feature', $post_id);
                    }
                }
            }

            if ($attach_id > 0) {
                update_post_meta($post_id, '_thumbnail_id', $attach_id);
            }

            $terms = get_terms('to_make');
            if ($terms) {
                foreach ($terms as $term) {
                    $modelValue = getPostValueOrNothing('model' . $term->term_id);
                    if ($modelValue != "") {
                        update_post_meta($post_id, 'to_model', $modelValue);
                        break;
                    }
                }
            }
            $post = get_post($post_id);
                $dummyUrl = plugins_url('/imgs/noCar.png', __FILE__);

                $html = '<div><span>Added a new Car</span></div><div><a href="' . get_bloginfo('url') . '/to-car/' . $post->post_name . '">';
                if (has_post_thumbnail()) {
                    $html .= '<img src="' . get_the_post_thumbnail_url(get_the_ID(), 'thumbnail') . '" title="' . get_the_title() . '" alt="' . get_the_title() . '" />';
                }else{
                    $html .= '<img src="' . $dummyUrl . '" title="' . get_the_title() . '" alt="' . get_the_title() . '" />';
                } 
                $html .= '<div><span>' . get_the_title() . '</span></div>';

                $html .= '</a></div>';
            bp_fmsu_generate_activity($author_id, $slug, $html);
            echo "<p>Car Saved!</p>";
        } else {
            $post_id = mysqli_real_escape_string(stripslashes($_POST['post_id']));

            if (is_nan($post_id)) {
                echo "Unable to update the classified posting";
            } else {
                $current_item = array(
                    'ID' => $post_id,
                    'post_title' => $title,
                    'post_content' => $content,
                    'comment_status' => (!empty($_POST['comment_status']))? $_POST['comment_status'] : 'closed',
                );

                wp_update_post($current_item, true);

                if (is_wp_error($post_id)) {
                    $errors = $post_id->get_error_messages();
                    foreach ($errors as $error) {
                        echo $error;
                    }
                } else {
                    update_post_meta($post_id, 'to_year', $year);
                    update_post_meta($post_id, 'to_vin', $vin);
                    update_post_meta($post_id, 'to_comm', $commNo);
                    update_post_meta($post_id, 'to_engine_no', $engineNo);
                    update_post_meta($post_id, 'to_reg', $reg);
                    update_post_meta($post_id, 'to_date', $pdate);
                    update_post_meta($post_id, 'to_mileage', $mileage);
                    update_post_meta($post_id, 'to_colour', $colour);
                    update_post_meta($post_id, 'to_close_colour', $ccolour);
                    update_post_meta($post_id, 'to_views', 0);

                    //Generate Topic post                   



                if (!function_exists('media_handle_upload')) {
                    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
                }
                if ($_FILES) {
                    foreach ($_FILES as $file => $array) {
                        if ($_FILES['feature']['error'] !== UPLOAD_ERR_OK) {
                            if ($_FILES['feature']['error'] != 4) {
                                echo "upload error : " . $_FILES['feature']['error'];
                            }
                        } else {
                            echo "file uploaded";
                            $attach_id = media_handle_upload('feature', $post_id);
                        }
                    }
                }

                if ($attach_id > 0) {
                    update_post_meta($post_id, '_thumbnail_id', $attach_id);
                }
                     $post = get_post($post_id);
                $dummyUrl = plugins_url('/imgs/noCar.png', __FILE__);

                $html = '<div><span>Updated a Car</span></div><div><a href="' . get_the_permalink() . '">';
                if (has_post_thumbnail()) {
                    $html .= '<img src="' . get_the_post_thumbnail_url(get_the_ID(), 'thumbnail') . '" title="' . get_the_title() . '" alt="' . get_the_title() . '" />';
                } else{
                    $html .= '<img src="' . $dummyUrl . '" title="' . get_the_title() . '" alt="' . get_the_title() . '" />';
                }
                $html .= '<div><span>' . get_the_title() . '</span></div>';

                $html .= '</a></div>';
                    bp_fmsu_generate_activity($author_id, $slug, $html);

                    echo '<p class="ajaxmessage">Car updated!</p>';
                }
            }
        }
    }
}
?>
  • If you want the easiest method, just replace mysql with mysqli. – Nathan Johnson Apr 22 '17 at 23:44
  • Thank you Nathan. I have tried that and posts that are changed (on front-end) via this custom plugin do not get saved to the database when I substitute mysql_ with mysqli_ under PHP7. Perhaps your change is all that is needed but there is a deeper issue in my plugin that relates to this change. – Glen Johnson Apr 22 '17 at 23:54
  • 1
    @Glen: try replacing mysql_escape_string with mysqli_real_escape_string ( PHP 7 ). If that does not fix the problem, more detailed info might help to find a solution. – Frank P. Walentynowicz Apr 23 '17 at 4:10
  • Thanks Frank. Same result - posts do not get saved back to database when that is in place (mysqli_real_ etc.) I've added some example functions that use it in the plugin. – Glen Johnson Apr 23 '17 at 10:24
0

You don't need to sanitize the variables that are passed to wp_update_post() because wp_update_post() after some checks pass the data to wp_insert_post() and wp_insert_post() calls sanitize_post(), which does the sanitization of all arguments.

Also add_post_meta and update_post_meta also do all the sanitization for you.

To answer your question I would replace mysql_escape_string with $wpdb->esc_sql($_POST[$value]). It calls mysqli_real_escape_string if supported or mysql_real_escape_string otherwise.

BUT whenever you echo inside an HTML code you should always escape the values by using esc_html($value), esc_url($url), esc_attr($attribute) etc.

More: Data Validation

  • I replaced all mysql_escape_.... instances as you suggested. After attempting to edit a post via the front end (part of the plugin capability) I end up with a blank page after the header. I enabled debug and it shows this in the body of the page (where the content would normally render with an 'updated' message: ( ! ) Fatal error: Uncaught Error: Call to a member function esc_sql() on null in ...\plugins\triumph-cars2017\carCreateForm.php on line 90 – Glen Johnson Apr 24 '17 at 6:50
  • Incidentally, the line 90 referred to is the return line of this function: function getPostValueOrNothing($value) { if (isset($_POST[$value])) { return $wpdb->esc_sql($_POST[$value]); } else { return ""; } } – Glen Johnson Apr 24 '17 at 6:55
  • You have to use global $wpdb; inside your function – Laxmana Apr 24 '17 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.