image not uploading/moving into folder - php

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');

Related

PHP - uploading new profile images. cannot set new img user variable, and cannot insert img into the database [duplicate]

This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
I dont understand why this isnt working, i have an insert querie, and one to change the Session variable, which both look fine. the actual image goes into the folder fine, it just does not get inserted into the database, nor stored as a session variable and displayed on the page. any help would be very appreciated!
here is the php processing code:
<?php
session_start();
include_once 'dbh-inc.php';
if (isset($_POST['upload'])) {
//gets all info from file to upload using the form//
$file = $_FILES['file'];
//extracting all info from file//
$FileName = $_FILES['file'] ['name'];
$FileTmpName = $_FILES['file'] ['tmp_name'];
$FileSize = $_FILES['file'] ['size'];
$FileError = $_FILES['file'] ['error'];
$FileType = $_FILES['file'] ['type'];
//separating the file name from the file extension, single out extension//
$FileExt = explode('.', $FileName);
//end function gets the last piece of data from an array//
$FileActualExt = strtolower(end($FileExt));
//allowed file types//
$allowed = array('jpg', 'jpeg', 'png');
//checking whether the fileactualext ie. extension types are defined as
allowed//
if (in_array($FileActualExt, $allowed)) {
if ($FileError === 0) {
if ($FileSize < 1000000) {
$FileNameNew = uniqid('', true).".".$FileActualExt;
$FileDestination = 'uploads/'.$FileNameNew;
//inserting into database//
$sql = "INSERT INTO users (user_image) VALUES ('$FileName') WHERE
`user_id`='".$_SESSION["u_id"]."' ;";
mysqli_query($conn, $sql);
//updating session image variable//
$result = mysqli_query($conn, "SELECT * FROM `users` WHERE
`user_id`='".$_SESSION["u_id"]."'");
$row = mysqli_fetch_array($result);
$_SESSION['u_image'] = $row['user_image'];
//inserting into folder//
move_uploaded_file($FileTmpName, $FileDestination);
header("Location: index.php?upload=success");
exit();
} else {
echo "your file is too big!";
}
}
} else {
echo "error uploading file";
}
} else {
echo "you cannot upload files of this type!";
}
and here is the html code for the editing profile page:
<?php include_once 'Header.php';
$uid = ucfirst($_SESSION['u_uid']);
//THIS CODE ONLY EDITS THE VISIBLE PORTION OF A USERS PROFILE//
?>
<table width="398" border="0" align="center" cellpadding="0">
<form class="edit-profile" action="includes/edit-profile-inc.php"
method="POST">
<tr>
<td width="82" valign="top"><div align="left"> <?php echo $uid ?> </div>
</td>
<td height="26" colspan="2"><input type="text" name="uid"
placeholder="New Username"></td>
<td><div align="right">logout</div></td>
</tr>
<tr>
<td width="129" rowspan="5"><img src="<?php echo $picture ?>" width="129"
height="129" alt="no image found"/></td>
<td width="82" valign="top"><div align="left">FirstName:</div></td>
<td width="165" valign="top"><input type="text" name="first"
placeholder="New First name"></td>
</tr>
<tr>
<td valign="top"><div align="left">LastName:</div></td>
<td valign="top"><input type="text" name="last" placeholder="New Last
Name"></td>
</tr>
<tr>
<tr>
<td valign="top"><div align="left">City:</div></td>
<td valign="top"><input type="text" name="city" placeholder="New City">
</td>
</tr>
<tr>
<tr>
<td valign="top"><div align="left">Region: </div></td>
<td valign="top"><input type="text" name="region" placeholder="New
Region"></td>
</tr>
<tr>
<td valign="top"><div align="left">Country:</div></td>
<td valign="top"><input type="text" name="country" placeholder="New
Country"></td>
</tr>
<tr>
<td valign="top"><div align="left">About me: </div></td>
<td valign="top">
<input type="text" name="about" placeholder="About me">
</thgd>
</tr>
<tr>
<td><button type="submit" name="edit">Update profile</button></td>
</tr>
</form>
<form action="uploads-inc.php" method="POST" enctype="multipart/form-data">
<tr>
<td>
<input type="file" name="file" >
<button type="submit" name="upload">Update profile picture</button>
</td>
</tr>
</form>
<p align="center"></p>
<?php
include_once 'Footer.php';
?>
Send help!

Adding the row ID to the filename of the uploaded file

I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);

How To Upload Multiple Images With Links To Them In mysql

Currently I have a code which is working perfectly for one image upload. But i want to upload multiple images at a time with same Image Title, Image Description for image group being uploaded as these images will be used in photo slideshow(See Images below please)
My Current Code is as follows -
PHP Code -
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="image_subject";
$all_columns[]="image_name";
$all_columns[]="clinic";
$all_columns[]="image_link";
//Get All values to insert in to table
$all_values[]=addslashes($_POST["image_subject"]);
$all_values[]=addslashes($_POST["image_name"]);
$all_values[]=addslashes($_POST["clinic"]);
$all_values[]=addslashes($pathAndName );
//=====================
$qry=$bsq->webdreaminsert("sa_galleryuploads_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_file_for_downloading_list.php");
///////////////////////////////////////////////////
}
And HTML Form For upload Image Is As follows -
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
<table width="90%" align="center" border="0" cellpadding="0" cellspacing="0" class="ListTable1">
<tr class="HeadBr">
<td colspan="4"><div align="center"><strong>Add Images For Photo Gallery</strong></div></td>
</tr>
<tr >
<td>Image Title*</td>
<td><input name="image_name" id="image_name" type="text" size="40" value="" /></td>
</tr>
<tr>
<td>Image Description In Short*</td>
<td><input name="image_subject" id="image_subject" type="text" size="40" value="" /></td>
</tr>
<tr >
<td>Clinic Name*</td>
<td>
<select name="clinic" id="message" >
<option value="">Select Clinic</option>
<option value="arogya">1. Arogyawardhini Ayurved Clinic</option>
<option value="smruti">2. Smruti Ayurved Clinic</option>
<option value="tarpan">3. Tarpan Ayurved Clinic</option>
<option value="vishwa">4. Vishwawardhini Ayurved Clinic</option>
</select>
</td>
</tr>
<tr >
<td>Your Image For Upload* </td>
<td><label for="image">File To Upload: </label><br>
<input type="file" size="40" name="image" id="image" /><br />
</td>
</tr>
<tr>
<td></td>
<td><button >Upload</button></td>
</tr>
</table>
</form>
Current Look of My Active Image upload Form -
And I Want Like Below (Created Graphically)
You can use a for loop.
For the form, do something like this:
for($i = 1; $i <= 4; $i++) {
echo "<input type=\"file\" size=\"40\" name=\"image{$i}\" id=\"image{$i}\" /><br />";
}
And for the processing, just put all of that in a for loop as well.
for($i = 1; $i <= 4; $i++) {
$fileName = $_FILES["image".$i]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image".$i]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$image_name = mysql_real_escape_string($_POST['image_name']);
$image_subject = mysql_real_escape_string($_POST['image_subject']);
$clinic = mysql_real_escape_string($_POST['clinic']);
$image_link = "http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), "\\/")."/".$pathAndName;
//=====================
mysql_query("INSERT INTO `sa_galleryuploads_by_admin` VALUES ('', '{$image_name}', '{$image_subject}', '{$clinic}', '{$image_link}' )") or die(mysql_error());
if(!mysql_error()) {
echo "success";
}
}
You can edit the number that the loop goes up to, to match the number of fields/images you want to show. Good luck!
edit: You also need to sanitize validate your inputs. At the very least, use mysql_real_escape_string().
Also, mysql_* functions are deprecated. You should switch to using either mysqli or pdo. I'd suggest mysqli to start off, because it also offers a procedural approach, whereas pdo is completely object oriented.

Image upload via php and adding details to mysql

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">

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