I have a form(HTML, PHP) that lets the end user upload a file to update the database(MySQL) with the records in the uploaded file(specifically .csv). However, in the phpscript, I can only get the filename and not the complete path of the file specificed. fopen() fails due to this reason. Can anyone please let me know how I can work on finding the complete path?
HTML Code:
<html>
<head>
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<p>File to upload : <input type ="file" name = "UploadFileName"></p><br />
<input type = "submit" name = "Submit" value = "Press THIS to upload">
</form>
</body>
</html>
PHP Script:
<?php
.....
......
$handle = fopen($_FILES["UploadFileName"]["name"], "r"); # fopen(test.csv) [function.fopen]: failed to open stream: No such file or directory
?>
name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:
$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
$target='uploads/'.basename($_FILES['UploadFileName']['name']);
if(move_uploaded_file($_FILES['UploadFileName']['tmp_name'],$target)) {
//Insert into your db
$fp = fopen($target, "r");
}
I wrote like this:
$filePath = realpath($_FILES["file"]["tmp_name"]);
This gave me the full path to the uploaded file in PHP. If you find 0 bytes problem in file download, just modify this content-lenght line like this
header("Content-Length: ".filesize($filePath));
Where $filePath should be absolute path to file not just file handle.
Use the following code,
$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
I use like this...
<?php
$NameOriginal = $_FILES["UploadFileName"]['name'];
$Typo_Image = $_FILES["UploadFileName"]['type'];
$name_Temp = $_FILES["UploadFileName"]['tmp_name'];
?>
Related
I am creating something like google drive or some cloud using PHP and HTML where you can save your files but i have problem with saving files to binary code and uploading it to database. I mean i want to do something like that:
User is uploading file by form in html -> converting file to binary -> saving it in database.
User can download his file by some button or smh like that -> file is converting from binary to file.
I tried with doing a script what will save bin code in my database but when i am trying to send some files i am getting error like that:
Fatal error: Uncaught TypeError: fopen(): Argument #1 ($filename) must be of type string, array given in C:\xampp\htdocs\fileshub\src\send_file.php:12 Stack trace: #0 C:\xampp\htdocs\fileshub\src\send_file.php(12): fopen(Array, 'rb') #1 {main} thrown in C:\xampp\htdocs\fileshub\src\send_file.php on line 12
This is my form in html:
<form class="upload-form" action="./src/send_file.php" method="post" enctype="multipart/form-data"><br>
<input type="text" name="filename" id="filename" placeholder="File name">
<input type="file" name="file" id="file"><br>
<button type="sumbit" class="submit">Submit</button>
</form>
And this is my script in php:
<?php
session_start();
include "../src/db_conn.php";
if(isset($_SESSION['id'])) {
$id = $_SESSION['id']; // id usera
$filename = $_POST['filename']; // nazwa pliku
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
$size = filesize ($file);
$contents = fread ($data, $size);
fclose ($data);
$binfile = base64_encode($contents);
if(!$filename|| !$file) {
header("Location: ../index.php?error=Enter your data!");
exit();
} else {
$check = "SELECT bin_code FROM files WHERE user_id = '$id' AND bin_code = '$binfile' AND file_name = '$filename'";
$result = mysqli_query($conn, $check);
if(mysqli_num_rows($result) === 1){
header("Location: ../index.php?error=Your file exsist.");
exit();
}else {
$save = "INSERT INTO files (user_id, file_name, bin_code) values('$id', '$filename', $binfile)";
$saveresult = mysqli_query($conn, $save);
$saveresult;
header("Location: ../index.php?error=Your file has been saved");
exit();
}
}
}
?>
db_conn:
<?php
$server = "localhost";
$user ="root";
$password = "";
$db = "fileshub";
$conn = mysqli_connect($server, $user, $password, $db);
?>
If you know any solutions for my problem please help :)
Files table
Users table and example user
I believe you know that uploading an image to a directory is a more efficient way to store it.
Please note that $_FILES['file'] is an array containing all sorts of information of the uploaded file, for your case you have to use the filename of the uploaded file. (which is "tmp_name")
So change
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
to
$file = $_FILES['file']["tmp_name"];
$data = fopen ($file, 'rb');
On the other hand, an alternative way is to use file_get_contents instead of fopen, fread, etc.
$contents = file_get_contents($_FILES['file']["tmp_name"]);
So firstly you need to ensure you have a directory that PHP has access and has permissions on but that is not publicly accessible. Usually, on web hosts the web root folder is a sub folder of the home directory, so you can create a new folder there for file storage. Eg:
/home/myuser/public_html/ <-- might be the web root (some installations differ eg: htdocs or html or httpdocs)
/home/myuser/files/ <-- Create this folder for storing files.
Alternatively, if youre web server is Apache, you can create a folder inside your web root, and protect that folder using a .htaccess file
The easiest way then to store an uploaded file on the file server is to use the move_uploaded_file command that PHP provides, here is how I would achieve this:
$postname = 'file';
$root = '/home/myuser/files';
//cleanse the filename to prevent SQL injections when saving to DB
$filename = preg_replace("/[^a-zA-Z0-9\.]/","_",$_FILES[$postname]['name']);
$path = "$root/$filename";
//Create the files folder if it doesnt already exist...
if(!file_exists($root)) if(!mkdir($root,0775,true)) die("Failed to create root folder $root");
//Store the uploaded file in the files folder
if(!move_uploaded_file($_FILES[$postname]['tmp_name'],$path)) die('Failed to move uploaded file into asset storage');
//Store the file location in the database...
$saveresult = mysqli_query($conn,"INSERT INTO `files` (`filename`,`path`) VALUES ('$filename','$path')");
I'm trying to remake the script to save the phone configurations to the server. I have a script that generates configs and displays their name and code on the page.
It looks like this:
<br>File:112233445566.cfg<br><textarea rows="50" cols="100">#!version:1.0.0.1
#File header "#!version:1.0.0.1" can not be edited or deleted.#
account.1.enable = 1
account.1.label = 123
account.1.display_name = 123
account.1.auth_name = 123
</textarea>
<br>File:112233445566.xml<br/><textarea rows="50" cols="100"><xxxIPPhoneDirectory>
</xxxIPPhoneDirectory>
</textarea><br/>`
How do I save the information I received in textarea in two different files with different names (File:xxxxxx.xxx) in the folder on the server?
https://pastebin.com/wSrfQGCt Code of original file
https://pastebin.com/9uqkRPmv Result page in html
Try submitting the form with textarea and then:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['name_you_give_to_first_textarea']) && isset($_POST['name_you_give_to_second_textarea'])){
#First file
$handler = fopen('path/to/folder/file1.txt', 'w+'); #this creates the file if it doesn't exist
$file1 = fwrite($handler, $_POST['name_you_give_to_first_textarea']);
fclose($handler);
#Second file
$handler = fopen('path/to/folder/file2.txt', 'w+'); #this creates the file if it doesn't exist
$file2 = fwrite($handler, $_POST['name_you_give_to_second_textarea']);
fclose($handler);
}
}
I want to move example.txt file on my server (/var/www/tmp) to different destination (/var/www/tmp/dir). I want to have this file only in one destination in which is file moved, so only one file on server. I have tried many commands but I wasn't sucessful. Can you help me with this issue? Thanks.
Source code:
<html>
<body>
<?php
// variables from the form
$blogentry = $_POST['blogentry'];
// creating or opening the file in append mode
$dataFile = "example.txt";
$fh = fopen($dataFile, 'a');
// writing to the file
fwrite($fh,"". " " . $blogentry . " " . "\n\n");
fclose($fh);
?>
</body>
</html>
You would use PHP's rename() function to move files (the name of the function can be a little confusing).
rename("/var/www/tmp/file.txt", "/var/www/tmp/dir/file.txt");
You can probably just use the rename() function. From http://php.net/manual/en/function.rename.php:
rename("var/www/tmp/example.txt", "/var/www/tmp/dir/example.txt");
I'm trying to upload a file from my custom HTML form to a PHP script. Here is the code that I have in my HTML.
<form action="test.php" method="post" enctype="multipart/form-data">
<input id="txt" class="button" type = "text" value = "Choose File" onclick ="javascript:document.getElementById('file').click();">
<input id = "file" type="file" style='visibility: hidden;' name="img" onchange="ChangeText(this, 'txt');"/>
<input type="submit">
</form>
Here is the test.php file:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$target = "i/";
if (move_uploaded_file($_FILES['img']['tmp_name'], $target)) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
Here's the error on the page:
Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /var/www/BLOCKED/test.php on line 7
Warning: move_uploaded_file(): Unable to move '/tmp/phpNxxB72' to 'i/' in /var/www/BLOCKED/test.php on line 7.
Yes it's permissions of the directory are 777.
the 2nd argument of move_uploaded_file should be a file name (with path) not a directory
$target = "i/".basename($_FILES['img']['name']);
The error is correct. The 2nd parameter to move_uploaded_file() is not a directory, it should be a file. You just need to append the file's name to $target in the 2nd parameter. For example:
if (move_uploaded_file($_FILES['img']['tmp_name'], $target.$_FILES['img']['name'])) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
move_uploaded_file function should be like this:
move_uploaded_file($_FILES['img']['tmp_name'], $target. $_FILES["img"]["name"])
add file name at end, as $target is a directory/folder only.
Tantibus, as you can read here:
http://php.net/manual/en/function.move-uploaded-file.php
You must specify the file name to your target file.
$target = "i/".basename($_FILES['img']['name']);
you probably missed this.
This question already has answers here:
Saving image from PHP URL
(11 answers)
Closed 6 years ago.
How can I use php to download an image from URL (eg: https://www.google.com/images/srpr/logo3w.png) then save it?
This is what I came up with so far, it gives me an error in 'file_put_contents' function.
<form method="post" action="">
<textarea name="text" cols="60" rows="10">
</textarea><br/>
<input type="submit" class="button" value="submit" />
</form>
<?php
$img = "no image";
if (isset($_POST['text']))
{
$content = file_get_contents($_POST['text']);
$img_path = '/images/';
file_put_contents($img_path, $content);
$img = "<img src=\"".$img_path."\"/>";
}
echo $img;
?>
It gives me the error:
[function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\img.php
The /images/ directory is located in the same directory of the php file and is writable.
You cannot save the image with your existing code because you do not provide a file name. You need to do something like:
$filenameIn = $_POST['text'];
$filenameOut = __DIR__ . '/images/' . basename($_POST['text']);
$contentOrFalseOnFailure = file_get_contents($filenameIn);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
file_put_contents() requires first parameter to be file name not the path.
What is your error ? But you have the right way to do what you want to do.
Just take care in your code, I can see file_put_contents($img_path, but $img_path is a path to a folder.
You need to write something like :
example
$img_path="home/downloads/my_images";
file_put_contents($img_path."/flower.jpg");
file_put_contents($img_path, $content);
To what are you putting to?? i think you have made a mistake with get and put. or missed to specify the full path including the file name and extension
I added one condition to accepted answer to check the image type as follows,
if (exif_imagetype($_POST['text']) == IMAGETYPE_PNG) {
$filename = './images/'.basename($_POST['text']);
file_put_contents($filename, $content);
}
from above example I show how to check png images before download the files and for more content types you can find here .