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')");
Related
I am trying to upload an image from android to mysql
Now the path can be successfully uploaded but there's something wrong on this code
<?php
require_once '../database/database.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// base_64 encoded string from android
$imageData = $_POST['image'];
// edittext from android
// $imageName = $_POST['image_name'];
$path = "images/Sample.jpg";
$actualPath = "http://192.168.254.123/*****/admin/$path";
if($user->UploadFiles($actualPath))
{
file_put_contents($path, base64_decode($imageData));
echo "Success";
}
else
{
echo "Failed";
}
}
?>
On the line where file_put_content is the error . here's the full error
Warning file_put_contents(images/Sample.jpg):failed to open stream:No such file or directory in C:\xampp\htdocs\projectname\admin\apk_api\upload_profile.php on line 17
Here's the proof that I can actually save the path on my database
and here's my directory
Can someone please help me out.
The directory images/ does not exists from the point of view, where the admin\apk_api\upload_profile.php file is. The resulting directory path will be
C:\xampp\htdocs\projectname\admin\apk_api\images\
However, the target directory should be
C:\xampp\htdocs\projectname\admin\images\
Create a relative path based from the location of the admin\apk_api\upload_profile.php file. You have to use something like ../images/ to get to the target directory.
this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission
I have problem to find file path. I have a form that can insert file or image.
Below code shows how the file or images save
if($_FILES["lampiran"]["name"][$i] != "")
{
$my_folder = "./files";
$location = $my_folder.'/'.$pname;
$imageFileType = pathinfo($tname,PATHINFO_EXTENSION);
move_uploaded_file($tname,$location);
$query2 = "INSERT into list_lampiran (id_aduan, folder, lampiran, nama_asal, type, size, time_create) VALUES ('$id_aduan', '$my_folder', '$location', '$pname', '$file_type', '$file_size', '$time_create')";
mysqli_query($con, $query2);
$id_lampiran=mysqli_insert_id($con);
if($query2){
$myfile_rename = $id_lampiran.'_'.$pname;
rename($location, './files/'.$myfile_rename);
$query3 ="UPDATE list_lampiran SET lampiran = '$myfile_rename' WHERE id = '$id_lampiran'";
mysqli_query($con,$query3);
}
}
Then the file or image will sent through an email and appear as a link. But the link have invalid URL
Code to display the file or image in email
if(mysqli_num_rows($resultlampiran) > 0){
$rowlampiran = mysqli_fetch_array($resultlampiran,
MYSQLI_ASSOC);
$folder_name = $rowlampiran['folder'];
$lampiran = $rowlampiran['lampiran'];
$lampiran1 = $folder_name.'/'.$lampiran;
$nama_asal = $rowlampiran['nama_asal'];
$file = "<ul><li><a href='".$lampiran1."'>".$nama_asal."</a></li></ul>"; }
Redirect notice
You missed to include the URL of your website in the file link. You need to update the file path in your email template or so as:
$website = "https://example.com/";
$file = "<ul><li><a href='".$website.$lampiran1."'>".$nama_asal."</a></li</ul>";
and you're good to go :)
Also, you have coded without caring about the security of your application. Anyone could easy upload backdoor or any other PHP
scripts and destroy all the data and files on your server. You must
validate file extension and then save to your database
Example:
$validExt = array("jpg", "png", "pdf", "txt"); // valid extensions that should only be allowed.
// and then check if upload file's extension matches in our valid list
if(in_array(strtolower($imageFileType), $validExt) === false) {
// some other file extension found, show error message
} else {
// upload your file here and save to database
}
This is your file url
$location = "www.sitename.com/". $my_folder.'/'.$pname;
echo $location;
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 have a file with extension PDF and DOCX, and when i download it from my server, the file cannot opened and the size become 1kb, when in my server folder it has 199kb size. iam using database to store the file path and filename, here is my view to download the file
View
<?php echo $details->FILE_NAME; ?>
and my controller
Admin_Controls.php
function download_proposal($id_pemesanan) {
$this->load->helper('download');
$this->load->model('gedung/gedung_model');
$temp_id = substr($id_pemesanan, 7); //i cut the string because it content prefix string
$data = $this->gedung_model->get_proposal_by_id($temp_id);
$path = file_get_contents($data->PATH.$data->FILE_NAME);
$file_name = $data->FILE_NAME;
force_download($file_name, $data);
}
my model
Gedung_Model.php
public function get_proposal_by_id($id_pemesanan) {
$sql = "SELECT * FROM pemesanan_details WHERE ID_PEMESANAN = $id_pemesanan";
$query = $this->db->query($sql);
$hasil = $query->row();
return $hasil;
}
my problem is just after i download the file, it becomes corrupted and cannot open, like i say the size become 1kb. all works well from user click to download until the download process
Thanks in advice
I would like to check the path . You can use absolute path of the file for testing purpose instead of dynamic generated path .