I am trying to make image show permanent on refreshing.
The image should be constant. We can add images and text permanent and we can add more posts.
A database called image_upload and create a table called images with fields:
id - int(11)
image - varchar(100)
image_text - text
index.php
<?php
// Create database connection
$db = mysqli_connect("localhost", "root", "", "image_upload");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Help me How to solve this problem. I have created database and uploading images and text. while refreshing page. The posts is repeating after and after.
It now works. Tested. For over two hours I was baffled why the page could not redirect after successful upload. Undoing some indentations at the top of the page solved the problem.
<?php
session_start();
// Create database connection
$db = mysqli_connect("localhost", "root", "", "image_upload");
if(isset($_POST['image_text'])){
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
}
if(isset($_FILES['image'])){
// Get image name
$image = $_FILES['image']['name'];
$tempath = $_FILES['image']['tmp_name'];
}
// If upload button is clicked ...
if(isset($_POST['upload'])){
if(isset($image) && isset($tempath) && !empty($image)){
$image = time()."_".$image;
$image_folder = "images/";
if(is_uploaded_file($tempath)){
if(move_uploaded_file($tempath, $image_folder.$image)) {
$image_uploaded = true;
}
}
}else{
$msg = "Failed to upload image";
}
if(isset($image_uploaded) && ($image_uploaded == true)){
$sql = "INSERT INTO images (image, image_text) VALUES('$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
$sent = true;
$_SESSION['sent'] = "Image uploaded successfully";
}
}
if(isset($sent) && ($sent == true)){
header("Location: index.php");
exit();
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
if(isset($_SESSION['sent'])){
echo "<p style='color:#006400;font-weight:bold;'>" . $_SESSION['sent'] . "</p>";
unset($_SESSION["sent"]);
}
if(isset($msg)){
echo "<p style='color:#ff0000;font-weight:bold;'>" . $msg . "</p>";
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
}else{
echo "<h4>No data has been uploaded</h4>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Hopefully the following will provide guidance ~ fully working but the paths used to store images is relevant to my laptop so you'll need to edit that portion slightly.
<?php
session_start();
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$msg='Failed to upload image';
/* utility to find error if something goes wrong */
function uploaderror( $error ){
switch( $error ) {
case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini";
case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded";
case UPLOAD_ERR_NO_FILE: return "No file was uploaded";
case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder";
case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk";
case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension";
default: return "Unknown upload error";
}
}
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES['image'] ) && isset( $_POST['image_text'] ) ){
try{
/* try to filter input of bad characters though using a prepared statement should help */
$text=filter_input( INPUT_POST, 'image_text', FILTER_SANITIZE_STRING );
/* get a reference to the uploaded FILE object*/
$obj=(object)$_FILES['image'];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
/* proceed to save file and log to db */
if( is_uploaded_file( $tmp ) && $error==UPLOAD_ERR_OK ){
#$destination = 'images/' . $name;
$root='c:/wwwroot';
$path='/images/tmp/';
$filepath = $path. $name;
$destination=$root . $filepath;
$status=move_uploaded_file( $tmp, $destination );
if( $status ){ /* moved/saved the file OK */
/* create a prepared statement */
$sql='insert into `images` ( `image`, `image_text`) values (?,?)';
$stmt=$db->prepare( $sql );
if( $stmt ){/* bind variables to placecholders ~ store path to image rather than just image name */
$stmt->bind_param('ss', $filepath, $text );
$status = $stmt->execute();
$stmt->close();
$msg = $status ? 'Image uploaded successfully' : 'Failed to log image to database';
}
} else {
throw new Exception('unable to move file');
}
} else {
throw new Exception( sprintf( 'error: possible file upload attack - %s',uploaderror( $error ) ) );
}
}catch( Exception $e ){
$msg = $e->getMessage();
}
}
/* fetch all image details from db */
$sql='select `image`,`image_text` from `images`;';
$result=$db->query( $sql );
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style>
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
$i=0;
while( $row = $result->fetch_object() ) {
$i++;
/* an ID MUST be unique! */
echo "
<div class='img_div' id='img_div__$i'>
<img src='{$row->image}' />
<p>{$row->image_text}</p>
</div>";
}
?>
<form method='POST' enctype='multipart/form-data'>
<input type='hidden' name='MAX_FILE_SIZE' value='1000000' />
<div>
<input type='file' name='image' />
</div>
<div>
<textarea
id='text'
cols='40'
rows='4'
name='image_text'
placeholder='Say something about this image...'></textarea>
</div>
<div>
<button type='submit' name='upload'>POST</button>
<?php
if( !empty( $msg ) && $_SERVER['REQUEST_METHOD']=='POST' ) echo $msg;
?>
</div>
</form>
</div>
</body>
</html>
Related
My Use case:
On my server I have 4 folders, On upload page I need to list those folder in drop-down. User first select multiple image files stored in local storage and select a desired server folder from drop-down where he/she wants to upload and then click on upload button.
I have coded it in PHP accordingly, I have achieve the above use case but with single image only. I am not able to select the multiple image files.
Below is my upload.php file:
<?php
session_start();
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit;
} else {
if ($_POST['variable'] == '')
{
$variable = './'; // default folder
}
else
{
$variable = $_POST['variable'] ;
}
$folder = $variable;
$uploadpath = "$folder/";
$max_size = 20000;
$alwidth = 9000;
$alheight = 8000;
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png', 'webp');
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext);
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);
$err = '';
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
echo 'File: <b>'. basename( $_FILES['fileup']['name']). '</b> successfully uploaded:';
echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
echo '<br />Size: <b>'. number_format($_FILES['fileup']['size']/1024, 3, '.', '') .'</b> KB';
if(isset($width) && isset($height)) echo '<br/>Image Width x Height: '. $width. ' x '. $height;
echo '<br/><br/>Image address: <b>http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'</b>';
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
}
?>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
margin: 50px auto;
text-align: center;
width: 800px;
}
h1 {
font-family: 'Passion One';
font-size: 2rem;
text-transform: uppercase;
}
label {
width: 150px;
display: inline-block;
text-align: left;
font-size: 1.5rem;
font-family: 'Lato';
}
input {
border: 2px solid #ccc;
font-size: 1.5rem;
font-weight: 100;
font-family: 'Lato';
padding: 10px;
}
form {
margin: 25px auto;
padding: 20px;
border: 5px solid #ccc;
width: 500px;
background: #eee;
}
div.form-element {
margin: 20px 0;
}
button {
padding: 10px;
font-size: 1.5rem;
font-family: 'Lato';
font-weight: 100;
background: yellowgreen;
color: white;
border: none;
}
p.success,
p.error {
color: white;
font-family: lato;
background: yellowgreen;
display: inline-block;
padding: 2px 10px;
}
p.error {
background: orangered;
}
</style>
<div style="margin:1em auto; width:333px; text-align:center;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
enctype="multipart/form-data">
Upload File: <input type="file" name="fileup" /><br/>
<select name="variable" />
<option value=null selected="selected">Select a folder</option>
<html>
<body>
<form name="input" action="upload.php" method="post" onchange="this.form.submit()">
<?php
$dirs = glob("*", GLOB_ONLYDIR);
foreach($dirs as $val){
echo '<option value="'.$val.'">'.$val."</option>\n";
}
?>
</select>
<input type="submit" name='submit' value="UPLOAD" />
</div>
</form>
<button>
LOGOUT</button>
</div>
</body>
</html>
Below is the UI:
Im trying to create a way to upload images to a page but when i load the page i get the following result: Result
Why arent the images showing up? im cofused.
I have been hours trying to find the solution but i end up in the same place.
Code:
<?php
// Create database connection
include ('config.php');
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['IMG_Link']['IMG_Name'];
// Get text
$image_text = mysqli_real_escape_string($link, $_POST['IMG_Name']);
// image file directory
$target = "GenFeed/".basename($image);
$sql = "INSERT INTO GenFeed (IMG_Link, IMG_Name) VALUES ('$image', '$image_text')";
// execute query
mysqli_query($link, $sql);
if (move_uploaded_file($_FILES['IMG_Link']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($link, "SELECT * FROM GenFeed");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='GenFeed/".$row['IMG_Link']."' >";
echo "<p>".$row['IMG_Name']."</p>";
echo "</div>";
}
?>
<form method="POST" action="ImageUpload.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="IMG_Link">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="IMG_Name"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Hope you guys can help me out on this one
PD: im aware the im using superglobal variables
I have written a PHP code to upload files from the azure web app (using an upload button from a browser) to azure blob container. I am successfully able to upload the files to the blob container, however, once uploaded the file sits in azure blob as 0 bytes without any extension. I am unable to view the file as well and the following message is shown 'The file '1721405003' may not render correctly as it contains an unrecognized extension'.
Below is my php code to upload files to blob -
<?php
error_reporting(0);
?>
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException;
use WindowsAzure\Common\ServicesBuilder;
// If upload button is clicked ...
if (isset($_POST['upload'])) {
//upload to azure blob container
$connectionString = "conn key"; //Enter deployment key
$containerName = 'sidblobcontainer';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$file_name = $_FILES['myFile']['name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$content = fopen($file_name, "r");
$blob_name = "myblob".'.'.$ext;
try {
//Upload blob
$blobClient->createBlockBlob($containerName, $blob_name, $content);
echo "successfull";
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
//upload to azure mysql database server
$filename = $_FILES["myFile"]["name"];
$tempname = $_FILES["myFile"]["tmp_name"];
$folder = "image/".$filename;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = mysqli_connect("demoserversid.mysql.database.azure.com",
"siddarth#demoserversid", "****", "images");
// Get all the submitted data from the form
$sql = "INSERT INTO demo (siddemo) VALUES ('$filename')";
// Execute query
mysqli_query($db, $sql);
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM demo");
?>
<!DOCTYPE html>
<html>
<head>
<style> #content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}</style>
<title>Image Upload</title>
<body>Upload to azure</body>
<link rel="stylesheet" type= "text/css" href ="style.css"/>
<div id="content">
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="uploadfile" value=""/>
<div>
<button type="submit" name="upload">UPLOAD</button>
</div>
</form>
</div>
</body>
</html>
Here is the message that I see in blob container
I removed the part that related to mysql and the code below works for me:
<?php
error_reporting(0);
?>
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException;
use WindowsAzure\Common\ServicesBuilder;
// If upload button is clicked ...
if (isset($_POST['upload'])) {
$connectionString = "<conn str>"; //Enter deployment key
$containerName = '<container name>';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$file_name = $_FILES['fileToUpload']['name'];
error_log($file_name);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$content = fopen($_FILES['fileToUpload']["tmp_name"], "r");
$blob_name = "myblob".'.'.$ext;
try {
//Upload blob
$blobClient->createBlockBlob($containerName, $blob_name, $content);
echo "successfull";
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style> #content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}</style>
<title>Image Upload</title>
<body>Upload to azure</body>
<link rel="stylesheet" type= "text/css" href ="style.css"/>
<div id="content">
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload"/>
<div>
<button type="submit" name="upload">UPLOAD</button>
</div>
</form>
</div>
</body>
</html>
Result:
Hello I would like to know how to add a description, title, & keywords to my file upload script? I already have the file upload working.
So I want people to be able to enter a title and description and keywords and save it to the database.
P.S: I already have the file upload system working. User uploads file saves it to a temp folder and uploads it to database so you don’t need to mess with the file uploading part just adding the title, keywords, & description.
File Upload Script:
This allows file uploads.
<?php
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>
<?php
session_start();
include_once "vendor/autoload.php";
$page = new membership\Page(1);
if ($page->isValid() == true) {
?>
<center>
<div class='container'>
<div class='row'>
<div class='col-xs-8 col-xs-offset-2 well'>
<form action='upload.php' method='post' enctype='multipart/form-data'>
<legend>Select File to Upload:</legend>
<div class='form-group'>
<input type='textname' name='title' />
<input type='textname' name='desc' />
<input type='file' name='file1' />
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Upload' class='btn btn-info'/>
</div>
<?php if (isset($_GET['st'])) { ?>
<div class='alert alert-danger text-center'>
<?php
if ($_GET['st'] == "success") {
echo "File Uploaded Successfully!";
} else {
echo 'Invalid File Extension!';
}
?>
</div>
<?php } ?>
</form></div></div></center>
<?php } ?>
upload.php:
This is the file that controls the file upload.
<?php include('dbconnect.php'); ?>
<?php
//check if form is submitted
if (isset($_POST['submit']))
{
$filename = $_FILES['file1']['name'];
//upload file
if($filename != '')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = ['zip', 'rar', 'php', 'html', 'sql'];
//check if file type is valid
if (in_array($ext, $allowed))
{
// get last record id
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
if (count($result) > 0)
{
$row = mysqli_fetch_array($result);
$filename = ($row['id']+1) . '-' . $filename;
}
else
$filename = '1' . '-' . $filename;
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H:i:s');
move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: new-project.html?st=success");
}
else
{
header("Location: new-project.html?st=error");
}
}
else
header("Location: new-project.html");
}
?>
MySQL:
CREATE TABLE IF NOT EXISTS `tbl_files` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`filename` varchar(255) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
Also I need help on creating the tables for the keywords, title, & description.
EDIT: : So I got everything working but now I can’t get the title to display on the page it’s just blank. Anyway here’s the code for the project display:
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>
<div class="gboxtop"></div>
<div div="button-pro">
<button>New Project</button>
</div>
<div class="left">
<div class="left_articles">
<h2>Lastest Projects</h2>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>File Name</th>
<th>View</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['title']; ?></td>
<td>View</td>
<td><a href="uploads/<?php echo $row['filename']; ?>" download>Download</td>
</tr>
<?php } ?>
</tbody>
</table>
</div></div></div>
</div></div></div></div>
//Start Table Style
<style>table.blueTable {
border: 1px solid #1C6EA4;
background-color: #EEEEEE;
width: 100%;
text-align: left;
border-collapse: collapse;
}
table.blueTable td, table.blueTable th {
border: 1px solid #AAAAAA;
padding: 3px 2px;
}
table.blueTable tbody td {
font-size: 13px;
}
table.blueTable tr:nth-child(even) {
background: #D0E4F5;
}
table.blueTable thead {
background: #1C6EA4;
background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
border-bottom: 2px solid #444444;
}
table.blueTable thead th {
font-size: 15px;
font-weight: bold;
color: #FFFFFF;
border-left: 2px solid #D0E4F5;
}
table.blueTable thead th:first-child {
border-left: none;
}
table.blueTable tfoot {
font-size: 14px;
font-weight: bold;
color: #FFFFFF;
background: #D0E4F5;
}
.button-pro {
float: right;
}
</style>
run:
ALTER TABLE tbl_files ADD title VARCHAR(255) AFTER created;
edit:
<input type='text' name='title' maxlength="255"/>
add before // insert file details into database:
$title = '';
if(!empty($_POST['title']))
{
$title = mysqli_real_escape_string($con, $_POST['title']);
}
edit:
$sql = "INSERT INTO tbl_files(filename, created, title) VALUES('$filename', '$created', '$title')";
the rest by analogy
This is the file upload.php. When I try to submit the HTML form and get the value of stateCode it throws an unspecified index error, please see attached screenshot
<html>
<body>
<?php
$target_dir = getcwd().DIRECTORY_SEPARATOR."/files/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]
["name"]);
$dst = $target_file;
$uploadOk = 1;
echo $_POST['stateCode'] ;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["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["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "xls" && $imageFileType != "xlsx" ) {
echo "Sorry, only Excel 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["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
</body>
</html>
The following is welcome.html whenever I try to submit this form I get the below error.
<!DOCTYPE html>
<html>
<style>
#form {
background-color: #FFF;
height: 600px;
width: 600px;
margin-right: auto;
margin-left: auto;
margin-top: 0px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
padding: 0px;
text-align:center;
}
label {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 18px;
color: #333;
height: 35px;
width: 200px;
margin-top: 18px;
margin-left: 10px;
text-align: right;
margin-right:15px;
float:left;
}
iframe {
height:35px;
width: 300px;
margin-top:14px;
}
button{
margin-top: 18px;
}
</style>
<script>
var dvalues='';
function myFunction(){
var iframe = document.getElementById('frame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var b =innerDoc.body;
var c = b.childNodes;
var dvalues = b.childNodes[0].value;
document.getElementById("placeholder").innerHTML =dvalues;
}
window.onload = function(){
document.getElementById("placeholder").innerHTML=dvalues;
};
</script>
<body>
<div id = "form">
<form action="upload.php" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<label for="States" name ="states">States:</label>
<iframe id ="frame" name="myPHPScript" src="myScript.php" width="100%" frameborder="0"></iframe>
<p id = "placeholder" name="stateCode"></p>
<input type="file" name="fileToUpload" id="fileToUpload" /><input type="submit" name="action"onclick="myFunction()"/>
</div>
</fieldset>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<style>
#form {
background-color: #FFF;
height: 600px;
width: 600px;
margin-right: auto;
margin-left: auto;
margin-top: 0px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
padding: 0px;
text-align:center;
}
label {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 18px;
color: #333;
height: 35px;
width: 200px;
margin-top: 18px;
margin-left: 10px;
text-align: right;
margin-right:15px;
float:left;
}
iframe {
height:35px;
width: 300px;
margin-top:14px;
}
button{
margin-top: 18px;
}
</style>
<script>
var dvalues='';
function myFunction(){
var iframe = document.getElementById('frame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var b =innerDoc.body;
var c = b.childNodes;
var dvalues = b.childNodes[0].value;
document.getElementById("placeholder").innerHTML =dvalues;
}
window.onload = function(){
document.getElementById("placeholder").innerHTML=dvalues;
};
</script>
<body>
<div id = "form">
<form action="upload.php" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<label for="States" name ="states">States:</label>
<iframe id ="frame" name="myPHPScript" src="myScript.php" width="100%" frameborder="0"></iframe>
<p id = "placeholder"></p>
<input type="text" name="stateCode" />
<input type="file" name="fileToUpload" id="fileToUpload" /><input type="submit" name="action"onclick="myFunction()"/>
</div>
</fieldset>
</form>
</div>
</body>
</html>
Fixed p into input type text. Not sure what you actually intended the type to be but that should get you running.