I am trying to upload a file onto the server using php but I need some help.
I have a html form to submit a book name and a book image. The book name will be stored in the database (see below) and the image will be stored on the server.
The id, book name, and date are being stored in the database however the image is not uploading. Please help me to sort it out.
Thanks.
Database table "books"
id int(11), book_name varchar(255), date_added date
add_book.php
<?php
$book_name = $_POST['book'];
// insert fields to database
$sql_query = mysql_query("INSERT INTO books (book_name, date_added) VALUES ('$book_name', now()");
// get id for that row
$id = mysql_insert_id();
// rename the book to that id followed by the format .jpg
$new_book_name = "$id.jpg";
// define upload path
$upload_path = "../book_images/";
// move the uploaded file to the upload path with the new name
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_path . $new_book_name);
?>
<form action="add_book.php" method="post" enctype="multipart/form-data" name="bookform" id="bookform">
Book name: <input name="book" type="text" id="book" value=""/> <br />
Book image: <input type="file" name="upload" id="upload" />
<input name="submit" type="submit" value="Add book" />
</form>
Before any PHP developer begins to debug anything I always suggest in every question that do set error_reporting(E_ALL); and ini_set("display_errors", 1); at the very top of your script. This will tell you what went wrong on what line with respect to what statement/variable/constant
Anyways, you should check for validities whether the file uploads or not, its type and other such parameters. You should also store it by adding relative path with respect to your current working directory
if(isset($_FILES["upload"])&&$_SERVER["REQUEST_METHOD"]=="POST")
{
$name=$_FILES["upload"]["name"];
$tempName=$_FILES["upload"]["tmp_name"];
$size=$_FILES["upload"]["size"];
$type=$_FILES["upload"]["type"];
$realPath="bookName/Imagename/".$name;
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/png"))
{
if(is_dir($fullDirectory)) //if directory exists, then simply move it
{
move_uploaded_file($tempName, $realPath);
}
else //if directory doesn't exist then make one and then move the file
{
mkdir($fullDirectory,0777,true);
move_uploaded_file($tempName, $realPath);
}
}
else
{
print $_FILES["upload"]["error"];
}
}
Spme thing is wrong here:
$new_book_name = "$id.jpg";
You should take file name from POST here $_FILES["upload"]["name"]. and add $id with this file name:
$new_book_name = $id."-".$_FILES["upload"]["name"];
Also check permission in your upload directory "../book_images/".
Related
I'm creating a site that displays news uploaded on it's admin panel.
Each post has an image and a title (and description, but i haven't implemented it yet).
My problem is, that when i try to post (and upload image with it) the post is created, but the image doesn't exist.
uploader (php):
if (isset($_FILES['image'])) {
//this script
//connects to mysql database
//declares an array that contains table names (array name is db)
require_once("db.php");
//move file to the img folder
move_uploaded_file($_FILES['image']['tmp_name'], "img/" . $_FILES['image']['tmp_name']);
//upload the post to the database
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('img/{$_FILES['image']['tmp_name']}', '{$_POST["text"]}')";
if (!mysql_query($sql)) {
//display error message
}
}
form (html):
<form action="post.php" method="POST" enctype="multipart/form-data">
<label>Image: </label><input type="file" name="image" />
<br />
<label>Text: </label><input type="text" name="text" />
<input type="submit" />
</form>
I check the files via ftp after posting, the image doesn't exist.
$_FILES['image']['tmp_name'] is an absolute pathname like /var/tmp/something. When you concatenate it to img/, you get a pathname that points into a subdirectory, img//var/tmp/something. Since the subdirectory doesn't exist, move_uploaded_file() fails.
You should use basename() to get just the filename portion.
$filename = 'img/' . basename($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES['image']['tmp_name'], $filename);
$text = mysql_real_escape_string($_POST['text']);
$sql = "INSERT INTO `{$db["posts"]}` (`img`, `text`) VALUES ('$filename', '$text')";
I'm not really sure how safe using the name of the temp file this way is, though. I don't think there's any guarantee that it will never repeat the same name for different uploads.
I'm writing a piece of code that uploads a .zip file, takes the content of the .zip file and removes the .zip itself. It also changes the name of the directory based on your own input, which is required. This is the form:
<form action ="" method="post" enctype="multipart/form-data">
<div>
<p><input type="text" name="NewName" placeholder="Enter New Name" required/></p>
<p><input type="file" name="zip" required/></p>
<p><input type="submit" value="upload" /></p>
</div>
</form>
This is the php i use to rewrite the directory, which is, by default, named "NewMap"
if($_POST['NewName']){
$NewNameStr = $_POST['NewName'];
$NewNameTrim=preg_replace('/\s+/', '', $NewNameStr);
rename("uploads/NewMap/", "uploads/" . $NewNameTrim);
mkdir("uploads/NewMap/");
}
As you can see after I rename it I create the directory again for future use.
My question is the following: It is possible that the user will use a name that already exists, when this happens it does not rename anything and the map structure gets messed up. How can i check if the name already exists with $_POST['NewName']; and add a number to it? So if user1 calls his directory onions and user2 also calls his directory onions user2's directory gets called onions1
Try something like this:
$dirName = YOUR_PATH;
$directoryExists = false;
$i = 1;
$tempName = $dirName;
do{
if(file_exists($tempName)){
$tempName = $dirName.$i;
$i++;
}else{
$directoryExists = true;
$dirName = $tempName;
}
}while(!$directoryExists);
or you could just add datetime (e.g 2016082916001234) after every folders name.
I strongly recommend that you do not allow that to happen. I point out that use the id of the User, or any unique identifier and concatenate in all his folders. that is, if he wants to create a folder called potato, the actual name would be: Potatouser
I am trying to enter some data into a database and upload an image to a specific directory. I am using the following script which is a modified version of the top voted answer to this question: How to store file name in database, with other info while uploading image to server using PHP?
require($_SERVER['DOCUMENT_ROOT']."/settings/functions.php");
// This is the directory where images will be saved
$target = $_SERVER['DOCUMENT_ROOT']."/safetyarticles/images/";
$target = $target . basename( $_FILES['article_img']['name']);
date_default_timezone_set("America/Chicago");
// This gets all the other information from the form
$article_name = $_POST['article_title'];
$article_date = date("m/d/Y");
$article_creator = $_POST['article_creator'];
$article_views = "0";
$article_content = $_POST['article_content'];
$article_content_2 = $_POST['article_content_2'];
$article_img = ($_FILES['article_img']['name']);
$article_credit = $_POST['article_credit'];
// Connect to database
$conn = getConnected("safetyArticles");
// moves the image
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))
{
// if upload is a success query data into db
mysqli_query($conn, "INSERT INTO currentArticles (article_name, article_date, article_creator, article_content, article_content_2, article_img, article_credit)
VALUES ('$article_name', '$article_date', '$article_creator', '$article_views', '$article_content', '$article_content_2', '$article_img', '$article_credit')") ;
echo "The file ". basename( $_FILES['article_img']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
I have successfully connected to my database since my getConnected() function contains error handling for if the connection fails.
For some reason I keep getting the Sorry, there was a problem uploading your file. error from the bottom of the script.
Am I missing something? All I did was change some minor lines here and there such as how the database connects, and the variables. I also moved the query to only happen if the file uploads.
I'm not sure what I'm missing.
Is it also possible to modify this current script to rename the image to whatever the value of $article_name is? For example if the article name is "This Is The First Article" then the image would be this-is-the-first-article.jpg?
My HTML form is:
<form method="post" action="http://example.com/admin/articleCreate.php" enctype='multipart/form-data'>
<input type="text" name="article_title" placeholder="What Is The Name Of This Article?" id="article_title_input">
<textarea name="article_content" placeholder="Write The Top Half Of Your Article Here." id="article_content_input"></textarea>
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
<textarea name="article_content_2" placeholder="Write The Bottom Half Of Your Article Here." id="article_content_2_input"></textarea>
<input type="text" name="article_creator" placeholder="Who Is Writing This Article?" id="article_creator_input">
<input type="text" name="article_credit" placeholder="If This Article Is Copied, What Website Was It Taken From?" id="article_credit_input">
<input type="submit" value="Submit">
</form>
And I did var_dump(is_uploaded_file($_FILES['article_img']['tmp_name'])); and it's returnign true.
Sidenote edit: This being before you edited your question with only one of them being renamed. https://stackoverflow.com/revisions/36367407/4
$_FILES['photo']
$_FILES['uploadedfile']
are two different file arrays and you're using name="article_img" as the name attribute.
You need to use the same one for all of them.
Error reporting http://php.net/manual/en/function.error-reporting.php would have told you about it.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional edit:
$target = $target . basename( $_FILES['photo']['name']);
if that's your real edit, still the wrong array name.
I think the problem is in this line:
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
Change it to this:
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))
Your html has:
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
And your php is waiting for $_FILES['photo']['tmp_name']
Change your html file input to:
<input type="file" name="photo" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end
I am new to php and trying to upload an image file in mysql database using php.I tried various tutorial but it didnot work for me.
Code Snippet:-
<?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "root", "");
//Select database, database_name needs to be changed
mysql_select_db("yelldb");
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>
<?php
}else{
//if the form hasn't been submitted then:
//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved
//into the database. The image is named after the persons IP address until it gets moved into the database
//get users IP
$ip=$_SERVER['REMOTE_ADDR'];
//don't continue if an image hasn't been uploaded
if (!empty($image)){
//copy the image to directory
copy($image, "./temporary/".$ip."");
//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR'];
$fp1 = fopen($filename1, "r");
//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));
//close the file
fclose($fp1);
//encode the image into text
$encoded = chunk_split(base64_encode($contents1));
//insert information into the database
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')");
//delete the temporary file we made
//unlink($filename1);
}
}
?>
We don't save out the whole image in our database usually. We go through inserting the permanent of picture in our database. Use this php function
move_uploaded_file(file,newloc)
This will move from your temporary directory to permanent directory. Then, get path from there and insert that to the database.
Typically, you wouldn't save an entire image into an SQL database. Instead, you store the on disk path or some other 'pointer' to the actual file.
Change your code to read something like the following:
//don't continue if an image hasn't been uploaded
if (isset($_POST['image'])){
$image = $_POST['image'];
//copy the image to directory
$path = "/some/path";
move_uploaded_file($image,$path);
//store the name and path. PS: you will want to validate your input, and look
//at using prepared statements.
//Concentating values like this is NOT safe, or ideal
$location = $path . "/" . $image
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")");
}
If however, you still wish to store the image in the SQL database, look into the blob storage type, not encoded text.
PHP move_uploaded_file