Trying to display images from a filesystem in php - php

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

Related

how to use filemtime function in PHP?

i have a database like picture bellow :
database
i want to insert date and time based on last modified date from a file on my computer in uploaddate column automtically using filemtime() function in php.
i have tried to use this code :
$namefile= $_FILES['filename']['name']; //from file i have uploaded
if (file_exists($namefile))
{
$uploaddate = date ("Y-m-d H:i:s", filemtime($namefile));
}
echo $uploaddate;
and this is my SQL Query :
$import="INSERT into scan (UploadDate, ScanDate, FileName)
values('$uploaddate', '$date', '$namefile')
ON DUPLICATE KEY UPDATE UploadDate='$uploaddate', ScanDate='$date',
FileName='$namefile'";
echo function is running and true but i still can't insert into database.
May you know where is the problem? Thank you so much for your help.
The problem is - you are trying to get modified time of name(!) not a path of the file.
This sample will work, if you will create and upload_from directory and put it near your form-processor file. You should then upload your files from there. Or you could specify another one (the path should be absolute). Unfortunately, this decision will work only in those specific cases.
However, the manipulations with modify-time of file - are tricky, because it could be set by users manually, it could come from users with different time-settings, so, you can only believe to your machine with that local decision, that I provided.
PS: I did not find the ways to access the absolute file name on uploaded file.
index.php contents:
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit">
</form>
<?php
$upload_from_dir = 'upload_from';
if (!empty($_FILES)) {
$namefile = $upload_from_dir . DIRECTORY_SEPARATOR . $_FILES['filename']['name'];
if (file_exists($namefile)) {
$uploaddate = date("Y-m-d H:i:s", filemtime($namefile));
echo $uploaddate;
}
}
?>

Javascript and PHP upload system

Thanks in advance for any help, I hope my explanation of my request is understandable.
I have a website where I upload various HTML pages with scripts, websites etc. that I have found useful over time... For the purpose of 1) a reference for myself, and 2) to share what I've found with others.
The website consists of 2 sections. A search page to find the script, and an admin page to upload it. The uploaded HTML file gets placed in a "docs/" directory on my server, and the details are added to a MySQL database for the search page.
The form looks like this:
<form name="upload" enctype="multipart/form-data" action="includes/add.php"
method="post" onsubmit="return validateForm();">
<label for="scriptname">Script Name</label><input class="inputarea" type="text"
name="scriptname"><br>
<label for="category">Category</label><input class="inputarea" type="text"
name="category"><br>
<label for="keywords">Keywords</label><input class="inputarea" type="text"
name="keywords"><br>
<label for="content">HTML File</label><input class="inputarea" type="file"
name="content"><br>
<input class="submit" type="submit" value="Add">
</form>
My question is this... Is there any way with JavaScript or PHP to do the following:
generate an automatic file name for the uploaded file (a few random digits would do)
In the "scriptname" input field, add text on submit so that it makes the Script name and file name into a hyperlink that's added to the database as text... eg. When submit button is pressed, the following is added to the database:
"scriptname_input"
Where the bold section is taken from the generated file name and the italic section is from the input field...
The purpose of this is so that in the search results, when the database column with the script name comes up, the script name is a link to the actual file. I have the search feature ready, and it is able to make a link from a database entry, but I just need to simplify the upload process.
If this is not possible, is there a different way to achieve this?
---EDIT---
Thank you all for your help! Much appreciated, I've worked it out using a combination of a few of the suggestions. However, I gave the credit to Ibere as his solution was the closest.
Here is the final code I used for the 'add.php' file that processed the upload and database addition, just in case it ever comes up again (I doubt it) :P
<?php
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
$url = "$labelForUrl";
$target = "../docs/";
//This gets all the other information from the form
$name=$_POST['scriptname'];
$cat=$_POST['category'];
$key=$_POST['keywords'];
$link=$_POST['link'];
$file=($_FILES['content']['scriptname']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or
die(mysql_error()) ;
mysql_select_db("scripts") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO scripttable (scriptname,category,keywords,link,content)
VALUES ('$url', '$cat', '$key', '$link', '$file')") ;
if(move_uploaded_file($_FILES['content']['tmp_name'], $target . $filename)) {
echo "The file ". $labelForUrl.
" has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
You can do something like this for the filename.
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
md5 is not Random, but is good enough for generating a unreadable string for a filename.
Then you can create a url like this
<a href="docs/<?php echo $filename; ?>" ><?php echo $labelForUrl; ?></a>
Hope this helps.
EDIT: I forgot to add the extension to the filname. So the right code would be something like:
$filename = md5($_FILES['content']['name']).$_FILES['content']['type']
I recommend using uploadify for uploads. But, to do what you asked:
$randomFileName = rand(1000, 9999);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $randomFileName . $_FILES["file"]["type"]);
// update your db with the location
$loc = "upload/" . $randomFileName . $_FILES["file"]["type"];
mysqli_query("insert into `myTable` (`loc`) values ('$loc')");
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
For file uploading help, look at http://www.w3schools.com/php/php_file_upload.asp
This is very easy, if you know codeigniter ( PHP Framework ).
You can use the Upload Class
You can easily create forms and submit them and also display them.
I would do it that way. If you are familiar with MVC you can do that in 10-15 mins.
To generate random file names, I usually find this does the work quite well: md5( rand( 0, 100000 ) );. If you wish to limit the size of the file name, you may use the substr function.
(Assuming a MySQL database), make the connection and then query the database using the INSERT command. This link shows how to do all of this.

File upload php mysql

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

uploading image to mysql using php

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

CSV Import to MySQL Table with image copy

Wondering if anyone would be so kind to help me with a addition to this script i have found online:
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
Import File : <input type='text' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
i have a csv which i want to import a bunch of data and this piece of code i have found online should do the trick but i have a couple of extra things i need to apply and hoping someone would be willing to write additional code to this for this to work.
i have 2 fields in the csv container image paths from another url:
image: http://blag.com/images.jpg
images: http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg
i am wanting to grab the image from the external url and upload it to a path on the site itself and then set the local image path and image name in the database
the images part contains multiple images which i need to do the same but apply to another field with those on them but would need to be able to display those additional images on the page but not sure if possible with that ; seperator in the database but guess you guys will know if its possible to fectha dn display but thats something ele i guess
if someone would be so kind to help me adapt that code so i can do that would be awesome as need to import a lot of data tonight :)
Thanks in advanced!
I wouldn't use php for this task. For importing the csv data I would use mysqlimport as it is much more efficient and less error prone then rolling your own php solution. For retrieving the images and storing them locally you could easily write a ruby or perl or even a bash script with curl to fetch the image and place them in the correct directory.
If this is part of another tool written in PHP then I would = look to using a system command to execute the mysqlimport on the local file. Then I would use the curl facility to grab the images and place them in the appropriate directory.
James,
you can add it easily,...
In this line:
$sql = "INSERT into user(name, email, phone) values('$data[0]','$data[1]','$data[2]')";
add the name of related Database Fields to the first part(for example:)
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]')";
and for add their values from the result array in $data if they are immediately after other items (I mean if it is in this format: Name - Email - Phone - image - images) you just need to add to the index of array, in this condition it would be something like this:
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]' **,'$data[3]','$data[4]'** )";
------------------------------------------------
UPDATED
OK, that's not hard too... I wrote a sample code for that, let me know if you have any problem:
// List of all images separated by ";"
$all_images = "http://www.google.com/images/nav_logo40.png;http://static.php.net/www.php.net/images/php.gif";
// Make an array from the list of images
$images = explode(";", $all_images);
// We want to copy all of images in the array
foreach ($images as $img_source_path){
// Retrive the name of file from path (It works for most of filenames!)
preg_match("/\/(?P<name>[a-zA-Z0-9._]+)$/", $img_source_path, $img_matches);
$img_filename = $img_matches[name];
// Make destination path
$img_destitation_path = getcwd()."/temp/".$img_filename;
// Copy file and check if it is done successfully
if (!copy($img_source_path, $img_destitation_path)) {
echo "failed to copy $img_filename...\n";
}
else {
echo "$img_filename copied successfully...\n";
}
}

Categories