move_uploaded_file error php won't upload to filepath - php

I'm writing a script to upload user input and images to a place in my file system (currently on a different server).
I get an error
move_uploaded_file(images//test.pdf): failed to open stream: Permission denied in ..
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
$title = $_POST["title"];
$authors = $_POST["authors"];
$description = $_POST["description"];
$price = $_POST["price"];
$uploads_dir = "images/";
$tmp_name = $_FILES["image"]["tmp_name"];
$name = $_FILES["image"]["name"];
$tmp_name2 = $_FILES["content"]["tmp_name"];
$name2 = $_FILES["content"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
move_uploaded_file($tmp_name2, "$uploads_dir/$name2");
$file_path=$uploads_dir. basename( $_FILES["image"]["name"]);
$file_path2=$uploads_dir. basename( $_FILES["content"]["name"]);
$stmt = $dbh->prepare("INSERT INTO books (title,authors,description,price,image, content)
VALUES ('$title', '$authors', '$description', '$price',$file_path', '$file_path2')") ;
$stmt->execute();
I've looked at similar questions on here but the answers haven't concluded my problem. I have tried the $uploads_dir variable as images/ and as its complete path /project/folder/user/images/ both give the same error.
Note: this php script is in the parent folder of images/.

Your problem is clearly related to permissions. The user under which the php is running doesn't have permissions to write in this images folder. Change the owner of the folder or change the permissions.

It looks like a File Permission error. You can check whether a directory is writable or not by,
$directoryName = "specify your directory name here";
if(is_writable($directoryName){
echo "Directory is writable"; // Returns TRUE if it's writable.
}
else{
}
More on here.

Related

PHP move_uploaded_file not uploading

I'm trying to upload an image on blog but it just doesn't do it. No error mesgs, just doesn't upload it. Checked permissions on the folder and they work when i place the image in the images folder but not when adding a post.
Below is the code im using.
Any help is greatly appreciated.
$post_image = $_FILES['image']['name'];
$post_image_temp = $_FILES['image']['tmp_name'];
$post_content = mysqli_real_escape_string($connection, $_POST['post_content']);
$post_tags = mysqli_real_escape_string($connection, $_POST['post_tags']);
$post_status = mysqli_real_escape_string($connection, $_POST['post_status']);
// $post_comment_count = 4; //THIS NEEDS TO BE DYNAMIC
move_uploaded_file($post_image_temp,"../images/".$post_image) ;
// if(!move_uploaded_file($post_image_temp,"../images/".$post_image)){
// echo 'Moved successfully:';
// }else{
// print_r(error_get_last());
// }
$query = "INSERT INTO posts(post_category_id, post_title, post_author, post_date, post_image, post_content, post_tags, post_status)";
$query .= "VALUES ({$post_category_id},'{$post_title}','{$post_author}',now(),'{$post_image}','{$post_content}','{$post_tags}','{$post_status}') ";
$create_post_query = mysqli_query($connection, $query);
confirm($create_post_query);
}
Replace
move_uploaded_file($post_image_temp,"../images/".$post_image) ;
with
move_uploaded_file(
$post_image_temp,
__DIR__ . "/../images/" . $post_image
);
Change these
move_uploaded_file("$post_image_temp,","../images/" . $post_image) ;
if(!move_uploaded_file($post_image_temp,"../images/".$post_image)){
to these
move_uploaded_file("$post_image_temp,", "images/" . $post_image) ;
if(move_uploaded_file($post_image_temp, "images/" . $post_image)){
Tested and works fine now!
you can use below code for acessing images folder
move_uploaded_file($post_image_temp,dirname(__FILE__)."/images/".$post_image) ;
but you should make sure images folder exists in same folder as the php file. If images folder is in an higher directory than your php file then use
dirname(__FILE__)."../images/"

Having an issue with the fopen() php function

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

move_uploaded_file warning

I am encountering the following error message saying:
Warning: move_uploaded_file(uploads/computer-science1.jpg): failed to open stream: No such file or directory....
while trying to move a file to a directory. above code provided.
I have also enabled the uploaded file in FileZilla to be writable and executable, is there another way of solving particular problem?
Thank you.
<?php
$upload_url = "uploads/" . $_FILES["myfile"]["name"];
$filename = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_url);
$conn = mysqli_connect("yourhost", "username", "password", "databasename");
$sql = "INSERT INTO images (image_url, image_title) VALUES ('$upload_url','$filename') ";
$imageresults = mysqli_query( $conn,$sql );
$sql = "SELECT image_url, image_title from images";
if ($imageresults = mysqli_query( $conn, $sql )) {
while ( $currentimage = mysqli_fetch_assoc($imageresults ) ) {
echo "<div><img src= '" . $currentimage['image_url'] . "'
width='200' height='200'/><br/>" .
$currentimage['image_title'] . "</div>";
}
}
} catch( Exception $e ) {
echo $e->getMessage();
}
Your PHP script must be in a directory which contains a sub-directory, uploads/, which is writeable.
It seems as if you are attempting to move the file from its temporary location to a folder (uploads/) that either doesn't exist or that the script is unable to write to.
When you've got this message :
Warning: move_uploaded_file(uploads/computer-science1.jpg): failed to
open stream: No such file or directory....
It means that the location of the file or the location of the destination directory is not good. Maybe you can check your link path of "uploads/computer-science1.jpg"
You can use a test to check it :
if(move_uploaded_file($yourFile, $yourlocation)) {
echo 'Good ! ';
} else {
exit('Error !');
}

Copy file into new directory (PHP)

I asked a similar question previously, but didn't know how to quite ask before. Below I created a new directory based on the username I grabbed from a signup form. I just need the inclusion of the template file copied over to the new directory that was just made. The outcome I'm getting is an inclusion of the file in the directory that's up one level. The new directory is created with the username but doesn't contain the template file in its directory. I spent hours on this so I wouldn't have to bother you guys again. What am I doing wrong?
$folder = DIRECTORY_SEPARATOR; // adds the forward slash
$name = $user->username; // included from a login script I purchased
$thisdir = "../associate"; // desired directory
$folderPath = $thisdir . $folder . $name;
$file = copy('../associate/joshua/career.php', $folderPath.'.php'); // copy this file into new directory
if(!file_exists($folderPath)){
mkdir($folderPath);
chmod($folderPath,0777);
}
file_put_contents(realpath($folderPath) .'/'. $folderPath, $file);
});
If I understand you well, you want to copy career.php template from /associates/ folder to /associates/username/ folder
$rootfolder = $_SERVER['DOCUMENT_ROOT'];
$name = $user->username;
$thisdir = "/associate/";
$folderPath = $rootfolder.$thisdir.$name."/"; // desired directory
if(!is_dir($folderPath)){
mkdir($folderPath, 0777, true);
}
$currentfile = $rootfolder.$thisdir.'joshua/career.php';
$destination = $folderPath.'career.php';
copy($currentfile, $destination); // copy this file into new directory

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

Categories