HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Bad code to handle image upload

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
imagehandleuploadbadcode

Problem

I'm using this form to submit articles into the database:










include ("database.php"); 
$upload_path = "files/images/";
$prefix= date("Hi-mdY")."-";

$file_name = $HTTP_POST_FILES['image']['name'];
$file_name = str_replace(' ', '-', $file_name);
$file_name = str_replace('_', '-', $file_name);
$file_name = strtolower($file_name);

$upload_path = $upload_path . basename($prefix.$file_name);
move_uploaded_file($_FILES['image']['tmp_name'], $upload_path);

$final_file_name = ("/files/images/".$prefix.$file_name);
$date=date("Y.m.d");

$sql="INSERT INTO articles (title, image_link,  text, date) VALUES ('$_POST[title]', '$final_file_name', '$_POST[text]', '$date')"
if (mysql_query($sql)){
    echo "done";
} else {
    echo "error" . mysql_error();
}


And here is the problem:

One of my friends told me that the PHP code in add.php is incorrect.

This is working for me, but can someone correct the code please.

EDIT:

Thanks guys, I've corrected the code :


  
  
  
  




" . mysql_error();
    }
  }
?>


Now it's good?

Solution

There are quite few things to note in your code.

First of all, you are using deprecated $HTTP_POST_FILES where as you should use $_FILES

You are not using mysql_real_escape_string function in your query variables and therefore are vulnerable to sql injection which is caused through poor sql queries.

You are not checking whether or not the submit button was clicked, you should wrap your entire code in between:

if (isset($_POST['go'])){
  // your code
}

Code Snippets

if (isset($_POST['go'])){
  // your code
}

Context

StackExchange Code Review Q#15172, answer score: 10

Revisions (0)

No revisions yet.