I am so stuck, could someone help, please?
I've been learning PHP for a while and currently, I am creating a file upload form.
What needs to happen is this:
File is uploaded
The name of the file is displayed on the main page as a link
Once the link is clicked on, information about the file displays
(first sentence or so)
The questions I have are:
File directory. I am supposed to create a folder, let's say called "uploads" - that's where the files are going to be downloaded to and have my form+php inside that folder, correct? - noob question, I know
I managed to get the name of the file appears as a link, but I don't know how to display its contents.
Could someone help, please?
Code: https://pastebin.com/rfUgKzSu
//file upload on main page
if (isset($_POST['name'])) {
move_uploaded_file($_FILES['file']['tmp_name'],'add_article_form.php' . $_POST['name'] . '.txt');
echo 'file ' . $_POST['name'] . '.txt' . 'uploaded';
}else{
echo 'There has been a mistake';
}
echo '<br>' ;
echo '<br>' ;
//form on main page
<form action = "add_article_form.php" method = "POST">
<input id = "add" type = "submit" value="add">
</form>
<?php
//display file name
$resource = opendir('../uploads/');
while(($entry = readdir($resource))!== FALSE)
{
if($entry != '.' && $entry != '..'){
echo "$entry" . '<br>';
} else {
"$entry" . '<br>';
}
}
PAGE 2
<!--The upload form, second page -->
<form action = "../uploads/" method="POST" enctype="multipart/form-data" >
Название статьи: <br>
<input type = "text" name = "name" value = "text"><br><br>
Файл:<br>
<input type = "file" name="file"><br><br>
<input id = "add" type = "submit" value="add"><br><br>
</form>
The questions I have are: 1. File directory. I am supposed to create a
folder , let's say called "uploads" - that's where the files are going
to be downloaded to and have my form+php inside that folder, correct?
- noob question, I know
No.
You can keep your upload script and the folder, where the files will be saved, anywhere even on different servers. The only thing that you should be careful that you use the correct links and proper permissions so that they can access each other.
I managed to get the name of the file appears as a link, but I don't
know how to display its contents.
Use PHP header function.
http://php.net/manual/en/function.header.php
(Go through Example 1.)
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
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 trying to upload a file from a php form.
I have verified the target location with my ISP as being "/home/hulamyxr/public_html/POD/"
I get the below error when executing the page:
Warning: move_uploaded_file(/home/hulamyxr/public_html/POD/ 1511.pdf) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/hulamyxr/public_html/hauliers/include/capturelocal2.php on line 124
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpyp3ERS' to '/home/hulamyxr/public_html/POD/ 1511.pdf' in /home/hulamyxr/public_html/hauliers/include/capturelocal2.php on line 124
POD Successfully uploaded for delivery 1511. filename: :
My Form Code
<form enctype="multipart/form-data" method="post" action="capturelocal2.php">
<input type=file size=6 name=ref1pod id=ref1pod>
</form>
My PHP Code to upload the file
$ref1 = $_POST[ref1]; //this is the name I want the file to be
$ref1pod = $_POST[ref1pod]; // this is the name of the input field in the form
move_uploaded_file($_FILES["ref1pod"]["tmp_name"],
"/home/hulamyxr/public_html/POD/ " . ($ref1.".pdf"));
Any assistance will be greatly appreciated.
Thanks and Regards,
Ryan Smith
There is an error in your code:
You need to change your move_uploaded_file funciton. There is an extra space i think which is causing the problem:
move_uploaded_file($_FILES["ref1pod"]["tmp_name"],"/home/hulamyxr/public_html/POD/" .($ref1.".pdf"));
Also i am not sure where is the
$ref1 = $_POST[ref1]; //this is the name I want the file to be
$ref1pod = $_POST[ref1pod];
coming from .There is no such values in your form. Did you upload only the form with upload only. Also be sure to put quotes around attribute values in your form and post value.
Is ref1 and ref1pod are constants. If you din't put quotes PHP will take it as constants. If they are not constants change to:
$ref1 = $_POST['ref1']; //this is the name I want the file to be
$ref1pod = $_POST['ref1pod'];
Also in your form, put quotes:
<form enctype="multipart/form-data" method="post" action="capturelocal2.php">
<input type="file" size="6" name="ref1pod" id="ref1pod"/>
</form>
Be sure you set permissions to your upload folder .
Hope this helps you :)
Check folder names, they should be case sensitive, and also check if POD folder has 777 rights(CHMOD)
Agreed with Phil, remove the space between string and file name
"/home/hulamyxr/public_html/POD/ " . ($ref1.".pdf"));
^
|
and you can also try the following :
$ref1 = $_POST[ref1];
$file_name = $_SERVER['DOCUMENT_ROOT'] . '/POD/' . $ref1 . '.pdf';
move_uploaded_file($_FILES['ref1pod']['tmp_name'], $file_name);
Please try following code.
<?php
if(isset($_REQUEST['upload'])) {
$filename = $_FILES['ref1pod']['tmp_name'];
if (file_exists($_SERVER['DOCUMENT_ROOT']."/POD/".$_FILES["ref1pod"]["name"]))
{
echo $_FILES["ref1pod"]["name"] . " Already Exists. ";
}
else {
$path = $_SERVER['DOCUMENT_ROOT']."/POD/".$_FILES['ref1pod']['name'];
move_uploaded_file($filename,$path);
}
}
?>
<form enctype="multipart/form-data" method="post" action="">
<input type=file size=6 name=ref1pod id=ref1pod>
<input type="submit" name="upload" value="upload" />
</form>
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
For some reason my PDF upload form is failing consistently, I have this code:
<?php
if($_POST["submit"] == "Add PDF to Comm and Special Projects")
{
$addsubp = $_POST["addsubp"];
$addsubp_name = $_POST["addsubp_name"];
$commuploadedfile = $_FILES['uploadedfile']['name'];
$sqldoc = "INSERT INTO projects_links (pid, display_name, link) VALUES ('".$addsubp."','".$addsubp_name."','".$commuploadedfile."')";
mysql_query($sqldoc) or die(mysql_error());
echo "<BR>";
$target_path = "D:\\Hosting\\69903\\html\\pdfs\\comm\\";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<br>The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded<br>";
} else{
echo "<br>There was an error uploading the file, please try again.<br>";
}
}
?>
<form method="post">
Add PDF to Project for Committees and Special Projects <br>Choose Project<select name="addsubp"><?php
$query = "SELECT
projects.*
FROM
projects";
$showresult = mysql_query($query);
$csp_c = 1;
while($buyarray = mysql_fetch_assoc($showresult))
{
echo "<option value=".$buyarray['id'].">".$buyarray["pname"]."</option>";
}
?></select><br>
Choose Display Name for PDF <input type="text" name="addsubp_name" /> <Br>
Choose PDF: <input name="uploadedfile" type="file" /> <Br>
<input type="submit" value="Add PDF to Comm and Special Projects" name="submit" />
</form>
I have made sure that the application has write privileges to the "comm" directory. I have godaddy and used the file manager to make sure of that. I have had problems with permissions in this project before, so I know this isn't case. It keeps printing
There was an error uploading the file, please try again.
It doesn't attempt to upload any PDF at all, what am I doing wrong?
thanks!
You may have permissions issues, but for file uploads your form tag should contain the proper enctype attribute.
<form enctype="multipart/form-data" method="POST">
and defining a file size limit is also a good idea:
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
try checking the Upload error message: http://php.net/manual/en/features.file-upload.errors.php
Your code is blindly assuming the file upload succeeded. At bare minimum you should have something like
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
... handle the upload
}
Your code is vulnerable to SQL injection. You do not escape any of the 3 values you're inserting into the database
You're creating the database record before making sure the file was successfully moved into the target directory. What happens if the file can't be written for any reason (as it is now with your problem)? The database will say it's there, file system will say it isn't
You're not checking for file collisions. If two seperate uploads send "file.txt", the second upload will overwrite the first one.
You're storing the files with the user-supplied name, which is under user control. If this file is web-accessible, anyone with access to your upload form can upload anything they want (e.g. a php file) and the server will happily execute it for them.
I want any php script which can demonstrate me how to upload multiple files in PHP. In my application I have given a link "Add Image" & 'Remove Image', on click of "Add Image" I am adding a new upload field on the page using javascript, using which user can upload more and more images, no limit on number of images for now. On click of delete i am removing that element.
I am just not getting the concept on how to process them in the POST request in PHP. I know in HTML if we give the name of field like myimages[] then it will create a PHP array, but how to process this.
I don't want to use AJAX/JavaScript for uploading, want to do it with traditional POST request in PHP.
If anyone have any link or code which shows such functionality, then pleas provide it will be really helpful.
Thanks!
combine this uploading multiple files & move_uploaded_file
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
$uploads_dir = '/uploads';
foreach ($_FILES["userfile"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Uploaded files are not in the POST array, they are in the FILES array.
http://www.php.net/manual/en/features.file-upload.multiple.php
The files are uploaded to a temp area with "safe" names. The array will contain the name of the file and the tmp file. You can then move them to where you want.
Name file input fields as file[] in HTML, then just run a loop from 0 do count($_FILES) in PHP...
for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++){
$tmp = $_FILES['file']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "File '$tmp' uploaded successfully";
}else{
echo "Uploading '$tmp' failed";
}
}
I've implemented something similar in the past as follows:
Have a hidden JavaScript form variable (e.g.: "numuploads") that stores the number of file inputs currently in the form. This will need to be incremented/decremented when you add/remove an input on the front end.
Name each of the inputs on the front end using a pattern such as "upload_X", where X is the next in the sequence. (Effectively the same as the counter above -1.)
On the PHP landing page, simply scan the $_FILES superglobal, looking for each "upload_X" where X is zero thru numuploads - 1.
You can then carry out the required logic for each of the uploaded files, other form elements, etc.