Sorry I wasn't able to be a lot more descriptive in my question title, I'm struggling to word the issue correctly. I have a script add-new-post.php
that adds a new blog post to the database. I'm struggling with the file upload process as the upload file is a few levels away from the script that's doing the uploading.
File locations:
public_html/content/uploads/imgs
public_html/content/themes/admin-cm/post/add-new-post.php
So, the script is attempting to upload files to the first directory. Below is the relevant snippet concerning the file upload, at the moment I'm just getting it to echo some info to the page so I can see what's happening:
if ( !empty( $_FILES[ "featured_image" ][ "name" ] ) ) {
$target_dir = '/content/uploads/imgs/';
$target_file = dirname(__FILES__, 4 ) . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
$upload_ok = 1;
$image_file_type = strtolower( pathinfo( $target_file, PATHINFO_EXTENSION ) );
$check = getimagesize( $_FILES[ "featured_image" ][ "tmp_name" ] );
if ( $check !== false ) {
echo "File is an image - " . $check[ "mime" ] . ".";
echo "<br>" . $target_file;
$upload_ok = 1;
} else {
$errors[] = "The uploaded file is not an image.";
$upload_ok = 0;
}
if ( file_exists( $target_file ) ) {
echo "Sorry, this file already exists.";
$upload_ok = 0;
} else {
echo "<br>This image doesn't exist already.";
}
if ( $_FILES[ "featured_image" ][ "size" ] > 500000 ) {
echo "Sorry, your file is too large.";
$upload_ok = 0;
}
if ( $upload_ok ) {
if ( move_uploaded_file( $_FILES[ "featured_image" ][ "name" ], $target_file ) ) {
echo "<br>Successfully uploaded the image.";
} else {
echo "<br>Couldn't upload the image.";
}
}
}
I'm guessing my issue is the directory, I've tried a few different ways of inputting the target directory and none seem to work (such as initially entering the $target_file
variable as a string ie. "../../../../content/uploads/imgs
). I am testing this out by attempting to upload a file that DOES currently exist in the uploads directory and the following is what is printed to the page:
File is an image - image/jpeg.
./content/uploads/imgs/post-img-8.jpg
This image doesn't exist already.
Couldn't upload the image.
To me the target directory looks correct.. I've also tried substr()
to lose the dot and tried it to lose the ./
. Any ideas what I'm doing wrong?
SOLVED (thanks to Martin in the comments):
I replaced the following:
$target_dir = '/content/uploads/imgs/';
$target_file = dirname(__FILES__, 4 ) . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );
with:
$target_dir ="content/uploads/imgs/";
$target_file = $_SERVER[ "DOCUMENT_ROOT" ] . $target_dir . basename( $_FILES[ "featured_image" ][ "name" ] );