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.
Related
I am trying to make a file upload for my website, and it has been working for the past few weeks now until today when i tried to change the upload directory. Now it says Undefined index: extension so i tried changing it back but it still says it. My code is here:
login.php
<!DOCTYPE html>
<head>
<style>
</style>
<body>
<?php
session_start();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<div class="container">
<?php
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
include 'user.php';
$user = new User();
$conditions['where'] = array(
'id' => $sessData['userID'],
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
?>
<h2>Welcome <?php echo $userData['first_name']; ?>!</h2>
Logout
<div class="regisFrm">
<p><b>Username: </b><?php echo $userData['username']; ?></p>
<p><b>Name: </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
<p><b>Email: </b><?php echo $userData['email']; ?></p>
<p><b>Phone: </b><?php echo $userData['phone']; ?></p>
</div>
<?php
$user = $userData['username'];
$url = "/Users/makefile.php?uname=$user";
echo 'Your Account';
// echo 'Your Account';
?>
<form action="upload.php?user=$user" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input type="submit" value="Upload">
</form>
<?php
$dir_path = "uploads/";
$extensions_array = array('jpg','png','jpeg','PNG','mp3','MP3','mp4','MP4');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
// echo "File Name -> $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// echo "File Extension-> $extension<br>";
$filephp = $files[$i] . '.php';
$filetxt = $files[$i] . '.txt';
$fileimg = $files[$i] . '.jpg';
$filetxtu = $files[$i] . 'uploaded' . '.txt';
// check file extension
if(in_array($extension, $extensions_array))
{
// show image
echo "<center><a href='$filephp?txt=$filetxt&img=$files[$i]&php=$filephp&user=$user&txtu=$filetxtu' target='_blank'>
<img src='$dir_path$files[$i]' style='width:300px;height:300px;align:left;'><br></a>
</center>";
}
}
}
}
?>
<?php }else{ ?>
<h2>Login to Your Account</h2>
<?php echo !empty($statusMsg)?'<p class="'.$statusMsgType.'">'.$statusMsg.'</p>':''; ?>
<div class="regisFrm">
<form action="userAccount.php?uimg=$" method="post">
<input type="email" name="email" placeholder="EMAIL" required="">
<input type="password" name="password" placeholder="PASSWORD" required="">
<div class="send-button">
<input type="submit" name="loginSubmit" value="LOGIN">
</div>
</form>
<p>Don't have an account? Register</p>
<p>Go back home Here</p>
</div>
<?php } ?>
</div>
upload.php
<?php
$uname = $_GET['user'];
define("UPLOAD_DIR", "/uploads");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$nametxt = $name . ".txt";
$namephp = $name . ".php";
$nametxtu = $name . "uploaded" . ".php";
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
$content = " ";
$fp = fopen($nametxt, "wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
$text = file_get_contents('comments.php');
$paste = file_put_contents($namephp, $text);
if($paste)
{
echo "File copied correctly\n";
} else {
echo "There was a problem copying the file\n";
}
$file = fopen($nametxtu,"w");
echo fwrite($file, $uname);
fclose($file);
header("Location: login.php");
die();
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
header("Location: uploadyourown.php");
die();
}
Check that upload directory has only files you uploaded, may be directory contains empty file, and be sure all files you uploaded have extensions
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'
)));
}
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>";
}
}
?>
iam new to php, i am using image upload script of php to update my logo, whenever user choose the image file the existing image file should be replaced by the new upoaded file and should be updated on the screen as well, for this iam using this script but its not doing anything, i mean its nor replacing the image neither putting the new image into the folder... :( please help me get out of this problem, i've been in this problem since months..
this is setup.php
<?php include("../includes/config.php"); ?>
<?php
if ($_SESSION["isadmin"])
{
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT * FROM setup WHERE (id=".$_SESSION["id"].")");
while($row = mysql_fetch_array($result))
{
$title = $row['title'];
$theme = $row['theme'];
}
mysql_close($con);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Admdin Home</title>
<link rel="StyleSheet" href="css/style.css" type="text/css" media="screen">
</head>
<body>
<?php include("includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<?php include("includes/aside.php"); ?>
<div id="maincontent">
<div id="breadcrumbs">
Home >
Setup >
Customization
</div>
<h2>Customize</h2>
<?php
if (isset($_GET["status"]))
{
if($_GET["status"]==1)
{
echo("<strong>Customization Done!</strong>");
}
if($_GET["status"]==2)
{
echo("<strong>Customization Error!!</strong>");
}
}
?>
<form method="post" action="setup-action.php" enctype="multipart/form-data" >
<label>Title Of Your Organization:</label> <input type="text" name="title" value="<? php echo $title; ?>" /> <br /> <br />
<label>Select Theme</label>
<select name="theme" value="<?php echo $theme; ?>">
<option value="Default">Default</option>
<option value="Dark">Dark</option>
<option value="White">White</option>
</select>
<br /> <br />
<label>Choose Your Logo Here</label><input type="file" name="file"/><br /> <br />
<input type="submit" name="Upload" value="Upload" />
</form>
</div>
</body>
<?php include("includes/footer.php"); ?>
</html>
<?php
}
else
{
header("Location: ".$fullpath."login/unauthorized.php");
}
?>
and this is setup-action.php
<?php include("../includes/config.php");?>
<?php
if(isset($_FILES["file"]))
{
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 1000000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
if (file_exists("../graphics/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["name"],
"../graphics/" . $_FILES["file"]["name"]);
echo "Stored in: " . "../graphics/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
<?php
$title=$_POST["title"];
$theme=$_POST["theme"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$result=mysql_query("SELECT * FROM setup WHERE id=".$_SESSION['id']);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0)
{
{
mysql_query("UPDATE setup SET title='".$title."' , theme='".$theme."'WHERE id=".$_SESSION['id']);
header("Location:setup.php?status=1");
}
}
else {
header("Location:setup.php?status=2");
}
mysql_close($con);
?>
See this URL
http://www.tizag.com/phpT/fileupload.php
Try this:-
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
uploder.php
$target_path = "uploads/";
$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!";
}
STEP1: Create file upload.php
############### Code
`<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile" type="file" id="ufile" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
`
STEP2: Create file upload_ac.php
############### Code
<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$HTTP_POST_FILES['ufile']['name'];
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$HTTP_POST_FILES['ufile']['name']."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
echo "<img src=\"$path\" width=\"150\" height=\"150\">";
}
else
{
echo "Error";
}
}
?>
I am working through a chapter of a book with regards to binary data. What I would like to do is to automatically display a picture of a person as my database deals with profiles.
So far my solution works and the photo is the last piece of the puzzle.
The book gets you to the stage where a filename link is outputted to the screen, and clicking on this link displays the picture.
What I would like to do instead of this is have the picture displayed automatically like for instance on Facebook. There you would not see a link to your profile picture but the actual picture itself.
Code looks like this:
INDEX.PHP (Controller)
<?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';
PHOTO.HTML (View)
<?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><?php htmlout($f['filedata']); ?></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>
All help is appreciated.
EXTRACT OF CURRENT PHOTO.HTML
<?php foreach($files as $f): ?>
<tr>
<td>
<a href="?action=view&id=<?php htmlout($f['id']); ?>"
><?php htmlout($f['filename']); ?></a>
<!-- attempt to output image not path -->
<img src="<?php echo htmlout($f['filename']); ?>" />
</td>
HELPER FUNCTION
<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}
?>
Wrap it in an <img> tag. This will output it as an image.
i.e. <img src="<?php echo $image; ?>">
In most cases, you are going to be better served by keeping the image files somewhere on a directory structure that is publicly available via HTTP and just storing the link to that image location in the database.
So for example when the user uploads the image, you place it within your web directory in some user images directory, and then just store the path or URL for the image in the database in a varchar field.
This gives you the benefit of keeping your database size down, making your queries for picture information from the database go much faster, improving browser caching of the images, and allowing you to keep your static files in one place (perhaps on a CDN again for better performance in end user's browsers).