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";
}
}
Related
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 have a website that allows users to upload a file. when uploading the file on another page users can download that file. the problem is if the file name has a space in it will only pick up the first work not the whole file name. i was wondering is there a way to download the file with spaces in it or an easy option might be to add underscores to the file name so that it can be downloaded.
//This is the directory where images will be saved
$target = "../images/avatars/";
$target = $target . basename($_FILES['photoLocation']['name']);
// Check to see all fields have been completed
$photoLocation =($_FILES['photoLocation']['name']);
if (!empty($photoLocation))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblPhotoUpload (photoLocation) VALUES ('$photoLocation')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
//Writes the photo to the server
if(move_uploaded_file($_FILES['photoLocation']['tmp_name'], $target))
// Close connection to the database
mysql_close()
And i am displaying the file like this.
while($record = mysql_fetch_array( $result ))
{
?>
<tr class="row">
<td class="cell"><a href= http://xxxxxxxxxxxxxxxxxxxxxx.com/images/avatars/<?php echo $record["photoLocation"];?>>Download</a> </td>
You're dealing with an escaping scheme within an escaping scheme when you work with URLs. In particular, you have to escape the URL so as to be a URL, and then you have to escape the URL as to embed it in HTML:
$url = "http://somesite.tld/some/path/" . urlencode($filename);
echo 'link';
It's pretty damn hard to think of a (realistic) situation that actually requires htmlspecialchars, but wooo paranoia!
Oh, and also, it's typically a good idea to just go ahead and quote all of your attribute values.
When you do: <tag attr=value with spaces> browsers interpret with and spaces as additional attributes, notas part of the value for attr
If you do go the replacement route though, you're just looking for a simple str_replace call:
$val = str_replace(' ', '_', $replaceMe);
Haven't tested but this logic seems right.
$name = str_replace(' ', '_', $photoLocation);
i would recommend to not display image by it original name, since there alot of security problems associated with that.
a way u can do it is to encode file name and save it in extra field in database.
example
$sql = "INSERT INTO tblPhotoUpload (photoLocation,photourl) VALUES ('$photoLocation','".md5($photoLocation)."')";
and when display use phtolocation in url and make display route that to photo location.
good luck,if u need full example let me know
str_replace()
$file= str_replace(' ','_',$file);
or in your case :
$target = $target . basename(str_replace(' ','_',$_FILES['photoLocation']['name']));
$photoLocation =(str_replace(' ','_',$_FILES['photoLocation']['name']));
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.
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
I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.