I am trying to download a previously uploaded file, form database and uploads folder in php codeigniter. I am using code below but downloading empty file.
controller.php
public function downloadFile($incidents_id)
{
$file = $this->incidents_model->getfile($incidents_id);
//echo $file; die;
$this->load->helper('download');
$path = file_get_contents(base_url()."uploads/".$file); //(the error shows on this line)
// echo $path; die;
$name = $file; // new name for your file
// echo $name ; die;
force_download($name, $path); // start download`
}
incidents_model.php
function getfile($Incident_id )
{
$file = $this->db->select('file');
$this->db->from('incidents');
$this->db->where('incidents_id' , $Incident_id );
$query = $this->db->get();
// return $query->row();
if ($query->num_rows() > 0) {
return $query->row()->file;
}
return false;
}
view.php
<div class="form-group col-md-4">
Download file
</div>
so running this code download an empty file.
echo $file; die; displays the file name which been saved in db and in uploads folder
echo $path; die; generates an error:
Severity: Warning
Message:
file_get_contents(http://localhost:8080/ticketing_tool_v2/uploads/Screenshot
2021-03-04 at 5.59.38 PM.png): failed to open stream: Connection
refused
Filename: admin/Incidents.php
Line Number: 380
Reviewing the documentation for file_get_contents you'll observe there's many different ways you can use it. For your purposes you would need to allow inbound connections to the filesystem.
The other way you could do this for better future proofing is to use the CodeIgniter file helper - https://codeigniter.com/userguide3/helpers/file_helper.html
Before reading the file from path, please check whether a path points to a valid file.
public function downloadFile($incidents_id) {
try {
$this->load->helper('download');
$file = $this->incidents_model->getfile($incidents_id);
$data = file_get_contents(base_url("uploads/" . $file));
$name = $file; // new name for your file
force_download($name, $data); // start download`
} catch (Exception $e) {
//exception handling code goes here
print_r($e);
}
}
Related
I got a problem with fileuploading images.
When I try to upload I get this error:
Warning: copy(/assets/img/products/): failed to open stream: No such file or directory in /customers/d/7/4/(website name)/httpd.www/newSite/pages/admin/adminPages/products.php on line 212
This is the code it's referring to:
if(isset($_POST['submitMoreImg'])){
$name = $_POST['imgName'];
$prod_id = $_POST['prod_id'];
if(!empty($_FILES['image']))
{
$path = "/assets/img/products/";
$path = $path.basename( $_FILES['image']['imgName']);
if(copy($_FILES['image']['tmp_name'], $path)) {
echo'<script type="text/javascript">
alert("uploaded");
</script>';
uploadExtraImg($name, $prod_id);
}
else{
echo "Error: ".$sql."<br>".$connection->error;
}
}
}
I can't seem to find the correct folder, I tried a lot of different folder path.
The issue is apparent.
Warning: copy(/assets/img/products/): failed to open stream: No such file or directory in /customers/d/7/4/(website name)/httpd.www/newSite/pages/admin/adminPages/products.php on line 212
It's looking in directory /customers/d/7/4/(website name)/httpd.www/newSite/pages/admin/adminPages/products.php
But I'm hoping that you want to get /assets/img/products/customers/d/7/4
or as a complete path (website name)/httpd.www/newSite/assets/img/products/customers/d/7/4
In that case. Please make sure your path is correct.
try changing your $path value. Like so
<?php
if(isset($_POST['submitMoreImg'])){
$name = $_POST['imgName'];
$prod_id = $_POST['prod_id'];
if(!empty($_FILES['image']))
{
$path = __DIR__."/../../../assets/img/products/";
$path = $path.basename( $_FILES['image']['imgName']) + $fileNameWithExtension;
if(copy($_FILES['image']['tmp_name'], $path)) {
echo'<script type="text/javascript">
alert("uploaded");
</script>';
uploadExtraImg($name, $prod_id);
}
else{
echo "Error: ".$sql."<br>".$connection->error;
}
}
}
?>
Please find below the coded section,
You can give your inputs based on the interpretation.
public function upload(Request $request)
{
$content = $_POST['code'];
if (Storage::exists('file.blade.php'))
{
echo "File is already exists..............";
}
else
{
Storage::disk('local')->put('file.blade.php', $content);
echo "uploaded successfully...........";
$fileName = "file.blade.php";
$oldPath = "/storage/app/file.blade.php";
$destinationPath = "/resources/views";
File::move($oldPath, $destinationPath);
}
}
I have used the above code trying to move the file. But I got the following error message.
ErrorException in Filesystem.php line 176:
rename(/storage/app/file.blade.php,/resources/views): The system
cannot find the path specified. (code: 3)
Try changing like this:
$fileName = "file.blade.php";
$oldPath = "/storage/app/file.blade.php";
//$destinationPath = "/resources/views"."$fileName";
$destinationPath = "/resources/views/"."$fileName";
I'm trying to make a upload class with PHP. so this is my first PHP class:
//Create Class
class Upload{
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
if(copy($Content, '/test/sdfsdfd.jpg')){
return "UPLOADED";
}else{
return "ERROR";
}
}
}
and usage:
$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');
problem is, this class is not working. where is the problem? I'm new with PHP classes and trying to learn it.
thank you.
copy expects filesystem paths, e.g.
copy('/path/to/source', '/path/to/destination');
You're passing in the literal image you fetched, so it's going to be
copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');
You want
file_put_contents('/test/sdfsdfg.jpg', $Content);
instead.
PHP's copy() function is used for copying files that you have permission to copy.
Since you're getting the contents of the file first, you could use fwrite().
<?php
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
// Create the file
if (!$fp = fopen('img.png', 'w')) {
echo "Failed to create image file.";
}
// Add the contents
if (fwrite($fp, $Content) === false) {
echo "Failed to write image file contents.";
}
fclose($fp);
}
Since you want to download a image, you could also use the imagejpeg-method of php to ensure you do not end up with any corrupted file format afterwards (http://de2.php.net/manual/en/function.imagejpeg.php):
download the target as "String"
create a image resource out of it.
save it as jpeg, using the proper method:
inside your method:
$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");
In order to have file_get_contents working correctly you need to ensure that allow_url_fopen is set to 1 in your php ini: http://php.net/manual/en/filesystem.configuration.php
Most managed hosters disable this by default. Either contact the support therefore or if they will not enable allow_url_fopen, you need to use another attempt, for example using cURL for file download. http://php.net/manual/en/book.curl.php
U can use the following snippet to check whether its enabled or not:
if ( ini_get('allow_url_fopen') ) {
echo "Enabled";
} else{
echo "Disabled";
}
What you describe is more download (to the server) then upload. stream_copy_to_stream.
class Remote
{
public static function download($in, $out)
{
$src = fopen($in, "r");
if (!$src) {
return 0;
}
$dest = fopen($out, "w");
if (!$dest) {
return 0;
}
$bytes = stream_copy_to_stream($src, $dest);
fclose($src); fclose($dest);
return $bytes;
}
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");
Hello so i have a simple upload system in php and i want to upload my files to ftp server but when i try to it doesnt work i get these two errors:
Warning: move_uploaded_file(/userfiles/grega): failed to open stream: No such file or directory in /srv/disk3/1618233/www/netdisk.co.nf/upload.php on line 19
Warning: move_uploaded_file(): Unable to move '/tmp/phpVtApVM' to '/userfiles/grega' in /srv/disk3/1618233/www/netdisk.co.nf/upload.php on line 19
and there is folder userfiles/grega on the ftp server please help me out
the code:
<?php
require_once 'core/init.php';
if($_POST[submit]) {
$name = $_FILES['upload']['name'];
$temp = $_FILES['upload']['tmp_name'];
$type = $_FILES['upload']['type'];
$size = $_FILES['upload']['size'];
if($size <= 5000000){
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
$uploads_dir = '/userfiles';
$username = ($user->data()->username);
move_uploaded_file($temp,"$uploads_dir/$username");
Session::flash('home', '<h3>Datoteka je bila naložena!</h3>');
Redirect::to('mojprofil.php');
} else{
echo "Napaka!";
}
} else {
header("Location: mojprofil.php");
}
?>
You say this:
there is folder userfiles/grega
But the error says this:
move_uploaded_file(/userfiles/grega)
Those are two very (even if subtly) different paths. Note also where you define the path in your code:
$uploads_dir = '/userfiles';
The code is looking for a folder called userfiles in the root of the entire file system, not just in the website. Perhaps you meant to do this?:
$uploads_dir = 'userfiles';
I was wondering, my Scandir() function works on a php $_GET variable, so the variable returns the folder, but I'm having a problem because I'm not sure how to echo out an error if there is a problem with with directory.
this is the error I am getting:
Warning: scandir(users/ro/f) [function.scandir]: failed to open dir: No such file or directory in C:\xampp\htdocs\OSO\desktop\main_content\file.php on line 31
This is my code
$folder = $_GET['file_folder'];
$directory = "users/$username/$folder";
if (scandir($directory, 0)) {
unset($documents[0], $documents[1]);
$documents = scandir($directory, 0);
// for each loop
} else {
echo "No such directory";
}
Cheers in advance
I would first check whether $directory exists using is_dir() before calling scandir():
if (is_dir($directory)) {
$filenames = scandir($directory, 0);
// do something
} else {
echo "No such directory";
}