I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>
Related
Here is my code, what I am trying to do is take the file post.php or $file from the root of the directory that it is originally from, then put it inside this uniqueID directory, or it should finally arrive in the $newFolder5 variable to complete. The $root in the !copy function is a path pointing to the file inside the current directory, then it should go it the $newFolder5 directory when the copy function is executed on the page load. Can $root or the source of the copy be a string with a directory to the file?
<?php
$unique = uniqid();
$root = '/gallry/' . $dir_auth1 . '/'. 'post.php';
$folder = mkdir($unique, 0755);
$uniqueFolder = '/' . $unique . '/' . 'post.php';
$destination2 = $dir_auth1 . '/' . $unique . '/' . 'post.php';
$newFolder = '/' . $dir_auth1 . $uniqueFolder;
if (!copy($root, $newFolder)) {
echo " status not created.";
} else {
echo "Success!";
}
?>
I changed $dir_auth1 to 'aidan', since that is the root directory that the post.php is in.
In short, what Im trying to do is create a folder/directory with a uniqid() and put post.php inside of it. Or copy it.
You're not creating the same directory that you're trying to copy into.
$unique = uniqid();
$root = "/gallry/$dir_auth1/post.php";
$uniqueFolder = "/$dir_auth1/$unique";
$destFile = "$uniqueFolder/post.php";
if (mkdir($uniqueFolder)) {
if (copy($root, $destFile)) {
echo "Success!";
} else {
echo " status not created";
}
} else {
echo "Unable to create folder $uniqueFolder";
}
I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}
note.. all folders chmod set to 777 for testing.
Okay, so i have been trying to design a simple cloud storage file system in php.After users log in they can upload and browse files in their account.
I am having an issue with my php code that scans the user's storage area. I have a script called scan.php that is called to return all of the users files and folders that they saved.
I originally placed the scan script in the directory called files and it worked properly, when the user logged in the scan script scanned the users files using "scan(files/usernamevalue)".
However I decided that I would prefer to move the scan script inside the files area that way the php script would only have to call scan using "scan(usernamevalue)". However now my script does not return the users files and folders.
<?php
session_start();
$userfileloc = $_SESSION["activeuser"];
$dir = $userfileloc;
// Run the recursive function
$response = scan($dir);
// This function scans the files folder recursively, and builds a large array
function scan($dir)
{
$files = array();
// Is there actually such a folder/file?
$i=0;
if(file_exists($dir))
{
foreach(scandir($dir) as $f)
{
if(!$f || $f[0] === '.')
{
continue; // Ignore hidden files
}
if(!is_dir($dir . '/' . $f))
{
// It is a file
$files[] = array
(
"name" => $f,
"type" => "file",
"path" => $dir . '/' . $f,
"size" => filesize($dir . '/' . $f) // Gets the size of this file
);
//testing that code actually finding files
echo "type = file, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
else
{
// The path is a folder
$files[] = array
(
"name" => $f,
"type" => "folder",
"path" => $dir . '/' . $f,
"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
);
//testing that code actually finding files
echo "type = folder, ";
echo $f .", ";
echo $dir . '/' . $f. ", ";
echo filesize($dir . '/' . $f)." ";
echo"\n";
}
}
}
else
{
echo "dir does not exist";
}
}
// Output the directory listing as JSON
if(!$response)
{ echo"failes to respond \n";}
header('Content-type: application/json');
echo json_encode(array(
"name" => $userfileloc,
"type" => "folder",
"path" => $dire,
"items" => $response
));
?>
As you can see i added i echoed out all of the results to see if there
was any error in the scan process, here is what i get from the output as you
can see the function returns null, but the files are being scanned, i cant
seem to figure out where i am going wrong. Your help would be greatly
appreciated. Thank you.
type = file, HotAirBalloonDash.png, test/HotAirBalloonDash.png, 658616
type = folder, New directory, test/New directory, 4096
type = file, Transparent.png, test/Transparent.png, 213
failes to respond
{"name":"test","type":"folder","path":null,"items":null}
You forgot to return files or folders in scan function, just echo values. That is the reason why you get null values in the response.
Possible solution is to return $files variable in all cases.
I´m building a php programm which uploads a zip file, extracts it and generates a link for a specific file in the extracted folder. Uploading and extracting the folder works fine. Now I´m a bit stuck what to do next. I have to adress the just extracted folder and find the (only) html file that is in it. Then a link to that file has to be generated.
Here is the code I´m using currently:
$zip = new ZipArchive();
if ($zip->open($_FILES['zip_to_upload']['name']) === TRUE)
{
$folderName = trim($zip->getNameIndex(0), '/');
$zip->extractTo(getcwd());
$zip->close();
}
else
{
echo 'Es gab einen Fehler beim Extrahieren der Datei';
}
$dir = getcwd();
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value) && $value == $folderName)
{
foreach (glob($value . "/*.html") as $filename) {
$htmlFiles[] = $filename; //this is for later use
echo "<a href='". SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "'>" . SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "</a>";
}
}
}
}
So this code seems to be working. I just noticed a rather strange problem. The $zip->getNameIndex[0] function behaves differently depending on the program that created the zip file. When I make a zip file with 7zip all seems to work without a problem. $folderName contains the right name of the main folder which I just extracted. For example "folder 01". But when I zip it with the normal windows zip programm the excat same folder (same structure and same containing files) the $zip->getNameIndex[0] contains the wrong value. For example something like "folder 01/images/" or "folder 01/example.html". So it seems to read the zip file differently/ in a wrong way. Do you guys know where that error comes from or how I can avoid it? This really seems strange to me.
Because you specify the extract-path by yourself you can try finding your file with php's function "glob"
have a look at the manual:
Glob
This function will return the name of the file matching the search pattern.
With your extract-path you now have your link to the file.
$dir = "../../suedkurier/werbung/"
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
foreach (glob($dir . DIRECTORY_SEPARATOR . $value . "/*.html") as $filename) {
$files[] = $value . DIRECTORY_SEPARATOR $filename;
}
}
}
}
The matched files will now be saved in the array $files (with the subfolder)
So you get your path like
foreach($files as $file){
echo $dir . DIRECTORY_SEPARATOR . $file;
}
$dir = "the/Directory/You/Extracted/To";
$files1 = scandir($dir);
foreach($files1 as $str)
{
if(strcmp(pathinfo($str, PATHINFO_EXTENSION),"html")===0||strcmp(pathinfo($str, PATHINFO_EXTENSION),"htm")===0)
{
echo $str;
}
}
Get an array of each file in the directory, check the extension of each one for htm/html, then echo the name if true.
I'm attempting to try and debug the following code with the file_exists function. I've ran a var_dump on the avatar directory and it always returns as bool(false). I'm not sure why. I tested the code below and it gets to the file exists but it proves the if statement false everytime. Any thoughts? I have looked and the image is in the directory correctly.
$default_avatar = 'default.jpg';
$avatar_directory = base_url() . 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists($avatar))
{
$user_data->avatar = $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
$default_avatar = 'default.jpg';
$avatar_directory = 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists(FCPATH . $avatar))
{
$user_data->avatar = base_url() . $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = base_url() . $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
from the name base_url seems like a function that will get a url like http://www.mysite.com, which will not work for doing local directory functions.
you need something like getcwd, or a full path
getcwd will get the current working directory (the directory where the initial script was executed from):
//If say script.php was exectued from /home/mysite/www
$avatar_directory = getcwd() . '/assets/globals/images/avatars/';
//$avatar_directory would be
/home/mysite/www/assets/globals/images/avatars/
Well this works both CLI and via Apache etc...:
$avatar_directory = substr(str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', __FILE__), 0, -1) . '/assets/globals/images/avatars/'
The did returned is the one that the php file itself is in, not the root.
assuming you meant base_url() to point to the root of your project -
$file = __DIR__ . "/path/to/file.ext";
if (file_exists($file)) {
//...
}
Or some variation thereof. This also works:
__DIR__ . "/.."
it resolves to the parent directory of __DIR__.
see PHP's magic constants:
http://php.net/manual/en/language.constants.predefined.php
If you are looking for a remote resource - a file not located on your local filesystem - you have to change your php.ini to permit that. And it's probably not a good idea, this is not usually considered safe or secure. At all.
http://php.net/manual/en/features.remote-files.php
And note:
"This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir."
-- from http://php.net/manual/en/function.file-exists.php
-- edited to add relevant information based on a comment from OP.