Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <form name="upload" action="uploadimg.php" method="POST" enctype="multipart/form-data">
- Select image to upload: <input type="file" name="image">
- <input type="submit" name="upload" value="upload">
- </form>
- <?php
- if(!empty($_POST['upload']) && !empty($_FILES['image']) && $_FILES['image']['error'] == 0) {
- $uploaddir = 'uploads/';
- /* Generates random filename and extension */
- function tempnam_sfx($path, $suffix){
- do {
- $file = $path."/".mt_rand().$suffix;
- $fp = @fopen($file, 'x');
- }
- while(!$fp);
- fclose($fp);
- return $file;
- }
- /* Process image with GD library */
- $verifyimg = getimagesize($_FILES['image']['tmp_name']);
- /* Make sure the MIME type is an image */
- $pattern = "#^(image/)[^\s\n<]+$#i";
- if(!preg_match($pattern, $verifyimg['mime'])){
- die("Only image files are allowed!");
- }
- /* Rename both the image and the extension */
- $uploadfile = tempnam_sfx($uploaddir, ".tmp");
- /* Upload the file to a secure directory with the new name and extension */
- if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
- /* Setup a database connection with PDO */
- $dbhost = "localhost";
- $dbuser = "";
- $dbpass = "";
- $dbname = "";
- // Set DSN
- $dsn = 'mysql:host='.$dbhost.';dbname='.$dbname;
- // Set options
- $options = array(
- PDO::ATTR_PERSISTENT => true,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
- );
- try {
- $db = new PDO($dsn, $dbuser, $dbpass, $options);
- }
- catch(PDOException $e){
- die("Error!: " . $e->getMessage());
- }
- /* Setup query */
- $query = 'INSERT INTO uploads (name, original_name, mime_type) VALUES (:name, :oriname, :mime)';
- /* Prepare query */
- $db->prepare($query);
- /* Bind parameters */
- $db->bindParam(':name', basename($uploadfile));
- $db->bindParam(':oriname', basename($_FILES['image']['name']));
- $db->bindParam(':mime', $_FILES['image']['type']);
- /* Execute query */
- try {
- $db->execute();
- }
- catch(PDOException $e){
- // Remove the uploaded file
- unlink($uploadfile);
- die("Error!: " . $e->getMessage());
- }
- } else {
- die("Image upload failed!");
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement