3
\$\begingroup\$

This is the first PHP script I have written. It downloads and installs a plugin called "anti-spam" by using the WordPress API. It also provides an option to either delete all comments or delete the comments, which are unapproved or marked as SPAM.

    <html>
    <head>
        <title>SPAM tool</title>
        <style>
form {
     text-align: center;
}
h2 {
     text-align: center;
   }

body {
    background-color: linen;
}
</style>
    </head>

    <body>

        <h2>Simple SPAM Managing tool</h2>

<form action="" method="post">
<input type="radio" name="radio" value="all">Delete ALL comments
<br>
<input type="radio" name="radio" value="un">Delete UNapproved comments
<br>
<input type="submit" name="submit" value="Kill spam" />
</form>


            <?php

include "wp-config.php"; #adds Wordpress configuration, so we can use DB config
include "wp-load.php";
include "wp-admin/includes/plugin.php";
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); #connect to DB
    if (!$connect) {
    echo 'Database connect failed';
    } else {
    echo 'Connection to database OK!';
    }
        echo "<br>";
$select = mysql_select_db(DB_NAME); 
$tablename = $table_prefix . "comments";
$query  = ("SELECT COUNT(comment_approved) FROM $tablename WHERE comment_approved = 0");
$execute = mysql_query($query, $connect);
    if ($execute) {
            echo ("Comments UNapproved (comment_approved = 0): "), mysql_result($execute, 0);}
    else {echo "Comment count failed";}    

        echo ('<br>');
$query  = ("SELECT COUNT(comment_approved) FROM $tablename"); 
$execute = mysql_query($query, $connect);
    if ($execute) {
            echo ("Comments total: "), mysql_result($execute, 0);}
        else {echo "Comment count failed";}    

        echo ('<br>');      
    $args = (object) array( 'slug' => 'Anti-spam' );

    $request = array( 'action' => 'plugin_information', 'timeout' => 15, 'request' => serialize( $args) );

    $url = 'http://api.wordpress.org/plugins/info/1.0/';

    $response = wp_remote_post( $url, array( 'body' => $request ) );

    $plugin_info = unserialize( $response['body'] );

    $durl = $plugin_info->download_link;

    echo "$durl";
$download = file_put_contents("antispam.zip", file_get_contents("$durl")); #downloads the Anti-spam plugin
if ($download) {
echo "Download OK!";}
else {
echo "Download FAIL!";} #check if download is OK
echo "<br>";
$path = getcwd();
$zip = new ZipArchive; #extracts the .zip
if ($zip->open('antispam.zip') === TRUE) {
    $zip->extractTo("$path/wp-content/plugins/");
    $zip->close();
    echo 'Plugin extracted';
} else {
    echo 'Extract Failed';
    }
echo "<br>";   
$activate = activate_plugin( "$path/wp-content/plugins/anti-spam/anti-spam.php" ); #Activate the plugin
if ( is_wp_error( $activate ) ) {

} else {
echo 'AntiSPAM plug-in activated!';}

echo ('<br>');      
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{ 
if ($_POST['radio']=="all") { $select = mysql_select_db(DB_NAME); 
$tablename = $table_prefix . "comments";
$query  = ("TRUNCATE $tablename"); #TRUNCATE comments
mysql_query($query, $connect);
echo "DELETED!"; 
}
elseif ($_POST['radio']=="un") { $select = mysql_select_db(DB_NAME); 
$tablename = $table_prefix . "comments";
$tablename2 = $table_prefix . "commentmeta"
$query  = ("DELETE FROM $tablename WHERE comment_approved = 0 or comment_approved = 'spam'"); 
mysql_query($query, $connect); 
$query2  = ("DELETE FROM $tablename2 WHERE comment_id NOT IN (SELECT comment_id FROM $tablename)");
mysql_query($query2, $connect); 
echo "DELETED!"; 
    } }}
else{ echo "<span>Please choose any radio button.</span>";}
mysql_close($connect);
exit;
?>
    </body>
</html>

You can also check the project's repository at GitHub.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Coding Style and Conventions

A nice coding style can dramatically improve readability, and thanks to IDEs, it's incredibly easy to achieve.

  • You should use correct indentation! This would make it a lot easier to see what blocks of code belong together (this goes for the PHP and the HTML code).
  • You should handle the same thing the same way: Sometimes your closing curly brackets are on the same line, sometimes the next; sometimes you use echo($var), and sometimes echo $var (the second version is how it's usually done).
  • be consistent with your casing. SQL keywords should always be all-uppercase, not only sometimes.
  • you have some unnecessary parentheses (eg $query = (...)).

Functions

Extracting functionality to functions increases readability as it's easier to see what a block of code does. It also decreases duplication and increases reusability of your code.

You could introduce functions such as:

  • countComments($onlyApproved): this can remove the SELECT COUNT(comment_approved) FROM $tablename duplication.
  • downloadPlugin($pluginName)
  • extractZip($fileName)
  • deleteComments($types): $types can be all, unapproved or spam.

Naming

Generally, your variable names are quite clear, but some of them could be more descriptive. Eg un could be unapproved, tablename could be tableNameComments, tablename2 could be tableNameCommentsMeta, query could be deleteComments and query2 could be deleteCommentsMeta.

Misc

  • If you have an error (eg the database connection failed), don't just continue. Return/Redirect/Die instead.
  • You should not use mysql_*, as it's deprecated (since 2013). Use mysqli_* or PDO instead (or use the wrapper that WordPress supplies)).
  • It seems that currently your code always installs the plugin, and additionally deletes comments if the user wants to, which doesn't seem to make that much sense. If I already installed the plugin, and only want to use the comment deletion option of your code, I would need to still download the plugin, which seems like a waste of resources.

WordPress

You should check out how to write plugins for WordPress, it would be a lot nicer than a plain PHP file.

For example, this would make it easier for a reader to understand how your includes work (eg wp-config.php isn't really needed, it's loaded by wp-load.php; on the other hand, you use functions from files which you don't explicitely include).

It would also add some security. Currently, it seems that anyone can access this script, not just admin users, which would be pretty bad. An attacker could delete all comments, and can cause your website to slow down significantly (because the script downloads and unzips a big file each time it is called).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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