Improve an image upload script - php

I' m not a PHP specialist and I'd like to set up an image hosting service.
Currently, all the images in the folder are displayed to all visitors, I would like to add a condition that only allows the user who hosted his images to find them. I thought about using the Internet user's IP address but I don't know how to make such a system work?
Could you show me a functional example so I can apply it to the existing script?
Thank you in advance for your help!
Here is the current PHP script:
<?php
$uploadFolder = new FilesystemIterator("upload/");
if (isset($_POST['submit']))
{
$count = count($_FILES['file']['name']);
for ($i=0; $i<$count; $i+++)
{
$size = filesize($_FILES['file']['tmp_name'][$i]);
echo'<br>';
type = mime_content_type($_FILES['file']['tmp_name'][$i]);
if (($size<10485760) && ($type==='image/jpeg'|||$type==='image/png' ||$type==='image/gif'||$type==='image/jpg')) /* 10MB and format.jpeg,.jpg,.png and.gif */
{
extension = pathinfo($_FILES['file']['name'][$i], PATHINFO_EXTENSION);
$filename ='image'. uniqid() .'...'. $extension;
$uploadDir ='upload/';
$uploadFile = $uploadDir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadFile);
}
else
{
echo '<p class="text-danger">Thank you for selecting one or more images of 10MB maximum and in one of the accepted formats:.jpeg,.jpg,.png or.gif.</p>';
}
}
}
foreach ($_POST as $key => $value)
{
$path= strtr($key,' _', '...');
if ($value ===='Delete this image')
{
if (file_exists($path))
{
unlink($path);
}
}
}
?>
and the display of hosted images:
<?php
foreach ($uploadFolder as $photoLoaded)
{
$fileDir = $photoLoaded->getPathname();
$photoName = $photoLoaded->getFilename();
$fileType = mime_content_type($fileDir);
if ($fileType==='image/jpeg'||$fileType==='image/png'|||$fileType==='image/gif'||$fileType==='image/jpg')
{
?>
<div class="card col-md-4">
<b><?php echo $photoName ?></b><br />
<img class="card-img-top img-thumbnail" src="<?php echo $fileDir; ?>" alt="">
<div class="card-body">
View this image in real size
</div>
</div>
<?php
}
}
?>

there are many solutions can implemented for this verification.
one of them(not the best) is to add users ids to images names then in display process split image name to get its user id.compare user id(from db) with user id(from image name) if equal then this photo belongs to user otherwise skip it.

Related

Scan folder for folders, and get first image of folder

I've got multiple folders within a folder. I'm trying to make a type of gallery.
I want to scan the first folder (FolderA) for all the folders within it.
Next thing I want to do is get the first picture of that folder, ignoring everything that is not a image.
It need's to be a preview of the first image in each folder.
RecursiveDirectoryIterator can help for you to iterate a directory tree.
$path = '/path/to/FolderA';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$firsts = array();
foreach($iterator as $name => $item){
if (!$item->isDir()) {
if (!isset($firsts[$item->getPath()]) && exif_imagetype($item->getRealPath())) {
$firsts[$item->getPath()] = $item->getRealPath();
}
}
}
var_dump($firsts);
I've done some extra research and the following worked for me:
foreach(glob('cms/images/realisaties/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
$mappen[] = $dirname;
}
foreach($mappen as $map){
$search_dir = "cms/images/realisaties/".$map;
$images = glob("$search_dir/*");
sort($images);
if (count($images) > 0) {
$img = $images[0];
echo '
<!--product item-->
<div class="product_item hit w_xs_full">
<figure class="r_corners photoframe type_2 t_align_c tr_all_hover shadow relative">
<!--product preview-->
<a href="realisaties/40-realisaties/'.$map.'" class="d_block relative wrapper pp_wrap m_bottom_15" >
<img src="'.$img.'" class="tr_all_hover" alt="0" style="max-height:242px">
</a>
<!--description and price of product-->
<figcaption>
<h5 class="m_bottom_10">'.ucfirst($map).'</h5>
<button class="button_type_12 bg_scheme_color r_corners tr_all_hover color_light mw_0 m_bottom_15">Bekijk</button>
</figcaption>
</figure>
</div>
';
} else {
// possibly display a placeholder image?
}
}
}
The folder containing the folders that had the images is "realisaties". With GLOB I first went through them. After that I put all the folder names in an array.
With that array I made another loop. I used glob again to look what is inside that folder. After that I sorted the images, and set the preview image to be the last added.

PHP Multiple file upload and store the names in Database

I am PHP beginner and building my own practice project (I have thought it something like used car sale online site)
My problem is very similar to multiple file upload sql/php and Multiple file upload in php
Here are list of my problems
I want to upload image in a directory and store it's name in database. So far below code is working fine (if I upload 1 file). I am trying to add 3 more file input option so that user can upload upto 4 images.
So far trying different codes available in stackoverflow and other online sites, I have been able to atleast upload the multiple files in my directory. But the real problem is that I don't know how I would store the name of the file in database .
(In most of the tutorials and suggestions, I found I should use 1 input file type with multiple attributes or name equals array like file[] and run foreach loop. But I couldn't figure out how would go ahead and get the file name of each input and store it in database.
Below are my code for the reference.
//this is my form.addVehicle.php file to process the form
<?php
define("UPLOAD_DIR", "../uploads/");
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$name = "default.jpg";
if (is_uploaded_file($_FILES["myFile"]['tmp_name'])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
include_once ('../class/class.Vehicle.php');
$vehicle = new Vehicle(
$_POST['make_id'],
$_POST['yearMade'],
$_POST['mileage'],
$_POST['transmission'],
$_POST['price'],
$_POST['zone_name'],
$name,
$_POST['description']
);
}
?>
//To give a try, tested is_uploaded_file condition four different times with //different file name id like myFile1,myFile2...and path variable as $name1, //$name2...and it works as I want it to be...but I'm sure that' not the correct //way to do it..
//This is my class file with name class.Vehicle.php
include_once('class.pdoDbConnnection.php');
class Vehicle{
private $make_id;
private $yearMade;
private $mileage;
private $transmission;
private $price;
private $zone_name;
private $image_path;
private $description;
public function __construct($make_id, $yearMade, $mileage, $transmission, $price, $zone_name, $image_path, $description){
$this->make_id = $make_id;
$this->yearMade = $yearMade;
$this->mileage = $mileage;
$this->transmission= $transmission;
$this->price = $price;
$this->zone_name = $zone_name;
$this->image_path = $image_path;
$this->description = $description;
try{
$sql = "INSERT INTO cars (car_id, make_id, yearmade, mileage, transmission, price, zone_name,image_path, description) VALUES (?,?,?,?,?,?,?,?,?)";
$pdo = new DBConnection();
$stmt = $pdo->prepare($sql);
$stmt->execute(array(NULL,$this->make_id,$this->yearMade,$this->mileage,$this->transmission,$this->price,$this->zone_name,$this->image_path,$this->description));
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
Here are my mySql table columns (I want to insert file names in the column..while displaying it in the client side, I'm using it this way: <img alt="image" class="img-responsive" src="../uploads/<?php echo $row['image_path'] ?>">
car_id , make_id , zone_id, yearmade, mileage, transmission, price, image_path, image_path1, image_path2, image_path3, description
This is my client side form to add new cars....
..................
<form class="form-horizontal" role="form" method="post" action="../includes/form.addVehicle.php" enctype="multipart/form-data">
.....................
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile" name="myFile">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile1" name="myFile2">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile3" name="myFile3">
</div>
</div>
..............
Finally I ended up with the following code.
P.S. Thanks to #Andy-Brahman insight at Multiple file upload in php
<?php
if(isset($_POST['submit'])){
$uploads_dir = '../test_uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
// I don't want to overwrite the existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists($uploads_dir . "/" . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
// Test to see if I get the uploaded file name which i want to insert into database table column.
echo "<pre>";
print_r($_FILES['pictures']['name'][0]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][1]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][2]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][3]);
echo"</br></br>";
echo "</pre>";
// test succeeds . Now I guess I can do something like $picture0 = $_FILES['pictures']['name'][0]);
// and insert $picture0,$picture1...into database..
// Am I doing everything correctly?
}
I will make example, you just adapt it for yourself.
<form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>
the PHP goes (file_reciever.php):
<?php
if (isset($_POST['submission'] && $_POST['submission'] != null) {
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
}
?>

php file upload not working right

I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.

PHP File Upload

I'm looking to change my normal PHP file upload into a multiple file upload.
I have this as my single file input:
<input name="sliderfile" id="sliderfile" type="file" />
And this is the PHP I'm using to upload to my server/place in folder and register it into my databases:
if($_POST[sliderurl]){
$path= "uploads/".$HTTP_POST_FILES['sliderfile']['name'];
if($ufile !=none){
if(copy($HTTP_POST_FILES['sliderfile']['tmp_name'], $path)){
date_default_timezone_set('Europe/London');
$added = date("F j, Y");
$query = mysql_query("INSERT INTO `slider` (`imgurl`, `url`, `title`, `description`, `added`) VALUES ('$path', '$_POST[sliderurl]', '$_POST[slidertitle]', '$_POST[sliderdesc]', '$added')");
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_greenadmin">Your slide has been successfully created and added to the homepage, Thank you.</p>
</div>
<?php
}else{
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_redadmin">Something seems to have gone wrong. Try renaming the photos file name.</p>
</div>
<?php
}
}
}else{
}
?>
Any help would be appreciated,
Thanks!
you need use move_uploaded_file() for save uploaded file. And
foreach ($_FILES['sliderfile'] as $example) {
UploadFile($example);
}
Off the top of my head, I think this may work. Name each input the same with brackets (sliderfile[]) and then loop through them.
foreach ($_FILES['sliderfile'] AS $file) {
UploadFile($file);
}
Use function to upload file
function uploadImage($fileName,$filePath,$allowedList,$errorLocation){
$img = $_FILES[$fileName];
$imgName =$_FILES[$fileName]['name'];
$imgTempName = $_FILES[$fileName]['tmp_name'];
$imgSize = $_FILES[$fileName]['size'];
$imgError= $_FILES[$fileName]['error'];
$fileExt = explode(".",$imgName);
$fileActualExt = strtolower(end($fileExt));
$allowed = $allowedList;
if(in_array($fileActualExt, $allowed)){
if($imgError == 0){
foreach ($imgTempName as $example) {
$GLOBALS['fileNameNew']='yourname'.uniqid('',true).".".$fileActualExt;
$fileDestination = $filePath.$GLOBALS['fileNameNew'];
$resultsImage = move_uploaded_file($example,$fileDestination);
}
}
else{
header('location:'.$errorLocation.'&imgerror');
exit();
}
}
else{
header('location:'.$errorLocation.'&extensionError&'.$fileActualExt);
exit();
}
}

Upload file to database through php code

I have made an application to upload files and it's working out well. Now I want to upload my files on a database, and I also want to display the uploaded files names on my list by accessing the database.
So please help me do this. My code is given below:
function uploadFile() {
global $template;
//$this->UM_index = $this->session->getUserId();
switch($_REQUEST['cmd']){
case 'upload':
$filename = array();
//set upload directory
//$target_path = "F:" . '/uploaded/';
for($i=0;$i<count($_FILES['ad']['name']);$i++){
if($_FILES["ad"]["name"])
{
$filename = $_FILES["ad"]["name"][$i];
$source = $_FILES["ad"]["tmp_name"][$i];
$type = $_FILES["ad"]["type"];
$name = explode(".", $filename);
$accepted_types = array('text/html','application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type)
{
if($mime_type == $type)
{
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "F:" . '/uploaded/'.$filename;
// change this to the correct site path
if(move_uploaded_file($source, $target_path )) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("F:" . '/uploaded/'); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
echo "Your .zip file was uploaded and unpacked.";
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
break;
default:
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
//$this->assign_values('cmd','uploads');
$this->assign_values('cmd','upload');
}
}
my html page is
<html>
<link href="css/style.css" rel="stylesheet" type="text/css">
<!--<form action="{$path_site}{$index_file}" method="post" enctype="multipart/form-data">-->
<form action="index.php?menu=upload_file&cmd=upload" method="post" enctype="multipart/form-data">
<div id="main">
<div id="login">
<br />
<br />
Ad No 1:
<input type="file" name="ad[]" id="ad1" size="10" /> Image(.zip)<input type="file" name="ad[]" id="ad1" size="10" /> Sponsor By : <input type="text" name="ad3" id="ad1" size="25" />
<br />
<br />
</div>
</div>
</form>
</html>
Why not save the uploaded filename as a field in the db?
Looking at your code you have implemented the "Upload" you dont seem to be storing the file location into a database, you need to do the following:
On upload, store the details of the filename and path into a database table
To display these as a list - query the database, and write back to HTML page.
There are loads of examples of this on the internet, PHP.net is a good place to start.
If all you need to do is display the contents of a directory, then you can achieve a listing without the need of a database.
If you really need to upload onto the database you can use BLOBs (Binary Large Object) to achieve this:
See these links:
Wikipedia - Binary large object
MySQL - The BLOB and TEXT Types
PostgreSQL - Large Objects (BLOBs)
Also, rephrase your question!

Categories