How to add delete in php script in my photo gallery - php

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!";
}
}?>

Related

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"

if isset $_POST output fail

I'm trying to create a banning system for a chat that I made and it has a separate "console" only seen by admins. Im using Mac OS 10.11.4, I am the owner and am using Mamp with php version 5.6.10
Ban.php
<?php
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
//example ip addresses
if ($ban === '1.1.1.1' || 192.168.1.132) {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
Chat.php:
<?php
require "blocked.php";
require "connect.inc.php";
require "core.inc.php";
require "commands.php";
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
if (loggedin()) {
echo 'Welcome, '.$first,'<br />';
if ($first != 'SnR' || 'Koi') {
fwrite($activef, $active."\n"."=");
}
} else if (!loggedin()) {
die('Not logged in');
}
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
echo 'Cant send an empty message','<br />';
}
}
$file = "chat.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
if ($linecount > 49) {
unlink($file);
} else {
echo 'Line count: '.$linecount,'<br />';
}
echo 'Chat will reset at 50 lines','<br />';
echo 'Your IP:';
echo $ip_addr,'<br />';
?>
<html>
<head>
</head>
<body>
<!-- <a href='active.txt'>Online users</a><br /> -->
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
</html>
<?php
if ($first == 'SnR' && 'Koi') {
include 'AdminCMD.php';
include 'ban.php';
?>
<iframe id='reload' src='refresh2.php' class="field2">
<fieldset class="field">
</fieldset>
</iframe>
<?php
}
?>
The problem is that everything is fine until you give an input, no matter what you put into the box the output is always "Can't ban an Admin" meaning that it doesn't write to the given file
Thank you for any help.
Your code contains an error, preventing the file from being written. The first line of PHP code,$ban = $_POST['ban'];, could fail if no post data was sent. You need to first check if the $_POST['ban'] was set. A fixed version of your code can be found below.
<?php
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
When i ran your code it returns undefined index ban, you can try this and make sure what is not working for you.
<?php
$ban = isset($_POST['ban']) ? $_POST['ban'] : null;
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if(isset($ban)){
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>

excel data into database using php

this is my sample excelsheet values
State 1972-1973 1973-1974 1974-1975 1975-1976 1976-1977 1977-1978 1978-1979 1979-1980 1980-1981 1981-1982
Alabama $733,750 $1,066,300 $1,136,244 $1,343,670 $1,476,307 $1,642,927 $1,507,315 $1,849,825 $2,402,873 $2,079,000
Alaska $1,019,000 $1,100,000 $1,180,500 $1,172,300 $1,415,300 $1,411,700 $1,666,500 $2,026,400 $3,409,800 $7,200,000
Arkansas $890,496 $1,173,304 $1,193,362 $1,735,266 $1,824,536 $1,929,071 $2,090,590 $2,173,595 $2,042,632 $2,203,864
through php coding i need to store in db.how to store it.
just try this
<title>Upload page</title>
<style type="text/css">
body {
background: #E3F4FC;
font: normal 14px/30px Helvetica, Arial, sans-serif;
color: #2b2b2b;
}
a {
color:#898989;
font-size:14px;
font-weight:bold;
text-decoration:none;
}
a:hover {
color:#CC0033;
}
h1 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #CC0033;
}
h2 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #898989;
}
#container {
background: #CCC;
margin: 100px auto;
width: 945px;
}
#form {padding: 20px 150px;}
#form input {margin-bottom: 20px;}
</style>
</head>
<body>
<div id="container">
<div id="form">
<?php
include "e2.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE books"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT INTO books (BookID,Title,Author,PublisherName,CopyrightYear) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='index.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
</html>
this is e2.php
$db = mysql_connect("localhost","root","") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("books",$db))
die("No database selected.");
?>
Try this
simplex excel library and script you can create your own excel import to mysql.
if (isset($_FILES['file'])) {
require_once "simplexlsx.class.php";
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
echo '<h1>Parsing Result</h1>';
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
list($cols,) = $xlsx->dimension();
foreach( $xlsx->rows() as $k => $r) {
// if ($k == 0) continue; // skip first row
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo '<td>'.( (isset($r[$i])) ? $r[$i] : ' ' ).'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
<h1>Upload</h1>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file" /> <input type="submit" value="Parse" />
</form>
the following worked for me if the source is a csv file:
$filename = "/path/to/your/csvfile.csv";
$handle = fopen ($filename, "r");
$buffer = "";
while (!feof($handle)) {
$buffer .= fgets($handle, 16384);
}
$array = parse_csv_php($buffer);
// do what you want with your array...
function parse_csv_php(&$data,$delim=';',$enclosure='"'){
$enclosed=false;
$fldcount=0;
$linecount=0;
$fldval='';
for($i=0;$i<strlen($data);$i++) {
$chr=$data{$i};
switch($chr) {
case $enclosure:
if($enclosed&&$data{$i+1}==$enclosure) {
$fldval.=$chr;
++$i; //skip next char
} else { $enclosed=!$enclosed; }
break;
case $delim:
if(!$enclosed) {
$ret_array[$linecount][$fldcount++]=$fldval;
$fldval='';
} else { $fldval.=$chr; }
break;
case "\r":
if(!$enclosed&&$data{$i+1}=="\n")
continue;
case "\n":
if(!$enclosed) {
$ret_array[$linecount][$fldcount]=$fldval;
$linecount++;
$fldcount=0;
$fldval='';
} else { $fldval.=$chr; }
break;
default:
$fldval.=$chr;
}
}
if($fldval) {
$ret_array[$linecount][$fldcount]=$fldval;
}
return $ret_array;
}

PHP search engine in a txt file

I need to create a basic search engine with PHP to search for an ID within a .txt file but still don't know how to do it, I'm new programming :(
Any help would be much appreciated.
Here's the code I have so far.
<style type="text/css">
td {
font-family:verdana,arial;
font-size:8pt;
border-color:#ccc; }
.header{
background-color:66b50b;
border-style:solid;
border-color:#32661e;
border-width:1px;
font-weight:bold;
font-size:10pt;
color:ffffff; }
.estiloceldaw{
background-color:ffffff;
border-style:solid;
border-color:666666;
border-width:1px; }
.estiloceldag{
background-color:ddeeff;
color:333333;
font-weight:bold;
font-size:10pt; }
</style>
<?php
$criterioid=$_POST["id"];
echo $criterioid;
$critrionombre=$_POST["nombre"];
$catalogo= array();
$datospelicula = array("clave","titulo","sinopsis","genero","anio","precio","status");
function TraeCatalogo()
{
$numregistros=0;
$ar=fopen("catalogo.txt","r") or
die("No se pudo abrir el archivo");
while (!feof($ar)) {
$linea=fgets($ar);
$catalogo[] = $datospelicula =explode("|",$linea);
$numregistros=$numregistros+1;
}
fclose($ar);
echo "numero de registros".$numregistros;
return $catalogo;
}
function Muestralistado($catalogo,$criterioid,$criterionombre)
{
$tabla= "<table><tr colspan=6><td>Clave</td><td>Nombre</td><td>Sinopsis</td><td>Genero</td><td>Año</td><td>precio</td><td>Status</td></tr>";
if (!isset($criterioid) || trim($criterioid) == "")
{
foreach ($catalogo as $k => $pelicula)
{
$clave=$catalogo[$k][0];
$titulo=$catalogo[$k][1];
$sinopsis=$catalogo[$k][2];
$genero=$catalogo[$k][3];
$anio=$catalogo[$k][4];
$precio=$catalogo[$k][5];
$status=$catalogo[$k][6];
$tabla.="<tr><td>".$clave."</td><td>".$titulo."</td><td>".$sinopsis."</td><td>".$genero."</td><td>".$anio."</td><td>".$precio."</td><td>".$status."</td></tr>";}
}else
{
$tabla.="<tr><td colspan=6>hay un criterio de busqueda!</td></tr>";
} $tabla.="<table>";
echo $tabla;
}
$catalogo2=TraeCatalogo("wa");
Muestralistado($catalogo2);
//var_dump($catalogo2);
?>
<html>
<body> Buscar Pelicula: <form action="index.php" method="post">
Nombre: <input type="text" name="nombre"> id: <input type="text" name="id"> <input type="submit">
</form>
</body>
</html>
$foundText = array(); // Create an array to store your found words
Then, once you've opened the file:
while (!feof($ar))
{
$dataBuffer = fgets($ar); // Load some text into buffer
$explodedText = explode($dataBuffer, "|");
foreach($explodedText as $item){
if(strpos($item, $clave) != false)
$foundText[] = $dataBuffer ;
}
}
}
And then you can iterate through each found item:
foreach($foundText as $textItem){
echo 'Word found: ' . $textItem . ' <br>';
}

php image upload

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");
}
}
}
}

Categories