upload file to mysql with PHP - php

I've really been stuggeling to get my head around the issue I have.
I've looked the whole internet but couldn't find any reason why I keep having this issue.
My file does get sent to the 'uploads' file on my server, but the details don't get sent to mysql db. What am I doing wrong?
Index.php
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="body">
<form action="upload.php" method="post" enctype="multipart/form-data">
<div class='container'>
<label for='voornaam' >Naam*: </label><br/>
<input type='text' name='voornaam' />
</div>
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
</div>
</body>
</html>
upload.php
<?php
include 'dbconfig.php';
if($_FILES["file"]["error"]>0)
{
echo "FILE ERROR";
die();
}
$filename = "uploads/".$_FILES["file"]["name"];
// move file to a folder
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
{
$sql="INSERT INTO tbl_uploads(name, file) VALUES('voornaam',$filename')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
?>

Firstly Drop using Mysql_* functions those are deprecated use
prepared statements instead
here's the solution
upload.php
<?php
include 'dbconfig.php';
if($_FILES["file"]["error"]>0)
{
echo "FILE ERROR";
die();
}
$filename = "uploads/".$_FILES["file"]["name"];
// move file to a folder
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
{
$sql="INSERT INTO tbl_uploads(name, file) VALUES('voornaam','$filename')";
mysqli_query($db,$sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
?>
dbconfig.php
<?php
//header('Content-Type: text/html; charset=ISO-8859-1');
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'tbl_uploads');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

First of all, please read about PDO / MYSQLI.
About your problem, you have to remove '

Related

Upload multiple files using PHP

I have the following code to upload files to a database in mysql:
Index.php
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
<?php
if(isset($_GET['success']))
{
?>
<label>File Uploaded Successfully... click here to view file.</label>
<?php
}
else if(isset($_GET['fail']))
{
?>
<label>Problem While File Uploading !</label>
<?php
}
else
{
?>
<?php
}
?>
Upload.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
which works well, but only for individual file. I saw many tutorials, but I can not modify the code to allow upload multiple files at once. Any suggestions?
To allow multiple file uplodes you need to set attribute multiple="multiple" on the file input with a name file[]. Or you can use separate inputs with a name file[] as well. Than to store values in database make a
foreach($_FILES['filename']['name'] as $key=>$name){
// store each file and write data to DB for each file
//for example to get the name of file
$name = $_FILES['filename']['name'][$key];
}

Wamp issue for testing upload PHP file

I'm trying to learn how to upload by using Wamp server..
But unsure is it the settings or my code.
Please enlighten me.
Upload.htmlS
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://localhost/testing/php/file_uploader.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
The uploader.php
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "C:\wamp\www\beta\images" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
The error i've received is ,
Warning: copy(bannerbelow.JPG): failed to open stream: No such file or directory in C:\wamp\www\beta\admin\php\file_uploader.php on line 4
This works for me:
<?php
if( $_FILES['file']['name'] != "" ) {
$uploadfolder = $_SERVER['DOCUMENT_ROOT']."/beta/images";
$filename = $_FILES['file']['name'];
move_uploaded_file( $_FILES['file']['tmp_name'], "$uploadfolder/$filename" ) or
die( "Could not copy file!");
}
else {
die("No file specified!");
}
?>
$path = 'C:\wamp\www\beta\images\'; // make sure dir is exist
if(!is_dir($path)){
mkdir($path)
}
//write code for move file via copy or move_uploaded_file funcition

php can't move file from tmp

I'm stuck with a simple php code, which must move a uploaded file from tmp to a desired location. Please find my code below. I'm not sure where i'm going wrong.
Any help is appreciated.
php code:
<?php
define("UPLOAD_DIR", "/srv/www/wordpress/mywebpage/uploads/");
$scr = $_FILES["jb_cv"]["tmp_name"];
$desttmp = $_FILES["jb_cv"]["name"];
$dest = UPLOAD_DIR .$desttmp;
echo " source file : ";
echo $scr."\t";
echo " destination file : ";
echo $dest;
$success = move_uploaded_file($scr,$dest);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
?>
HTML code:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="move.php" id="contactform" name="contactform" enctype="multipart/form-data">
<label> Upload your CV</label> <input name="jb_cv" type="file" />
<input type="submit" value="SUBMIT" />
</form>
</body>
</html

Outputting an image from an SQL BLOB

I have a php file which stores an image in a BLOB in a Database. The uploading part works fine. However it won't display the image and I don't know why. Help appreciated.
Two files:
index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload an Image</h1>
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$imageName=mysql_real_escape_string($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
?>
</body>
</html>
and get.php:
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
$id=mysql_real_escape_string($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
PHP uploads, as stored in the ['tmp_name'] are TEMPORARY files, which are automatically deleted by PHP when the script ends/exits, unless you've taken measures to move it elsewhere. You'd need to have something more like
if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
... handle upload ...
move_uploaded_file($_FILES['image']['tmp_name'], "/path/in/your/document/root/$id.jpg");
} else {
die("Upload failed with error code: " . $_FILES['image']['error']);
}
first. Note the addition of the error check - NEVER assume that an upload succeeded.

updating existing image with new image

im new to php and i want to update a logo, i mean i want to upload an image file which i want to be replaced by the logo.png and shown as a logo on my webpage, the code till now is uploading an image and saving the image in the folder but not replacing the exixting image with the new one, olease help me solve this problem, thanku
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 />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><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");
}
?>
this is setup-action.php
<?php include("../includes/config.php");?>
<?php
$target_path = "../graphics/";
$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!";
}
?>
<?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);
?>
Have a look at PHP File Upload Tutorial. You may use logo.png as the file name.

Categories