How to insert xml process instruction upon upload on database - php

I found a code from one of the questions here on SO. I wonder where I will put this code on my upload function so it will insert this line:
<?xml-stylesheet type="text/xsl" href="foreach_template.xsl"?>
before it would be uploaded on the database.
*note: I have this table on the database which has the following columns:
id - int(3)
title - varchar(50)
name - varchar(50)
type - varchar(25)
size - int(10)
content - mediumblob
*note: Also I have a folder where the xml files are uploaded
uploadprocess.php
<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$title = $_POST['title'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
$xml = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($xml, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$file = strip_tags(mysql_real_escape_string($filename.$ext));
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
if ($_FILES["userfile"]["type"] == "text/xml")
{
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO xmltable (title, name, size, type, content) ".
"VALUES ('$title','$file', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
move_uploaded_file($_FILES["userfile"]["tmp_name"], $full_local_path);
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
else
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
}
?>
upload.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>XML Upload</title>
</head>
<body>
<div style="font-family:verdana;padding:50px 10px 0px 0px;border:5px solid #4D4D4D;">
<form action="uploadprocess.php" enctype="multipart/form-data" method="post">
<center>
<p>
TITLE OF THE ARTICLE <input name="title" type="text" id="title" /><br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile" />
<input name="upload" type="submit" class="box" id="upload" value=" Upload ">
</p>
</center>
</div>
<br />
<div>
<table border="1" align="center">
<tr>
<td align="center" width="100px">ID</td>
<td align="center" width="100px">TITLE</td>
<td align="center" width="100px">LINK</td>
</tr>
<?php
include ('connection.php');
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$resultsPerPage = 5;
$startResults = ($page - 1) * $resultsPerPage;
$numberOfRows = mysql_num_rows(mysql_query('SELECT id FROM xmltable'));
$totalPages = ceil($numberOfRows / $resultsPerPage);
$query = mysql_query("SELECT * FROM xmltable LIMIT $startResults, $resultsPerPage");
while ($output = mysql_fetch_assoc($query))
{
echo "<tr><td>".$output['id']."</td>";
echo "<td>".$output['title']."</td>";
echo "<td>";
?>
<a class="del" href="/xml/images/<?php echo $output['name']; ?>" class="del">View Article</a>
</td></tr>
<?php
}
?>
</div>
<div id="pagination">
<div id="pagiCount">
<center>
<?php
echo '<span id="prev"> | First |</span>';
if ($page > 1)
{
echo '<span id="prev"> <a href="?page='.($page - 1).'">| Prev |';
}
for($i = 1; $i <= $totalPages; $i++)
{
if($i == $page)
echo '<strong>'.$i.'</strong>';
else
echo ''.$i.'';
}
if ($page < $totalPages)
echo '<span id="next"> | Next |</span>';
echo '| Last |';
?>
</center>
</div>
</div>
</table>
</form>
</body>
and view.php
<?php
include 'connection.php';
$name=$_GET['name'];
$sql="SELECT * FROM xmltable WHERE name = '$name'";
$rs=mysql_query($sql);
if (!$rs)
{
echo "failed to connect";
}
else
{
while($row = mysql_fetch_array($rs))
{
show_source("images/".$row['name']);
}
}
?>
Where can I put this code? And is it correct?
$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?><root/>');
$dom->insertBefore($dom->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="foreach_template.xsl"'), $dom->documentElement);
echo $dom->saveXml();
Sorry if you find it long to read. Please help. Thank You!

<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
if ($_FILES['userfile']['type'] == 'text/xsl')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else if($_FILES['userfile']['type'] != 'text/xml')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else
{
$userfile = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($userfile, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
$xslt = strip_tags(mysql_real_escape_string($filename.$ext));
$xml = new DOMDocument('1.0', 'utf-8');
$xml->load($tmpName);
$xml->insertBefore($xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/foreach_template.xsl"'), $xml->documentElement);
$xml->formatOutput = true;
$xml->saveXml();
$xml->save($tmpName);
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
print_r($tmpName);
var_dump($tmpName);
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
move_uploaded_file($tmpName, $full_local_path);
$query = "INSERT INTO xmltable (name, size, type, content) "."VALUES ('$xslt', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
}
?>

Related

error displaying images - code from PHP & MySQL Novice to Ninja

I am new to PHP and MySQL and in 2 chapters of Kevin Yank's book - PHP & MySQL Novice to Ninja there are mistakes in the code. The only one I haven't figured out lies in chapter 12, and having tried suggestions from multiple posts on this and other fora, nothing works. Thanks to in advance for your help
Problem: Blob gives problem to load:
The image "http://localhost/chapter12/filestore5/index.php?action=view&id=5" cannot be displayed because it contains errors
All other functions: upload, description, delete works perfectly.
index.php file
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
if (isset($_POST['action']) and $_POST['action'] == 'upload') {
// Bail out if the file isn't really an upload
if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
$error = 'There was no file uploaded!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$uploadfile = $_FILES['upload']['tmp_name'];
$uploadname = $_FILES['upload']['name'];
$uploadtype = $_FILES['upload']['type'];
$uploaddesc = $_POST['desc'];
$uploaddata = file_get_contents($uploadfile);
include 'db.inc.php';
try {
$sql = 'INSERT INTO filestore SET
filename = :filename,
mimetype = :mimetype,
description = :description,
filedata = :filedata';
$s = $pdo->prepare($sql);
$s->bindValue(':filename', $uploadname);
$s->bindValue(':mimetype', $uploadtype);
$s->bindValue(':description', $uploaddesc);
$s->bindValue(':filedata', $uploaddata);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error storing file!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
if (isset($_GET['action']) and ($_GET['action'] == 'view' or $_GET['action'] == 'download') and isset($_GET['id'])) {
include 'db.inc.php';
try {
$sql = 'SELECT filename, mimetype, filedata
FROM filestore
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_GET['id']);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error fetching requested file.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$file = $s->fetch();
if (!$file) {
$error = 'File with specified ID not found in the database!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download') {
$mimetype = 'application/octet-stream';
$disposition = 'attachment';
}
// Content-type must come before Content-disposition
header('Content-length: ' . strlen($filedata));
header("Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
echo $filedata;
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'delete' and isset($_POST['id'])) {
include 'db.inc.php';
try {
$sql = 'DELETE FROM filestore
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error deleting requested file.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
include 'db.inc.php';
try {
$result = $pdo->query('SELECT id, filename, mimetype, description
FROM filestore');
}
catch(PDOException $e) {
$error = 'Database error fetching stored files.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$files = array();
foreach($result as $row) {
$files[] = array(
'id' => $row['id'],
'filename' => $row['filename'],
'mimetype' => $row['mimetype'],
'description' => $row['description']
);
}
include 'files.html.php';
?>
HTML file
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP/MySQL File Repository</title>
</head>
<body>
<h1>PHP/MySQL File Repository</h1>
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="upload">Upload File:
<input type="file" id="upload" name="upload"></label>
</div>
<div>
<label for="desc">File Description:
<input type="text" id="desc" name="desc"
maxlength="255"></label>
</div>
<div>
<input type="hidden" name="action" value="upload">
<input type="submit" value="Upload">
</div>
</form>
<?php if (count($files) > 0): ?>
<p>The following files are stored in the database:</p>
<table>
<thead>
<tr>
<th>Filename</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php foreach($files as $f): ?>
<tr>
<td>
<a href="?action=view&id=<?php htmlout($f['id']); ?>
"><?php htmlout($f['filename']); ?></a>
</td>
<td><?php htmlout($f['mimetype']); ?></td>
<td><?php htmlout($f['description']); ?></td>
<td>
<form action="" method="get">
<div>
<input type="hidden" name="action"
value="download"/>
<input type="hidden" name="id"
value="<?php htmlout($f['id']); ?>"/>
<input type="submit" value="Download"/>
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="action" value="delete"/>
<input type="hidden" name="id"
value="<?php htmlout($f['id']); ?>"/>
<input type="submit" value="Delete"/>
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</body>
</html>
Finally got back to fixing the code and found a workable solution here:
https://www.sitepoint.com/community/t/problem-using-php-to-pull-binary-files-from-a-blob-field-in-mysql/6431/16
I added in "while (#ob_end_clean());" after the magicquotes in index.php and all works well.
According to what this person found in another forum, if server has output buffering on, then it won't send the image data correctly.

How to upload/insert image/photo on mysql using php

I searched for some solution and it seems can work by adding some code in it. My codes seems doesn't work. I don't know what to do. I'm new in php. The input type file seems working but the upload button doesn't work and it seems that is the problem of this.
<?php
include ('LoginFunction.php');
$conn = mysqli_connect('localhost','root','','danganan');
$user = $_SESSION['Username'];
$query = "SELECT * FROM tblactivity WHERE Username = '$user'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result);
This is the upload function
if (isset($_POST['upload'])) {
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tem_loc = $_FILES['file']['tmp_name'];
$file_store = "uploads/".$file_name;
if(move_uploaded_file($file_tem_loc, $file_store)) {
echo "Image uploaded!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile info</title>
</head>
<body>
<form method="POST">
<div class="container">
<h1><?php echo "Welcome " . " " . $user; ?></h1>
<img src="<?php $row['Picture']; ?>" width=150; height=150;>
<div class="send-button">
<input type="file" name="file" style="margin-right: -76px;"><br><br>
<input type="submit" name="upload" value="Upload">
<?php
$folder = "uploads/";
if(is_dir($folder)) {
if ($open = opendir($folder)) {
while (($file = readdir($open)) !=false) {
if($file == '.' || $file == '..') continue;
echo '<img src ="uploads/'.$file.'" width = "150" height=150>';
}
closedir($open);
}
}
?>
</div>
<input type="hidden" name="usrid" value="<?php echo $row['ID']; ?>">
<h2>FIRST NAME</h2><input type="text" name="fname" value="<?php echo $row['Fname']; ?>">
<h2>LAST NAME</h2><input type="text" name="lname" value="<?php echo $row['Lname']; ?>">
<h2>USERNAME</h2><input type="text" name="uname" value="<?php echo $row['Username']; ?>">
<h2>PASSWORD</h2><h3><?php echo $row['Password']; ?></h3>
</form>
</body>
</html>

ajax php sql without refreshing

I'm not familiar with ajax and I'm trying to submit a form using one PHP page and ajax so that after form is submitted/updated the page doesn't refresh completly. the php page is loaded on a div section of a parent page.
Can someone point me in the right direction how to submit the form without refreshing the entire page?
Below the code I have so far, and it is only all in one php file. Thank you
<?php
$servername = "data";
$username = "data";
$password = "data";
$database = "data";
$successAdd="";
$errorAdd="";
$connect = mysql_connect($servername, $username, $password) or die("Not Connected");
mysql_select_db($database) or die("not selected");
if (isset($_POST['Add'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$sql = "INSERT INTO `categorytable`(`category`) VALUES ('$venueName')";
$result = mysql_query($sql, $connect);
if ($result != 0) {
$successAdd = "Success fully done";
} else {
$errorAdd = "Not done ";
}
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
if (isset($_POST['Update'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$successAdd = "Success fully done";
}else{
$errorAdd = "Not Updated";
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3 style="color: red"><?php echo $errorAdd; ?></h3>
<h3 style="color: green"><?php echo $successAdd; ?></h3>
<!--<div style="float: left;width: 50%">-->
<h1>Add Category</h1>
<form action="" method="POST" enctype="multipart/form-data" id="add-category" >
Category Name <input type="text" name="cname" value="" /><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Add" name="Add"/>
</form>
<!--</div>-->
<!--<div style="float: left;width: 50%">-->
<h1>Update Category</h1>
<form action="addCategory.php" method="POST" enctype="multipart/form-data" >
Select Category<select name="cname">
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row[1]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Update" name="Update"/>
</form>
<!--</div>-->
<div style="width: 25%;margin: 20px auto;float: left">
<table border="1">
<tr>
<th>Category Name</th>
<th>Category Image</th>
</tr>
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td>
<img src="images/category/<?php echo $row[1]; ?>.png" height="50"/>
</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
First things first, swap to PDO, ASAP. This will save you TONS of time and can help with SQL execution time, when used correctly (You can find a quick PDO tutorial here). To answer question, I would recommend you start with importing the jQuery library. It allows near effortless manipulation of the DOM.
Then, just do something like
$('#your-form-id-here').submit(function(clickEvent){
$.ajax({
url: 'http://www.foo.com/',
data: $('#your-form-id-here').serialize(),
method: 'POST',
success: function(Response){
//If the request is successful, this code gets executed
},
error: function(){
//If the request failed, this code gets executed
}
});
return false; <----This prevents the page from refreshing
});
Now lets break it down a bit
data: $('#your-form-id-here).serialize() <-- This gets all of your form data ready
NOTE: There's way more to it than this. You'll need to do some server-side stuff to make this work right. For instance, if you want a JSON object back, you'll need to return it. In php, I like to do something like
if(My request succeeded){
echo(json_encode(array(
'status' => 'success',
'message' => 'Request description/whatever you want here'
)));
}

Upload Download from mysql php

I've made use of a script which is available online. The File upload.php allows the user to upload a file and then store the selected file in the MySQL database.
Later the download.php script displays the links for all the files stored in the database. When the user clicks the link, the file should be downloaded. I've enclosed the script below.
But the problem is, I am not using any upload.php nor download .php.
I have tried this in wordpress using "php code for post (Only shortcode placed ion the page)" at one shot.
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fileType = (get_magic_quotes_gpc() == 0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) :
mysql_real_escape_string(stripslashes($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
mysql_connect("localhost","*****","***");
mysql_select_db("****");
$query = "INSERT INTO wp3_cte (FileupName, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "File $fileName uploaded";
}
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input id="userfile" type="file" name="userfile" /></td>
<td width="80"><input id="upload" type="submit" name="upload" value=" Upload " /></td>
</tr>
</tbody>
</table>
</form>
<html>
<head>
<title>Download File From MySQL Database</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<?php
mysql_connect("localhost","**********","**********");
mysql_select_db("**********");
$query = "SELECT id, FileupName FROM wp3_cte";
$result = mysql_query($query) or die('Error, query failed');
if (mysql_num_rows($result) == 0) {
echo "Database is empty <br>";
} else {
while (list($id, $name) = mysql_fetch_array($result)) {
?>
<a href="download.php?id=<?php echo urlencode($id); ?>"
><?php echo urlencode($name); ?></a> <br>
<?php
}
}
mysql_close();
?>
</body>
</html>
<?php
if (isset($_GET['id'])) {
mysql_connect("localhost","**********","**********");
mysql_select_db("**********");
$id = $_GET['id'];
$query = "SELECT FileupName, type, size, content"FROM wp3_cte WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
ob_clean();
flush();
echo $content;
mysql_close();
exit;
}
?>
The problem i am facing is in this peace of code:`download.php`.
Uploaded file is showing properly if i click on download file blank page appears.
Id is displayed in Url
The uploaded file is saving in some folder named upload in ftp server i tried a lot but i was out with no result.
can any one help me Thanks in advance!!!!

php - Update Will Not Store New Files But Updates Text Data

I'm working on a script to upload files. The files are uploaded into a folder and the path is written into a table. One table is used to store the descriptions, names etc and the other table the path. I can upload files, I can edit the descriptions and names but I cannot overwrite old files with new files. I'm not getting any errors. Permissions on the folder are set to 777. I have adapted a script I used to upload images and didn't have any issues updating images so I don't understand why it's not working? This is the edit script.
NON WORKING CODE
<?php
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
function uploadfile($dir){
if(!empty($_FILES)){
$url ='';
// $file = ($_FILES["file"]["tmp_name"]);
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "PNG", "GIF", "mp3");
$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"] == "audio/mpeg")
)
&& ($_FILES["file"]["size"] < 209715200)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = $dir . $_FILES["file"]["name"];
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$dir . $_FILES["file"]["name"]);
$path = $dir . $_FILES["file"]["name"];
}
}
}
else
{
$message = "Wrong format";
}
}
return $path;
}
//declare form field and form field error variables
$descriptionErr = $categoryErr = $titleErr = "";
$description = $category = $title = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if(empty($_FILES["file"]["tmp_name"])){
$has_errors = true;
$fileErr = "Missing Show!";
}else{
$dir = "audio/";
}
if (empty($_POST["title"])) {
$has_errors = true;
$titleErr = "Enter a title";
}else {
$title = validate_input($_POST["title"]);
}
if (empty($_POST["description"])) {
$has_errors = true;
$descriptionErr = "Enter a description";
}else{
$description = validate_input($_POST["description"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
//write data into database table
if (!$has_errors)
{
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$path = uploadfile($dir);
$Query = "INSERT INTO ccshowcontent VALUES ('','".mysql_escape_string($user)."','".mysql_escape_string($title)."','".mysql_escape_string($description)."',
'".mysql_escape_string($category)."')";
//pass id from form table into file table in order to link files to form data
if(mysql_db_query ($DBName, $Query, $Link)) {
$formid = mysql_query("SELECT id FROM ccshowcontent ORDER BY id DESC LIMIT 1");
$formid = mysql_fetch_array($formid);
$Query = "INSERT INTO ccaudio VALUES ('{$formid[0]}','".mysql_escape_string($user)."','{$path}')";
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
if($sql = mysql_db_query ($DBName, $Query, $Link)) {
$message = "Show Saved";
header("Location: ccuploadshow.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/formcomiccon.css" />
<link rel="stylesheet" href="styles/slideshow.css" />
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<link href='//fonts.googleapis.com/css?family=Economica:700,400italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>Audio File Upload</title>
<meta name="Description" content="Audio File Upload" />
<meta name="Keywords" content="Audio File Upload" />
<script>
$(function(){
$(document).click(function(){
$('.messagebox').hide();
});
});
</script>
</head>
<body id="bodyform">
<p class="header">Audio File Upload</p>
<form action="ccuploadshow.php" method ="post" enctype="multipart/form-data" name="myForm">
<fieldset>
<div class="legendcreate">Upload</div>
<div class="audiocontainer">
<div class="audiocontainerinner">
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelcard">Title</label><input id="title" class="insetcard" name="title" type="text" placeholder="Title" value="<?PHP print $title ; ?>"/>
<p class="errorcard"><?php echo $titleErr;?></p></div>
<div><label class="labelcard">Category</label><input id="category" class="insetcard" name="category" type="text" placeholder="Category" value="<?PHP print $category ; ?>"/>
<p class="errorcard"><?php echo $categoryErr;?></p></div>
<div><textarea id="description" name="description" class="textareadescription" placeholder="Enter show description" value="<?PHP print $description ; ?>"></textarea>
<p class="errordescription"><?php echo $descriptionErr;?></p></div>
<p class="errorfiles"><?php echo $fileErr;?>
<div class="uploadimgbtn"><p class="upload">Select Audio<input id="upfile" type="file" name="file" class="uploadbtn"/></p></div>
<div class="submit"><input name="Reset" type="reset" class="resetbtn" value="Reset"/></div>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Create"></div>
</div>
</div>
</fieldset>
</form>
</body>
</html>
I've posted the solution for those who have had similar problems or need a script for this task.
<?php
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
function uploadfile($dir){
if(!empty($_FILES)){
$url ='';
$file = ($_FILES["file"]["tmp_name"]);
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "PNG", "GIF", "mp3");
$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"] == "audio/mpeg")
)
&& ($_FILES["file"]["size"] < 2009715200)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = $dir . $_FILES["file"]["name"];
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$dir . $_FILES["file"]["name"]);
$path = $dir . $_FILES["file"]["name"];
}
}
}
else
{
$message = "Wrong format";
}
}
return $path;
}
//declare form field and form field error variables
$titleErr = $descriptionErr = $categoryErr = "";
$title = $description = $category = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysql_real_escape_string($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if(empty($_FILES["file"]["tmp_name"])){
$path = mysql_real_escape_string($_POST['path']);
}else{
$dir = "audio/";
}
if (empty($_POST["title"])) {
$has_errors = true;
$titleErr = "Enter A Title";
} else {
$title = validate_input($_POST["title"]);
}
if (empty($_POST["description"])) {
$has_errors = true;
$descriptionErr = "Enter A Description";
} else {
$description = validate_input($_POST["description"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter A Category";
} else {
$category = validate_input($_POST["category"]);
}
if (!$has_errors)
{
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
if(empty($path)){
$path = uploadfile($dir);
}
//write edited data into tables matching logged in user with their data
$ccid = mysql_real_escape_string($_POST['ccid']);
$Query = "UPDATE ccshowcontent SET title='$title', description='$description', category='$category' WHERE id='$ccid' AND '$user'='$user'";
if(mysql_db_query ($DBName, $Query, $Link)) {
$Query = "UPDATE ccaudio SET path='$path' WHERE id='$ccid'";
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
if($sql = mysql_db_query ($DBName, $Query, $Link)) {
$message = "Changes Saved";
$current = $_GET['page'];
header("Location: cceditshow.php?page=".$current."&message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccshowcontent JOIN ccaudio USING (id) WHERE ccshowcontent.username = '$user'")
or die(mysql_error());
$count = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$id[] = $row['id'];
$name[] = $row['name'];
$title[] = $row['title'];
$description[] = $row['description'];
$category[] = $row['category'];
$audio_paths[] = $row['path'];
}
//create counts and links for pagination
if(empty($_GET['page'])){
$i = 0;
$current = $i + 1;
}else{
$i = $_GET['page'];
$current = $i;
$i = $i - 1;
}
if($i == 0 && $count == 1){
$prevlink = "";
$next = $current + 1;
$nextlink = "";
}elseif($i == 0 && $count > 1){
$prevlink = "";
$next = $current + 1;
$nextlink = "<a href='?page=$next'>Next</a>";
}elseif($current > 0 && $current < $count){
$prev = $current - 1;
$next = $current + 1;
$prevlink = "<a href='?page=$prev'>Previous</a>";
$nextlink = "<a href='?page=$next'>Next</a>";
}elseif($current == $count){
$prev = $current - 1;
$prevlink = "<a href='?page=$prev'>Previous</a>";
$nextlink = "";
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deletecard = $_POST['Delete'];
mysql_query("DELETE FROM ccshowcontent WHERE id = '$deletecard'");
mysql_query("DELETE FROM ccaudio WHERE id = '$deletecard'");
mysql_query("ALTER TABLE ccshowcontent AUTO_INCREMENT = 1");
$message = 'Show Deleted';
header("Location: cceditshow.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/formcomiccon.css" />
<link rel="stylesheet" href="styles/slideshow.css" />
<script type="text/javascript" src="javascript/jquery-2.1.1.js"></script>
<link href='//fonts.googleapis.com/css?family=Economica:700,400italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>File Upload</title>
<meta name="Description" content="File Upload" />
<meta name="Keywords" content="File Upload" />
<script>
$(function(){
$(document).click(function(){
$('.messagebox').hide();
});
});
</script>
</head>
<body id="bodyform">
<p class="header">File Upload</p>
<ul id="navigation">
<li>Admin<ul>
<li>Edit</li>
<li>Shows</li>
<li>Upload</li>
</ul></li>
<li>Register</li>
<li>Logout</li>
</ul>
<br style="clear:left;"/>
<form action="" method ="post" enctype="multipart/form-data" name="editform">
<fieldset>
<div class="legendcreate">Edit</div>
<div class="audiocontainer">
<div class="audiocontainerinner">
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelcard">Title</label><input id="title" label="title" class="insetcard" name="title" type="text" placeholder="title" value="<?PHP print $title[$i] ; ?>"/><p class="errorcard"><?php echo $titleErr;?></p></div>
<div><label class="labelcard">Description</label><input id="category" class="insetcard" name="category" type="text" placeholder="category" value="<?PHP print $category[$i] ; ?>"/>
<p class="errorcard"><?php echo $categoryErr;?></p></div>
<div><textarea id="description" name="description" class="textareadescription" placeholder="Enter character description"><?php
$out = htmlspecialchars_decode($description[$i]);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<p class="errorbio"><?php echo $biographyErr;?></p></div>
<input type="hidden" name="path" value="<?php echo $audio_paths[$i]; ?>"/>
<p class="errorimage"><?php echo $imageErr;?>
<div class="uploadimgbtn"><p class="upload">Select File<input id="upfile" type="file" name="file" class="uploadbtn"/></p></div>
<div class="submit"><input name="Submit" type="submit" class="savebtn" value="Save"/></div>
<input type="hidden" name="Delete" value="<?php echo $id[$i]; ?>">
<div class="delete"><input name="deletebtn" type="submit" class="deletebtn" value="Delete"/></div>
<input type="hidden" name="ccid" value="<?php echo $id[$i]; ?>"/>
</div>
</div>
</form>
</fieldset>
<div class="previouscardedit"><?php echo $prevlink; ?></a></div>
<div class="countpreviousedit"><?php if($prevlink != ""){ echo $prev."/".$count; } ?></div>
<div class="nextcardedit"><a class="tcg"><?php echo $nextlink; ?></a></div>
<div class="countnextedit"><?php if($nextlink != ""){ echo $next."/".$count; } ?></div>
<div class="currentcardedit"><?php echo "Show ".$current." of ".$count; ?></div>
<br style="clear:left;"/>
</body>
</html>

Categories