I want to utilize namespaces and make the code on this file uploading script more secure, and cleaner looking, here is what i have so far
it uploads an image and inserts it into a database.
I want to be able to use namespaces within view files, without it looking messy.
i know i can use laravel blade etc, but for the sake of sharpening my php skills, i want to be able to do this from scratch.
Image.php
<?php
require 'Db.php';
class Image{
private $dbh;
private $connect;
public $directory;
public $uploadfile;
public function __construct()
{
$this->dbh = new Db();
$this->connect = $this->dbh->connect();
$this->directory = "uploads/";
}
public function upload_image($filename, $image_name)
{
$this->uploadfile = $this->directory . basename($filename);
try{
$stmt = $this->connect->prepare("INSERT INTO images (img, image_name) VALUES (:img, :imagename) ");
$stmt->bindparam(':img', $this->uploadfile);
$stmt->bindparam(':imagename', $image_name);
$stmt->execute();
return $stmt;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
public function get_image()
{
return $this->uploadfile;
}
}
upload_image.php (view file)
<form action="/ImgUpload.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" name="profile_img" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
<input type="text" name="image_name" placeholder="Enter Name Of File" class="mt-3">
<small id="fileHelp" class="form-text text-muted">This is some placeholder block-level help text for the above input. It's a bit lighter and easily wraps to a new line.</small>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
ImgUpload.php
<?php
session_start();
require_once 'Image.php';
if(isset($_FILES['profile_img'])){
$image = new Image();
$filename = $_FILES["profile_img"]["name"];
$realname = "uploads/" . basename($filename);
$directory = "/Applications/MAMP/htdocs/eliphp1/uploads/";
$path = $directory . basename($filename);
$image_name = $_POST['image_name'];
if($image->upload_image($realname, $image_name)){
move_uploaded_file($_FILES["profile_img"]["tmp_name"], $path);
echo '<img src="'.$image->get_image().'">';
};
};
?>