php image upload - php

How to make a basic PHP uploader? I want my images to save in my htdocs/myfolder/
Here is my code:
<form enctype="multipart/form-data" method="post" action="img_uploader.php">
<input type="file" name="fileToUpload" /><br />
<input type="submit" value="Upload File" />
</form>

the code below is a simple example touching all the aspects of image or file upload take a look at it and understand it
<?php
/* to do large file uploads open the php.ini file and set "post_max_size = 150M" or the
size you wish and also set "upload_max_filesize = 120M" post_max_size must be greater than upload_max_filesize in oder
to work, also set the "max_input_time" and "max_execution_time" to 300 (5 minutes specified in seconds)
or more if you wish finally set them in your php script as below, also set "memory_limit = 1024M" or what you wish
by default "memory_limit = 128M" Note in Wamp this should be done in C:\wamp64\bin\apache\apache2.4.23\bin\php.ini and
in C:\wamp64\bin\php\php5.6.25\php.ini or C:\wamp64\bin\php\php7.0.10\php.ini depending on the php version you are using
the values must all be the same in all scripts */
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
ini_set('memory_limit','500M');
//set errors array
function output_errors($errors){
$output = array();
foreach($errors as $error){
$output[] = '<li>' . $error . '</li>';
}
return '<ul class="errors">' . implode('', $output) . '</ul>';
}
//set validation array
function output_valids($no_errors){
$output = array();
foreach($no_errors as $no_error){
$output[] = '<li>' . $no_error . '</li>';
}
return '<ul class="valid">' . implode('', $output) . '</ul>';
}
$no_errors = array();
$errors = array();
if (isset($_FILES['image']) AND $_FILES['image']['error']== 0){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$only_extentios = array('jpg', 'jpeg', 'gif','png');
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
array_push($no_errors,"File is an image - " . $check["mime"] . ".");
$uploadOk = 1;
} else {
array_push($errors,"File is not an image.");
$uploadOk = 0;
}
}
// check for correct image extention and size
if (!in_array($imageFileType,$only_extentios)){
array_push($errors,"Sorry, only jpg, jpeg, png & gif files are allowed.");
$uploadOk = 0;
}elseif ($_FILES["image"]["size"] > 10000000){
array_push($errors,"Sorry, your file is too large.");
$uploadOk = 0;
}
// Check if file already exists, if uploadok is set to one ant try to upload image
if (file_exists($target_file)) {
array_push($errors,"Sorry, file already exists.");
$uploadOk = 0;
}
if($uploadOk == 1){
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
}else{
array_push($errors,"Sorry, your file was not uploaded.") ;
}
if (file_exists($target_file)){
array_push($no_errors,"The file ". basename( $_FILES["image"]["name"]). " has/had been uploaded.");
} else {
array_push($errors,"Sorry, there was an error uploading your image.");
}
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8"/>
<title > image upload </title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="author" content="image uploader"/>
<style type="text/css" >
*,{
margin: 0px;
padding: 0px;
font-family: 'Oswald', sans-serif;
}
header,section,footer,aside,nav,article,hgroup {
display: block;
}
body{
width:100%; color:black;
display:-webkit-box;
-webkit-box-pack: center;
-webkit-box-orient:vertical;
-webkit-box-flex: 1;
background: rgba(204,204,255,0.9);
background-repeat:repeat;
}
.errors{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.errors li{
text-align:left;
color:red;
font-size:15px;
list-style:;
}
.valid{
width:97%;
height:auto;
float:left;
margin-left:3%;
padding:10px;
}
.valid li{
text-align:left;
color:green;
font-size:15px;
list-style:;
}
</style>
</head>
<body>
<p><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" >
<?php
echo output_valids($no_errors);
?>
Sélectionnez une photo:
<label class="custom-file-upload" style=" margin:0px auto;"> <input type="file" name="image" /> choix </label>
<input type="submit" value="Envoyer " name="submit"/>
<?php
echo output_errors($errors);
?>
</form></p>
</body>
</html>

Here is a quick tutorial I found for doing a file upload:
http://www.tizag.com/phpT/fileupload.php
I read through it pretty quick, but it gives you the basic idea with some safety stuff to boot

specify your directory path here
$target_path = "uploads/";
replace the name of file input with uploadedfile and rest code will work fine
`
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}`

As Your Code below is working example:
first create a folder with name "myfolder" in your htdocs folder
[img_uploader.php]
<?php
$target_path = "myfolder/";
$target_path = $target_path . basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

In the working directory is fine work upload but, uploading in the database at the same time is note working any one solve this problem? kindly.
function doInsert(){
if(isset($_POST['save'])){
if ( $_POST['BRANCHNAME'] == "" || $_POST['BRANCHLOCATION'] == "" || $_POST['BRANCHCONTACTNO'] == "" ) {
$messageStats = false;
message("All field is required!","error");
redirect('index.php?view=add');
}else{
$branch = New Branch();
$branch->BRANCHNAME = $_POST['BRANCHNAME'];
$branch->BRANCHLOCATION = $_POST['BRANCHLOCATION'];
$branch->BRANCHCONTACTNO = $_POST['BRANCHCONTACTNO'];
$branch->BRANCHLEVEL = $_POST['BRANCHLEVEL'];
$branch->BRANCHSTATUS = $_POST['BRANCHSTATUS'];
$branch->BRANCHMANAGER = $_POST['BRANCHMANAGER'];
$branch->BRANCHDESCRIPTION = $_POST['BRANCHDESCRIPTION'];
//$branch->PICLOCATION = $_POST['PICLOCATION'];
$branch->_FILES = $_POST['PICLOCATION'];
$file =$_FILES['PICLOCATION'];
$filename = $file['name'];
$filepath = $file['tmp_name'];
$fileerror = $file['error'];
if ($fileerror == 0) {
$destfile = 'photos/'.$filename;
move_uploaded_file($filepath, $destfile);
$branch->LATITUDE = $_POST["LATITUDE"];
$branch->LONGITUDE = $_POST["LONGITUDE"];
$branch->create();
message("New Branch created successfully!", "success");
redirect("index.php");
}
}
}
}

Related

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image

This is simple php code which displays image chosen from directory, but when I run it, It shows torn image and doesn't display the actual image..
This is the output that I am getting
Does anyone know why is this happening?
I have tried to run this in all browsers, and it is still showing
This is the code:
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="p10a.php" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "C:/xampp/htdocs/LAMP LAB";
$target_file1 = basename($_FILES["file"]["name"]);
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";?><br><?php
$file = $target_file1;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024, 2); // kilobytes with two digits
echo "The size of your file is $filesize KB.";?><br><?php
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($file));?></p>
<br><br><br><br><b><?php
echo "<img src='C:/xampp/htdocs/LAMP LAB".$imageFileType."' width='200'> "; //display image
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
</body>
</html>
[This is the output that I am getting]
https://i.stack.imgur.com/mQNdX.png
Use the following code.
<html>
<head>
<title>PHP File Upload example</title>
</head>
<body style="background-color:cyan;">
<style>
p
{
background-color: yellow;
border: 3px solid black;
text-align: center;
}
#grad
{
background-image: linear-gradient(indigo,violet,cyan);
text-align: center;
}
</style>
<div id = "grad">
<b>
<form action="" enctype="multipart/form-data" method="post">
Select image from dir :
<input type="file" name="file"><br/><br>
<input type="submit" value="Upload" name="Submit1"> <br/>
</b>
</form><p>
<?php
if(isset($_POST['Submit1']))
{
$target_dir = "LAMP LAB/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
echo $target_file;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["file"]["name"])). " has been uploaded.";
echo "Content last changed: ".date("F d Y H:i:s.", filemtime($target_file));?></p>
<br><br><br><br><b><?php
echo "<img src='".$target_file."' width='200'> "; //display image
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
</body>
</html>

Script doesn't recognized file extension to upload pdf in php

I try to modify the php scrip to allow it to upload pdf instead of image. I've done several modification but none of them are working. I really appreciate if someone can show me how to modify this script to allow uploading the pdf.
I'm very new in php and need more guidance from php experts out there.
Thanks in advance for your kind assistance.
Anyway this is the code:
## Heading ##<html>
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
#uploader {
width: 300px;
height: 200px;
background: rgba(0,0,0,.075) url(../../img/pdf_icon.png) repeat fixed left;
border-radius:8px;
box-shadow: 5px 5px 10px 0px rgba(0,0,0,0.15);
display: block;
padding: 10px;
}
#uploader.highlight {
background:#ff0;
}
#uploader.disabled {
background:#aaa;
}
</style>
<script src="drag-drop-upload-pdf.js"></script>
</head>
<body>
<!-- DROP ZONE -->
<div id="uploader">
Muatnaik fail pdf di sini...
</div>
<!-- STATUS -->
<div id="upstat"></div>
<!-- FALLBACK -->
<form action="upload-pdf.php" method="post" enctype="multipart/form-data">
<br />
<input class="btn btn-primary" type="file" name="file-upload" id="file-upload" accept="pdf/*">
<br />
<br />
<input class="btn btn-primary" type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
## PHP Script ##
<?php
// SOURCE + DESTINATION
$source = $_FILES["file-upload"]["tmp_name"];
$destination = __DIR__.'/../../download/'. $_FILES["file-upload"]["name"];
echo "Uploaded ";
$error = "";
// CHECK IF FILE ALREADY EXIST
if (file_exists($destination)) {
$error = $destination . " already exist.";
}
// ALLOWED FILE EXTENSIONS
if ($error == "") {
$allowed = ["application/pdf", "application/x-pdf", "application/acrobat", "applications/vnd.pdf",
"text/pdf". "text/x-pdf"];
$ext = strtolower(pathinfo($_FILES["file-upload"]["name"], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
$error = "$ext file type not allowed. File must be uploaded in PDF format. - " . $_FILES["file-
upload"]["name"];
}
}
// LEGIT TEXT FILE CHECK
if ($error == "") {
if (getimagesize($_FILES["file-upload"]["tmp_name"]) == false) {
$error = $_FILES["file-upload"]["name"] . " is not a valid file.";
}
}
// FILE SIZE CHECK
if ($error == "") {
// 1,000,000 = 1MB
if ($_FILES["file-upload"]["size"] > 50000000) {
$error = $_FILES["file-upload"]["name"] . " - file size too big!";
}
}
// ALL CHECKS OK - MOVE FILE
if ($error == "") {
if (!move_uploaded_file($source, $destination)) {
$error = "Error moving $source to $destination";
}
}
// ERROR OCCURED OR OK?
if ($error == "") {
echo $_FILES["file-upload"]["name"] . " Upload DONE.";
} else {
echo $error;
}
?>
Try change this in HTML:
accept="application/pdf"

View the last image uploaded to the database using php

I am new in php and I am trying to view the last image uploaded to the database using php.
insertion code running perfectly but the selection one accrued an issue.
here is my code
<?php
if (isset($_POST['UploadImage'])) {
$image = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if ($image == '') {
echo "<script> alert('please choose picture') </script>";
} else if ($image_type != "image/jpeg" && $image_type != "image/png" && $image_type != "image/gif") {
echo "<script> alert('image format is not correct ') </script>";
} else {
$query = "INSERT INTO image (ImageLink) VALUES ('" . $image . "')";
if (mysqli_query($db1, $query)) {
echo '<script> alert("image uploaded successfully") </script>';
} else {
echo '<script> alert("please try again") </script>';
}
}
if (mysqli_affected_rows($db1) > 0) {
$query_image = "SELECT ImageLink FROM image ORDER BY Image_Id DESC LIMIT 1;";
$result = mysqli_query($db1, $query_image);
while ($row = mysqli_fetch_assoc($result)) {
echo "<img width='450' height='600' src='data:image/jpeg; base64,".base64_encode($row['ImageLink'])."' >";
echo "<br>";
}
}
}?>
while running... image doesn't appear in page.
please any help in doing that...
thank you
Solution is:
HTML code
<table
style="border-style: solid; border-color: gray; margin-top: 17px; width: 100%; height: 50%; width: 100%">
<tr>
<td>please upload a picture :</td>
<td><input type="file" name="image" id="image"></td>
</tr>
<tr></tr>
<tr>
<td> </td>
<td><input type="submit" value="Upload Image" name="UploadImage"
id="UploadImage"> </td>
</tr>
</table>
PHP Code
<?php
if(isset($_POST["UploadImage"])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if (isset($_POST["UploadImage"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["image"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$query = "INSERT INTO image (ImageLink) VALUES ('" . $target_file . "')";
if (mysqli_query($db1, $query)) {
echo '<script> alert("Image Has been Uploaded Successfully") </script>';
} else {
echo '<script> alert("Please Try Again") </script>';
}
if (mysqli_affected_rows($db1) > 0) {
$query_image = "SELECT ImageLink FROM image ORDER BY Image_Id DESC LIMIT 1;";
$result = mysqli_query($db1, $query_image);
while ($row = mysqli_fetch_assoc($result)) {
// var_dump( $row );
echo "<img width='450' height='600' src='data:image/jpeg; base64,".base64_encode(file_get_contents($row['ImageLink']))."'>";
echo "<br>";
}
}
}
}

Only allow image & PDF types in image uploader PHP script

I have a script that allows only 1 image to be uploaded which works fine.
But right now it allows any and all types to uploaded.
How do I only allow jpg, jpeg, gif, png & PDF files to be the only ones allowed to upload?
Here is part of my code.
<?php
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.success.php';
// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
//echo'<pre>';print_r($_FILES);exit;
// Now let's deal with the uploaded files
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}
// check at least one file was uploaded
if (count($active_keys) < 1)
{ echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>You must upload one file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\"> "; }
//count($active_keys)
//or error('No files were uploaded', $uploadForm);
// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname]['error'][$key] == 0)
or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
#is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
}
// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
{
$now++;
}
}
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
#move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
or error('receiving directory insuffiecient permission', $uploadForm);
}
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
if($_FILES['file']['error'] === UPLOAD_ERR_INI_SIZE) {
// Handle the error
echo 'Your file is too large.';
die();
}
// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<!--<b>Your proof is not a supported filetype.<br>
Please upload an image (jpg, gif, png, bmp file) or PDF file.
<br>
<br>
or</b>
<br>
<br>-->
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">";
}
/*
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
'<head>'."\n".
'<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
'<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
'<title>Upload error</title>'."\n\n".
'</head>'."\n\n".
'<body>'."\n\n".
'<div id="Upload">'."\n\n".
'<h1>Upload failure</h1>'."\n\n".
'<p>An error has occured: '."\n\n".
'<span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
*/
// < input id="file1" name="file[]" type="file" style="border: 1px solid white;">
//$fi= $_POST['file[]'];
//$fi = "(0)";
$fi = array($_FILES['file']['name']['0'],$_FILES['file']['name']['1'],$_FILES['file']['name']['2']);
====EDIT====
I was able to get it to ONLY allow images, but now how to I allow PDF's to be uploaded also?
I added this code to my script.
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
Just attached the following line in your code. its will checks upload file is image or pdf before it move to directory.
$allowedExts = array("gif", "jpeg", "jpg", "png", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "application/pdf")
&& in_array($extension, $allowedExts)) {
// put the upload code here
} else {
// put error message here
}
I was able to achieve this with the code below.
$thefilename = $_FILES["file"]["name"][0];
/* first, check for suffix
(jpg, gif, png, bmp file) or PDF file */
$thefilesuffix = substr($thefilename, -3);
// echo "<p>".$thefilesuffix."</p><hr />";
switch($thefilesuffix)
{
case "pdf": case "PDF":
/* don't need to do anything special,
but notice the capitalized versions */
break;
case "jpg": case "gif": case "png": case "bmp":
case "JPG": case "GIF": case "PNG": case "BMP":
//ALLOWS ONLY IMAGES TO BE UPLOADED
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
//ALLOWS ONLY IMAGES TO BE UPLOADED
break;
default:
echo "<table border=\"0\" cellspacing=\"4\" cellpadding=\"4\" style=\"border: 1px solid black; text-align: center; font-family: arial; font-size: 14px;\" width=\"600px\" align=\"center\">
<tr>
<td>
<font size=\"3\" color=\"red\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your proof must be an an image (jpg, gif, png, bmp file) or PDF file.<br>
Please upload a different file.</b>
<br>
<br>
Back to upload form
<br>
</td>
</tr>
</table> <div style=\"display: none;\">"; exit;
break;
}

How to add delete in php script in my photo gallery

I made a Photo gallery by php.
I am able to make upload image and show the image list. But i want to add a delete button where users can delete there unwanted image. But i was failed to add this button work.
Someone please help to fix it?
Here is my code on GitHub: https://github.com/sagar290/photo_gallerey/blob/6cad3743e735ea109723de7e14d5477bff1e964b/gallery.php
<?php
if (isset($_FILES["file"]["name"])) {
$name = $_FILES['file']['name'];
//$size = $_FILES['file']['size'];
//$extention = $type;
$type = strtolower($_FILES['file']['type']);
$tmp_name = $_FILES['file']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($type=='image/jpg')||($type=='image/jpeg')||($type=='image/gif')) {
$location = 'photos/';
if(move_uploaded_file($tmp_name, 'photos/'.$name)) {
echo $name.' is uploaded';
}
}else {
echo 'file must be jpg or jpeg ';
}
}else {
echo 'please choose a file';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo gallery</title>
<style type="text/css">
ul {
list-style-type: none;
}
li {
float: left;
padding: 10px;
margin: 10px;
font: bold 10px Verdana, sans-serif;
}
img {
display: block;
border: 1px solid #333300;
margin-bottom: 5px;
}
</style>
</head>
<body>
<h2>Photo gallery</h2>
<form action="gallery.php" method="POST" enctype="multipart/form-data">
UPLOAD:
<input type="file" name="file"><br><br>
<input type="submit" value="submit">
</form>
<ul>
<form action="gallery.php" method="POST">
<?php
//define location of photo image
$photosDir = './photos';
//define which file extention are images
$photosExt = array('gif','jpg','jpeg','tif','tiff','bmp','png');
//initialize array to hold filenames of images found
$photoList = array();
//read directory contents
//build photo list
if (file_exists($photosDir)) {
$dp = opendir($photosDir) or die('Error: cannot open file');
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
$fileData = pathinfo($file);
if (in_array($fileData['extension'], $photosExt)) {
$photoList[] = "$photosDir/$file"; // file includes as an array
}
}
}
closedir($dp);
}else {
die('ERROR: directory dosent exists');
}
//itarate over photo list
//display each image and file name
if (count($photoList)>0) {
for ($x=0; $x <count($photoList) ; $x++) {
?>
<li>
<input type="submit" name="delete" value="Delete">
<img src="<?php echo $photoList[$x]; ?>" height="150" width="200"/>
<?php echo basename($photoList[$x]); ?><br>
<?php echo round(filesize($photoList[$x])/1024) . 'KB'; ?>
</li>
<?php
}
} else {
die('ERROR: No image found');
}
?>
</form>
</ul>
</body>
</html>
hello just change your submit input to:
<input type="submit" name="delete" value="<?php echo $photoList[$x] ?>">
and then check for that value:
<?php if(isset($_POST['delete']) && !empty($_POST['delete'])){
//find the file
$file = 'photos/'.$_POST['delete'];
if(is_file($file)){
unlink($file);
}else{
echo $_POST['delete']." has not been found!";
}
}?>

Categories