PHP - write to server folder denied - php

I have done chmod -R 777 on the root folder, but I'm still unable to successfully
upload (thus, write) to the uploaded folder!
Do I also have to change the php.ini file?
//$target_path = "http://localhost/photoServerProject/uploaded";
$target_path = "/photoServerProject/uploaded";
$fname = $_FILES["file"]["name"];
$upload_location = $target_path.'/'.$fname;
move_uploaded_file($_FILES["file"]["tmp_name"], $upload_location);
echo 'Moving file: ' . $fname . '</br></br>to: ' . $upload_location;
//echo "<img src=$upload_location>";
if(is_writeable($upload_location)){
echo '</br></br>Location <strong>is</strong> writeable ';
} else {
echo '</br></br>Location <strong>is NOT</strong> writeable ';
}
Output:
Moving file: camera.jpeg
to: /photoServerProject/uploaded/camera.jpeg
Location is NOT writeable

Try using
$targetPath= $_SERVER['DOCUMENT_ROOT'] . "photoServerProject/uploaded"
or
$targetPath= $_SERVER['DOCUMENT_ROOT'] . "/photoServerProject/uploaded"

I was confusing the difference between paths on my local drive vs server paths. My root folder (localhosts) for server paths is different than my local directory structure.

I was misunderstanding the difference between server and local disk directory structures. Namely, the root folders are different.
I'm surprised nobody brought up this issue.
Here's the solution:
<?php
$local_target = "~/webdev/photoServerProject/uploaded/";
$server_target = $_server['DOCUMENT_ROOT'] . "/photoServerProject/uploaded/";
$fname = $_FILES["file"]["name"];
$local_file_location = $local_target.$fname;
$server_file_location = $server_target.$fname;
move_uploaded_file($_FILES["file"]["tmp_name"], $local_file_location);
echo 'Moving file: ' . $fname . '</br></br>to local path: ' . $local_file_location;
echo '</br></br> But on the server it resides in : ' . $server_file_location;
echo '</br></br> See?';
echo "</br></br> <img src=$server_file_location>";
?>

Related

move_uploaded_file(/Advanced Java Programming.pdf): failed to open stream: Permission denied

So, I am working on a system where people working in a company can upload files to a system which will be sorted by departments. I have managed to get the files info(name, size, type), but the problem occurs while trying to upload the file.
I get:
move_uploaded_file(/Advanced Java Programming.pdf): failed to open stream: Permission denied
move_uploaded_file(): Unable to move 'C:\xampp\tmp\php1B99.tmp' to '/Advanced Java Programming.pdf'
I have set the permissions of the folder where the file needs to be uploaded to everybody (777).
Here's my code
<?php
$department = $_POST['department'];
$file = $_FILES['fileToUpload'];
echo "<b>Department: </b>" . $department . "<br>";
echo "<b>Name: </b>" . $file['name']. "<br>";
echo "<b>Size: </b>" . $file['size'] . " bytes<br>";
echo "<b>Type: </b>" . $file['type'];
move_uploaded_file($file['tmp_name'], "/". $file['name']);
?>
Try using an absolute path for your destination or at least start it with the DIR-constant, "/" ist not a valid (Windows)-path.
Also think about using the constant DIRECTORY_SEPARATOR as "/" is a *nix-standard, but as you're running on Windows, it should be "\" - using the constant will hold the right slash for every system.

symlink directory

Can I get an eyeball on my symlink?
I'm trying to download a file from one directory, while the file actually exists in another.
I've got the actual file, and the symlink in seperate subdirectories, but both reside in the public html(both are web accessible).
I've verified the file and file location on my (shared Linux) server by going to the file directly.
The link is being created (I've used readlink, is_link, and linkinfo), and I can see it when I FTP in.
I believe I am probably just having a misunderstanding of the directory structure.
I put the file here: ./testdownload/
I put the symlink here: ./testDelivery/
<?php
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "./testdownload/";//Where the actual file lives
$downloadDirectory = "./testDelivery/";//Where the symlink lives
unlink($downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($fileRepository . $fileName, $downloadDirectory . $fileName);
$checkLink = ($downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
Everything looks right to me....but the link won't work.
Help?
Ultimately, I will put the source data outside the public area...this is just for testing.
(I'm trying to find a better solution for download than chunking out fread which fails for poor connections. (200-400MB files))
My problem (appears) to be not providing the absolute path for the symlink.
I've added the absolute path below to the same code above, to give a working copy:
<?php
$absolutepath = ( $_SERVER['DOCUMENT_ROOT']);
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "/testdownload/";//Where the actual file lives
$downloadDirectory = "/testDelivery/";//Where the symlink lives
unlink($absolutepath .$downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($absolutepath . $fileRepository . $fileName, $absolutepath. $downloadDirectory . $fileName);
$checkLink = ($absolutepath . $downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
This original post, is a duplicate (though I didn't see it until now)
Create a valid symlink for PHP file
(Most of the answers given for that question were wrong however--but the original poster figured it out, and it worked for me too)

mkdir function, doesn't appear to be working

I have created a mkdir function in my php webpage but it doesn't appear to be working.
Here it is:
mkdir("Game/" . $user . "/" . $name . ".actibuild", 0777, true);
user and name are defined above. Here's the snippet of code:
if (isset($_POST['name'])){
if (isset($_POST['desc'])){
$name = mysql_real_escape_string($_POST['name']);
$desc = mysql_real_escape_string($_POST['desc']);
$user = $check_user['Username'];
mkdir("Game/" . $user . "/" . $name . ".actibuild", 0777, true);
mysql_query("INSERT INTO `games`(`creator`, `name`, `desc`) VALUES ('$user', '$name', '$desc')");
header('Location: Games.php');
}
}
It is correctly running those queries into the database, but it isn't creating those directories.
Can you help?
check the current directory with:
echo __FILE__;
or
echo getcwd();
and build your path relative to this reference.
or
you can use chdir("/") to set the root directory as the current directory, then try to create your path.
Do you know where PHP executes? You have a relative system path (starting with Game). Chances are, your directory is getting created (if permissions allow), but in a location relative to the working directory, which is not necessarily the same place where your PHP script lives.
You using relative paths, it may be not the place you think directories are created but current directory/web-root/etc.
Try:
$path = "Game/" . $user . "/" . $name . ".actibuild";
is_writable('.') || die(realpath('.') . ' is not writable');
mkdir($path, 0777, true) || die(realpath($path).' directory not created');
print_r(realpath($path));

php - Issue with move_uploaded_file function

I am facing issue with the move_uploaded_file() php function below is my script.
Its saying permission denied . The directory is not writable . But I checked the permissions , its read-write-execute. Not Sure what's the issue , How do I make sure the permission is R-W-X. ?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$target = "BharatTest/";
$photoName = basename( $_FILES['image']['name']);
$target = $target . basename( $_FILES['image']['name']) ;
ini_set('display_errors', 1);
echo '<pre>Debug: tmp file:', htmlspecialchars($_FILES['image']['tmp_name']), "</pre>\n";
echo '<pre>Debug: target directory: ', htmlspecialchars("BharatTest/"), "</pre>\n";
echo '<pre>Debug: real target: ', htmlspecialchars(realpath("BharatTest/")), "</pre>\n";
echo '<pre>Debug: source readable: ', is_readable($_FILES['image']['tmp_name']), "
</pre>\n";
echo '<pre>Debug: target is_dir: ', is_dir("BharatTest/") ? 'yes':'no', "</pre>\n";
echo '<pre>Debug: target writable: ', is_writeable("BharatTest/") ? 'yes':'no', "
</pre>\n";
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
echo "YES";
}
else
{
echo "NO";
}
?>
You need to ensure the webserver user has write permissions. Depending on the setup this often requires 775 or even 777 permissions on the folder.
Just because the directory is writable to you (when you log in), does not mean that it is writable to PHP / Apache / whatever web server you have. Depending on your server configuration, PHP likely runs with an entirely different set of permission. You can either lookup the permissions for your web server or set the directory to 777 and then backoff from there to determine the correct permissions for the directory.

How do I set relative paths in PHP?

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>

Categories