Image upload via php and adding details to mysql - php

So I have searched everywhere and i cannot figure this out at all. I am trying to upload POST info and the image name to SQL and also upload the image to the uploads directory. SQL will update all info except the image line nor will it actually upload the image. Ill post code below
EDIT: I got it to add the file name into the SQL table but still it wont upload file.
FORM info
<table width="100%" border="0">
<tr><form action="specialadd.php" method="post">
<td>Name of Special</td>
<td>Special Price</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="name"></td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>Description #1</td>
<td>Description #2</td>
</tr>
<tr>
<td><textarea name="desc1" rows="6" cols="50"></textarea></td>
<td><textarea name="desc2" rows="6" cols="50"></textarea></td>
</tr>
<tr>
<td>Upload Photo</td>
<td> </td>
</tr>
<tr>
<td><input type="file" name="image"></td>
<td><input type="submit" value="Save Your Special"></form></td>
</tr>
</table>
PHP Info
<?php
//This is the directory where images will be saved
$target = "/public_html/uploads";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$price=$_POST['price'];
$image=($_FILES['image']['name']);
// Connects to your Database
include "process/connect.php";
//Writes the information to the database
mysql_query("UPDATE specials
SET name='$name', desc1='$desc1', desc2='$desc2', price='$price', image='$image'") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I figured it out also thanks on the enctype i completely forgot about that. It works perfectly.

You need to add
enctype="multipart/form-data"
in the form so your form should be
<form action="specialadd.php" method="post" enctype="multipart/form-data">

Related

Error while trying to upload image in a insert post form using a database with php and mysql in after hosting the website online?

I am trying to upload image in a insert post form using a database with php and mysql. I hosted the website. after hosting, i tried to insert data, but it throws the following errors:
Warning: move_uploaded_file(images/Penguins.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in C:\inetpub\vhosts\srkv9093.com\testsrkv\insert_post.php on line 75
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpC2A4.tmp' to 'images/Penguins.jpg' in C:\inetpub\vhosts\srkv9093.com\testsrkv\insert_post.php on line 75
The code
<body>
<div>
<h2>Logout</h2>
<h2>View Post</h2>
</div>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<table width="600" align="center" border="0">
<tr>
<td align="center" colspan="6" bgcolor="white">
<h1>Insert New Post Here</h1>
</td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords"></td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content:</td>
<td><textarea name="content" cols="30" rows="15"></textarea> </td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
<?php
include("includes/connect.php");
if(isset($_POST['submit'])) {
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if($post_title=='' or $post_keywords=='' or $post_content=='' or $post_author=='' or $post_date=='') {
echo "<script>alert(Some field is empty')</script>";
exit();
}
move_uploaded_file($image_tmp, "images/$post_image");
$insert_query = "insert into posts (post_title, post_date, post_author, post_image, post_keywords, post_content) values ('$post_title', '$post_date', '$post_author', '$post_image', '$post_keywords', '$post_content')";
if(mysql_query($insert_query)) {
echo "<center><h1>Post Published Successfully!</h1></center>";
}
}
?>
Just to be curious, is your website hosted in a windows server or a linux server? Only then one can answer the question comprehensively
i could have commented but apparently, someone has upped the reputation for commenting,
From your path, I guess you are working on Window host.
So, you need to set writing permission of "images" folder to the "Everyone User" account. (or at least the internet guest account)
You can refer this link for how to work. http://www.web-site-scripts.com/knowledge-base/article/AA-00427/0/Setup-correct-files-and-folders-access-permissions-efficiently.html

image not uploading/moving into folder

i am uploading an image , image title is getting added to database but the file(image is not uploading/moving to the folder), i am getting 404 error for that image , i have set that folder permissions to 0777 and also max upload is 1024MB
$article_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
define ('SITE_ROOT', realpath(dirname('_FILE_')));
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');
$add="insert into articles(article_title,article_date,article_author,category,article_image,article_keywords,article_content) values ('$article_title','$article_date','$article_author','$article_category','$article_image','$article_keywords','$article_content')" ;
if(mysqli_query($conn,$add)== 1 ){
echo "<script> alert('article added')</script>";
}
else{
echo "failed".mysqli_error($conn) ;
}
}
what mistake am i doing ?
EDIT here is my html code
<form method="post" action="addarticle.php" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="center"><h1> ADD ARTICLE</h1></td>
</tr>
<tr>
<td>Article Title</td>
<td><input type="text" name="title"></td>
<tr>
<td>Article Keyword</td>
<td><input type="text" name="keywords"></td>
<tr>
<td>Article Image</td>
<td><input type="file" name="image"></td>
</tr>
<td>Article Content</td>
<td><textarea name="content" cols="90" rows="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Check your line with:
realpath(dirname('__FILE__'));
__FILE__
is a magic constant, and should not be wrapped in single or double quotes.
If you were to echo out the result of that function call you would probably see a different path than what you're expecting.
You're also trying to use string interpolation with single quotes around the variable instead of double:
SITE_ROOT.'/images/$article_image';
Should be:
SITE_ROOT."/images/$article_image";
Example:
if (!empty($_FILES['image'])) {
$tmp_file_to_upload = $_FILES['image'];
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
$uploaded_name = $tmp_file_to_upload['name'];
$tmp_name = $tmp_file_to_upload['tmp_name'];
$destination = realpath(dirname(__FILE__))."images/$uploaded_name";
if (!move_uploaded_file($tmp_name, $destination)) {
die('Error uploading file.');
}
} else {
die('Error uploading file.');
}
}
Try this, Variable concatenation issue '/images/'.$article_image
move_uploaded_file($image_tmp,SITE_ROOT.'/images/'.$article_image);
instead of
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');

PHP File upload script getting in the way

I have this form
If the first radio button is clicked, the textfield below it is enabled and if the 2nd radio button is clicked, the file upload is enabled and the former is disabled,vice versa. It works fine if the file upload option is chosen but if the 1st radio button is chosen and the file upload is disabled, it doesn't insert data in the database. :/ What should be done to successfully send the form details even if the file upload is disabled/empty?
CODE:
<form name="form" method="POST" enctype="multipart/form-data">
<table width="416" height="245" border="1" align="center">
<tr>
<td colspan="2">Transaction No: <input type="text" name="transaction_no" id="transaction_no" /> </td>
</tr>
<tr>
<td colspan="2" align="center">Please select the mode of payment</td>
</tr>
<tr>
<td width="183" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="Smart Money" checked="checked">
Smart Money</td>
<td width="201" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="BPI"> BPI Bank Deposit</td>
</tr>
<tr>
<td align="center"><input type="text" name="contactno" id="contactno"></td>
<td align="center"><input name="filename" type="file" id="filename" disabled="disabled"/></td>
</tr>
<tr>
<td>Total amount sent:</td>
<td> <input type="text" name="totalsent" id="totalsent" /></td>
</tr>
<tr>
<td>Date sent:</td>
<td> <input type="text" name="datesent" id="datesent" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form" />
</form>
PHP
<?php
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// pag walang error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
mysql_query("INSERT INTO payment_form (date, Tracking, mode, ContactNo, totalsent, datesent, filename) VALUES (NOW(), '$transactionNo', '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
?>
Javascript for enable/disable
<script type="text/javascript">
function enableField(obj){
var form=obj.form;
var txtNames=['contactno','filename'], f;
var rads=document.getElementsByName(obj.name), r, i=0;
while(r=rads[i++]){
f=form[txtNames[i-1]];
if(r.checked){
f.removeAttribute('disabled');
f.focus();
}
else{
f.value='';
f.setAttribute('disabled','disabled')
}
}
}
</script>
You should first check which radio is checked and then decide what to do. It's not working because the whole script is under the if(isset($_FILES['filename'])). If the file upload is disabled then $_FILES will not be set and nothing will be executed.

include thumbnail upload in php sql code

I have an upload to mysql script in php that works perfectly for a property website - inserting all relevant fields and the main image.
The problem is however, this image is used in a slideshow which identifies the thumbnail as xxxxxt.png where the main image is xxxxx.png for example.
My php code is:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
$uniqid = md5(uniqid(mt_rand()));
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$extra = mysql_real_escape_string($_POST['extra']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `postcode`, `desc`, `extra`, `productcode`, `price`, `status`, `pandp`, `photo`) VALUES ('$title', '$postcode', '$desc', '$extra', '" . $uniqid . "', '$price', 'tolet.png', '$pandp', '$pic' )") ;
echo "The property has been added to the lettings portfolio";
}
else
{
echo "Error uploading new property - please ensure all the fields are correctly entered and the file is an image";
}
}
?>
The html code for the upload form is:
<form enctype="multipart/form-data" action="addlet.php" method="POST">
<table width="600px" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="135">Title: </td>
<td width="427"><input name="title" type="text" size="40"/></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea name = "desc" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Property Features: </td>
<td><textarea name = "extra" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Postcode: </td>
<td><input name = "postcode" type="text" size="40" /></td>
</tr>
<tr>
<td>Price per week (£): </td>
<td><input name = "price" type="text" size="40" /></td>
</tr>
<tr>
<td>Furnished/Unfurnished: </td>
<td><input name = "pandp" type="text" size="40" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" class="forms" /></td>
</tr> </table></p>
<p> <input type="submit" class="CMSbutton" value="Add" /></p>
</form>
Is there a simple way to add an extra line of code which will insert two images into the desired target on the server, (images/properties/) - one the original name of the image, and one the thumbnail version (with a "t" on the end of the image name).
As they are both reasonably small I am not fussed about resizing the thumbnail as the code is pretty much done I dont want to have to rebuild everything!
Any help much appreciated
Thanks
JD
If your image file is being moved into place successfully, I would take this strategy: create columns is_uploaded, is_thumb_created and is_image_created in your database table. Upon successful upload and move, set the first one.
Then run a cron or other background system that generates a 'main' and a 'thumb' view from the uploaded image (bearing in mind that the uploaded image may be way too large for an ordinary screen-size picture). Upon the successful generation of these images, the relevant columns can be set as 'done', and the row remains non-live until this happens.
This approach is a great deal more scalable, incidentally, since it is not clogging up your web request with expensive image processing.

move_uploaded_file is giving a error

this is my form
<form action="test.php" method="post" name="myform">
<table width="500" border="0">
<tr>
<td width="369" colspan="3">Admin's Area </td>
<td width="121"><?php echo $_SESSION['name'];?></td>
</tr>
<tr>
<td colspan="3">sponseres list </td>
<td>+Add new Sponser</td>
</tr>
<tr>
<td colspan="3"><?php echo $sponsere_list; ?></td>
<td> </td>
</tr>
<tr>
<td align="center" colspan="4"> <a name="sponserForm" id="sponserForm"></a> Add New Sponser Form</td>
</tr>
<tr>
<td align="left">Sponser name</td>
<td align="left"><input type="text" name="spname" id="spname" tabindex="1" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Image</td>
<td align="left"><input type="file" name="fileToUpload" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="left">Add this</td>
<td align="left"><input type="submit" name="sumit" id="sumit" value="Submit" tabindex="3" /></td>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td align="center" colspan="4"> </td>
</tr>
</table>
</form>
and this is the php code to retrive it
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')
";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
$newname="$spic.jpg";
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"../sponsers/$newname")or die (mysql_error());
}
?>
when i try to upload a image it gives me this warning message
Notice: Undefined index: fileToUpload in J:\xampp\htdocs\srimag\admin\test.php on line 3
so i tried to echo the fileToUpload value by using $_POST['fileToUpload'] it show the values without errors so can't figure out the error.
so please help me on this :-(
Thanks.
Your main problem is you are missing the appropriate enctype attribute on your form
<form ... enctype="multipart/form-data">
Make sure you read this section of the manual carefully - http://php.net/manual/en/features.file-upload.php
Your issue is mentioned on the first page
Note:
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You need enctype="multipart/form-data" in your form to upload images, also it would be a good idea to check if user even uploads an image and specificity naming a file .jpg will not work, images will be treated as corrupt when outputting if ther not jpegs, not to mention people uploading php files.
You also need to make some other checks on validity, upload security is not something that should be overlooked, else you have one of thos awful phone home / botnet malware scripts injecting code into all your scripts:
<?php
if(isset($_POST['spname'])){
$spname=mysql_real_escape_string($_POST['spname']);
$user_query = "INSERT INTO `sponsers` (`spname`)
VALUES ('{$spname}')";
$sql=mysql_query($user_query)or die (mysql_error());
$spic= mysql_insert_id();
if(isset($_FILES["fileToUpload"]["tmp_name"]) && $_FILES["fileToUpload"]["error"] ==0){
$name = basename($_FILES["fileToUpload"]['name']);
$ext = end(explode('.', $name));
$newname = $spic.".".$ext;
$info = getimagesize($_FILES["fileToUpload"]['tmp_name']);
$allowed = array('image/png','image/jpg','image/gif');
if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
move_uploaded_file($_FILES["fileToUpload"]['tmp_name'], "../sponsers/$newname");
//done upload
}else{
//Not allowed, perhap notify user
}
}
}
?>
include this in form tag
enctype="multipart/form-data"
You should add this in your form
<form action="test.php" method="post" name="myform" enctype="multipart/form-data">

Categories