Php scandir() problems - php

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";
}

Related

File_get_contents(): failed to open stream: Connection refused

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);
}
}

PHP-File upload failed to open stream - wrong folder

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;
}
}
}
?>

PHP's move_uploaded_file error: Permission denied on Mac

I'm new to PHP and I seem to have a problem uploading file to the web server. I've made myself a simple form and have a PHP file to control the uploading but every time I run the code, I get an error. Here is the code:
<?php
$name = $_FILES['upload']['name'];
$temp = $_FILES['upload']['tmp_name'];
$error = $_FILES['upload']['error'];
if ($error = 0) {
move_uploaded_file($temp, "images/" . $name);
echo 'Success';
} else {
die ('$error');
}
?>
and this is the error:
Warning: move_uploaded_file(images/macbook.jpg): failed to open stream: No such file or directory in /Library/WebServer/Documents/doc/ch07/upload_check.php on line 7
Warning: move_uploaded_file(): Unable to move '/private/var/tmp/phpuMC0td' to 'images/macbook.jpg' in /Library/WebServer/Documents/doc/ch07/upload_check.php on line 7
Thanks in advance!
error assign vs evaluate
if ($error = 0) should be if ($error == 0)
name is from basename. also declare the target before.
$target_path_file = 'images/' .basename($_FILES['upload']['name']);
move_uploaded_file($temp, $target_path_file);

Trying to validate a folder being dynamically created using PHP

I am trying validate: whether or not the folder I am attempting to create exists. Sure, I get a message... an error message :/ telling me it does! (if it doesn't exist, no error message, and everything goes as planned).
It outputs this error message
Directory exists
Warning: mkdir() [function.mkdir]: File exists in /home/***/public_html/***/formulaires/processForm-test.php on line 75
UPLOADS folder has NOT been created
The current code I use is this one:
$dirPath = $_POST['company'];
if(is_dir($dirPath))
echo 'Directory exists';
else
echo 'directory not exist';
function ftp_directory_exists($ftp, $dirPath)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dirPath))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>'.$dirPath . " has been created".'<br/>';
} else {
echo '<br/>'.$dirPath . " has NOT been created".'<br/>';
}
I added the middle part recently (I don't know if that would even have an impact). The one that starts off with "function ftp_directory_exists($ftp, $dirPath)"
Use file_exists() to check if a file / directory exists:
if(!file_exists('/path/to/your/directory')){
//yay, the directory doesn't exist, continue
}
The function ftp_directory_exists you added won't have any impact on your code as it is never called...
You might tried something like this (not tested...) :
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if(!dirExists)
$dirExists = mkdir($dirPath, 0755);
echo '<br/>'.$dirPath . (($dirExists)? "" : "DO NOT") . " exists".'<br/>';

PHP Fix Needed on How to Bypass mkdir if Folder Already Exists

I have a PHP file which creates a unique directory for each user when a file is uploaded. I would like the script to check and see if the directory already exists and if so then skip the mkdir action. Here is my code sample:
<?php
$thisdir = getcwd();
$new_dir = "123";
$full_dir = $thisdir . "/upload/" . $new_dir;
if(mkdir($full_dir, 0777))
{
echo "Directory has been created successfully... <br>";
}
else
{
echo "Failed to create directory...";
}
?>
To continue this example, please assume that the folder "123" already exists. How do I modify it for this case? I am thinking it must be some sort of if...else statement. Thanks for going through this issue.
Use is_dir() to find out whether the folder already exists.
function maybe_mkdir($path, $mode) {
if(is_dir($path)) {
return TRUE;
} else {
return mkdir($path, $mode);
}
}

Categories