I'm trying to upload a image in PHP but the image is not getting saved in the directory on the server. However I'm able to save the path of the image in the database. Please help. Here is the piece of code. I'm not getting any error in the web page.
<?php
error_reporting(E_ALL);ini_set('display_errors', 'On');
session_start();
$logged_user_name = $_SESSION['user_name'];
$logged_user_type = $_SESSION['user_type'];
$logged_user_team_id = $_SESSION['team_id'];
$logged_user_team_name = $_SESSION['team_name'];
$uploaded_profile_image = $_POST['propic'];
//$uploaded_profile_image = $_FILES['propic']['name'];
include_once("classes/doEverything_framework.php");
function upload_image()
{
$db_connection_obj = new database_connection;
$db_connection = ($db_connection_obj -> open_database_connection());
global $logged_user_name;
global $uploaded_profile_image;
$profile_image_upload_dir = 'images/uploaded_profile_pics/';
if ($uploaded_profile_image != null || $uploaded_profile_image != "")
{
//file_put_contents($uploaded_profile_image);
move_uploaded_file($uploaded_profile_image, $profile_image_upload_dir);
//file_put_contents($uploaded_profile_image,$profile_image_upload_dir);
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image;
$sql = "UPDATE user_login_table SET user_profile_image = '$uploaded_profile_image_link' WHERE user_name = '$logged_user_name'";
mysql_query($sql, $db_connection);
}
$db_connection_obj -> close_database_connection($db_connection);
}
?>
HTML Code:
<form enctype="multipart/form-data" name="uploadprofileimage" onsubmit="" action="" method="post">
<input type="file" name="propic" id="propic" onclick="" >
<input type="submit" value="Upload" name="upload" id="submit" >
<br>
<label for="propic" id="picerrorlabel"></label>
</form>
<?php
if(isset($_POST['upload'])) //This ensures the function runs only when the submit button is clicked.
{
upload_image();
}
The correct way to access selected File is as follows
$uploaded_profile_image = $_FILES['propic']['name'];
Make sure you are uploading file within limit of configured file size in php.ini (upload_max_filesize). rest all should work.
Correction 1:-
Your are passing only directory name in move_uploaded_dir. I think you should pass complete image path. and $uploaded_profile_image should be your image tmp_name.
move_uploaded_file($_FILES['propic']['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image);
Correction 2:- You can't get image name in $_POST. so it should be
$uploaded_profile_image = $_FILES['propic']['name'];
You cannot get image or any file in $_POST['propic']; the correct way to access file or image is by using $_FILES
so you should use $uploaded_profile_image = $_FILES['propic']['name'] in move_uploaded_file function. Make sure to check upload_max_filesize limit in php.ini.
To upload a file in php use move_uploaded_file()
$path="upload/".$_FILES["file"]["name"]; // This specifies the path to save file
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
First You cant get file value in POST method so you need to user $_FILE to get file. So you need to replace line no 5 with this :
$uploaded_profile_image = $_FILES['propic'];
Another mistake in your code is while moving uploaded file where source params is expected to be temporary location of file :
move_uploaded_file($uploaded_profile_image['tmp_name'], $profile_image_upload_dir.$uploaded_profile_image['name']);
Now in line no 27 you can get file name to store in database this way :
$uploaded_profile_image_link = $profile_image_upload_dir.$uploaded_profile_image['name'];
Related
Is it possible to get the filename of a file, without a complete upload
Meaning after the user chose a file, dont upload that file, just get the filename and save to database?
yes it is possible you can use the code as given below
$filename=$_FILES['nameofyourfileinput']['name'];
echo $filename;
you can echo the $filename;
OR You can use jquery to get this value like
$('#inputid').change(function(){
var value =$(this).val();
alert(value);
})
ya it is possible.You can also do this before uploading the file basename() is enough for extracting name.
$next=$pfet['f_name']; //fetched file from database
$next1 = basename($next);
The accepted answer doesn't prevent the file upload, it simply provides a way to get the file name independent of the file contents.
Preventing file upload, is best looked at the other way: what enables uploading a file. The answer to that is the enctype attribute on the form tag (multipart/form-data).
HTML:
<form action="upload.php" method="post" enctype="application/x-www-form-urlencoded">
Select:
<input name="upload[]" type="file" multiple="multiple" />
<input type="submit" value="Update" name="submit">
</form>
PHP:
$total = count($_POST['upload']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
$fileName = $_POST['upload'][$i];
}
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 trying to upload a file to my site but for some odd reason its not working. The exists=true is triggering so this means it should be working right? Its giving me the $error=true;. Below is my code:
HTML:
<input size="30" enctype="multipart/form-data" name="profile_icon" id="register-profile_icon" class="elgg-input-file" type="file">
PHP:
$profile_icon = $_FILES["profile_icon"];
if($profile_icon){
$exists=true;
}
$error = false;
if(empty($profile_icon["name"])){
register_error(elgg_echo("profile_manager:register_pre_check:missing", array("profile_icon")));
$error = true;
}
Use $_FILES["profile_icon"]["tmp_path"] for file path.
$_FILES["profile_icon"] This will contains arrays of values like name, tmp_path, type, size etc.
On another note you need to add enctype attribute to your <form>.
And there is function available for moving upload function move_uploaded_file();
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/".
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