PHP move_uploaded_file not uploading - php

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/"

Related

unlink is showing error that is not present

I am trying to delete image from server but unlink is showing error that is not a error at all. My code is given below:
private function delete_image($ad_id){
$this->load->helper('file');
$sql = "SELECT image1,image2,image3 from ads where AdId = ?";
$query = $this->db->query($sql,array($ad_id));
//for fetching result
$result = $query->result_array();
//to make a array of all images
$img = [$result[0]['image1'],$result[0]['image2'],$result[0]['image3']];
$i = 0;
while ($img[$i]!= "edubuylogo.png" && $i<3){
unlink('./uploads/'.$img[$i]);
$i++;
}
}
and the link to image is http://localhost/edubuy/uploads/IMG_20180120_210433.jpg
And image is perfectly loading.
The error is Message:
unlink(/uploads/IMG_20180120_210433.jpg): No such file or directory
It seems that your computer is confused, and you should specify an absolute path. In CodeIgniter you can use the FCPATH constant, so do like this:
unlink( FCPATH . 'uploads/' . $img[$i] );
That assumes your index.php file is inside edubuy. If it's not then:
unlink( FCPATH . 'edubuy/uploads/' . $img[$i] );

move_uploaded_file() function does not upload to my folder

I'm making a ecommerce website with a CMS where I can edit, add products etc, when I add a product and choose and image from my computer it does not upload to my folder I made for images "uploads".
Does anyone know the solution to this, it's probably in my code but I can't seem to figure it out.
If I manually add the image to the folder uploads and choose the image when I add the product the image shows.
Here is my code:
function add_product() {
if(isset($_POST['publish'])) {
$product_title = escape_string($_POST['product_title']);
$product_category_id = escape_string($_POST['product_category_id']);
$product_price = escape_string($_POST['product_price']);
$product_description = escape_string($_POST['product_description']);
$short_desc = escape_string($_POST['short_desc']);
$product_quantity = escape_string($_POST['product_quantity']);
$product_image = escape_string($_FILES['file']['name']);
$image_temp_location = escape_string($_FILES['file']['tmp_name']);
move_uploaded_file($image_temp_location, UPLOAD_DIRECTORY . DS . $product_image);
$query = query("INSERT INTO products(product_title, product_category_id, product_price, product_description, short_desc, product_quantity, product_image) VALUES('{$product_title}', '{$product_category_id}', '{$product_price}', '{$product_description}', '{$short_desc}', '{$product_quantity}', '{$product_image}')");
$last_id = last_id();
confirm($query);
set_message("New Product with id {$last_id} was Added");
redirect("index.php?products");
}
}
The UPLOAD_DIRECTORY is a path that I have configured in a file named config.php and it looks like this:
defined("UPLOAD_DIRECTORY") ? null : define("UPLOAD_DIRECTORY", __DIR__ . DS . "uploads");

move_uploaded_file error php won't upload to filepath

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.

How can my upload file script save file path to the database, return an error message, and create a folder?

I'm making a script to upload files. I have some questions.
I'm using the dropzonejs library.
I need to save the uploaded file info into the database. I made a prepared statement but it's not working: nothing is stored in the table.
Table info: userID (int 11), image_name (varchar 50), image_path (varchar 60), up_time (varchar 60), up_ip (varchar 45).
Where can I see the MySQL errors? I already checked the .err file from appdata and there was nothing there.
How can I return an $error_msg from the upload page to the form page? I'll have to move the first check (file exists) from the upload page to the dropzone.js file but I'm not sure how to do this. Maybe there's already an option for this, but I searched and found nothing.
HTML:
<link rel="stylesheet" href="/css/dropzone.css"/>
<script type="text/JavaScript" src="/js/dropzone.js"></script>
<form action="/upload"
class="dropzone"
id="my-awesome-dropzone"></form>
<?php
if (isset($error_msg)) {
echo '<p class="error">' . $error_msg . '</p>';
}
?>
My upload.php script:
require_once('/includes/functions.php');
$image = basename($_FILES['file']['name']);
$image = str_replace(' ','|',$image);
$img_dir = $_SERVER['DOCUMENT_ROOT'] . '/images/user_uploads/' . $_SESSION['username'] . '/';
if (file_exists($img_dir . $image)) {
return $error_msg = $img_dir . $_FILES["file"]["name"] . " ya existe. ";
} elseif (move_uploaded_file($_FILES["file"]["tmp_name"],
$img_dir . $image)) {
$img_path = $img_dir . $image;
$up_time = get_current_time();
$up_ip = get_ip_address();
if ($insert_stmt = $mysqli->prepare("INSERT INTO user_uploads (userID, image_name, image_path, up_time, up_ip) VALUES (?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('issss', $_SESSION['user_id'], $_FILES["file"]["name"], $img_path, $up_time, $up_ip);
if (! $insert_stmt->execute()) {
return $error_msg = '¡Error al subir la imagen! (db_error)';
}
}
} else return $error_msg = '¡Error al subir la imagen!';
This works only if I use $_SERVER['DOCUMENT_ROOT'] as the image directory.
If the folder does not exist (each user will have their own folder for their uploads), how can I tell the script to automatically create it?
I'm using XAMPP in Windows, but once it's finished I'll upload it to Linux hosting, so maybe I'll have to change the paths or something. So what is the difference between these two operating systems?
Ok I got it :)
$tmp_name = $_FILES["file"]["tmp_name"];
$image = basename($_FILES['file']['name']);
$image = str_replace(' ', '|', $image);
$img_dir = $_SERVER['DOCUMENT_ROOT'] . '/images/user_uploads/' . $_SESSION['username'] . '/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/images/user_uploads/' . $_SESSION['username'])) {
mkdir($_SERVER['DOCUMENT_ROOT'] . '\\images\\user_uploads\\' . $_SESSION['username']);
}
move_uploaded_file($tmp_name, $img_dir . $image);
$img_path = $_SESSION['username'] . '/' . $image;
$up_time = get_current_time();
$up_ip = get_ip_address();
if ($stmt = $mysqli->prepare("INSERT INTO user_uploads (userID, image_name, image_path, up_time, up_ip) VALUES (?, ?, ?, ?, ?)")) {
$stmt->bind_param('issss', $_SESSION['user_id'], $image, $img_path, $up_time, $up_ip);
$stmt->execute();
}
Using this javascript I think it's only possible to return error messages from the javascript itself so creating functions or setting the messages will be ok:
dictInvalidFileType: "No puedes subir este tipo de archivos.",
dictResponseError: "Código de error {{statusCode}}.",
Hope it helps someone :)
Please provide your final query and its value
You upload code in inside one file, so you can not return value by including file, you need to wrap that code in function or class method.
Refer this: Create a folder if it doesn't already exist

Setting the directory to include subdirectories using html2text

Long time reader, first time poster. I know just enough about php to be dangerous and this is my first BIG project using it.
Some background:
I have over 1 million (yes, million) .html files that were generated from an old news gathering program. These .html files contain important archive information that needs to be searched on daily basis. I have yet to get to other servers which might very well have more so 2-3 million+ is not out of the question.
I am taking these .html files and transferring them into a mysql database. At least, so far, the code has worked wonderfully with several hundred test files. I'll attach the code at the end.
The problem starts when the .html files are archived, and it's a function of the box generating the archive which cannot be changed, is the files go into folders. They are broken down like this
archives>year>month>file.html
so an example is
archives>2002>05may>lots and lots of files.html
archives>2002>06june>lots and lots of files.html
archives>2002>07july>lots and lots of files.html
With help and research, I wrote code to strip the files of markup that includes html2text and simple_html_dom and put the information from each tag in the proper fields in my database, which works great. But ALL of the files need to be moved to the same directory for it to work. Again, over a million and possibly more for other severs takes a REALLY long time to move. I am using a batch file to robocopy the files now.
My question is this:
Can I use some sort of wildcard to define all of the subdirectories so I don't have to move all of the files and they can stat in their respective directories?
Top of my code:
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\name\\search\\files\\";
The subdirectories are under the files directory.
In my searches for an answer, I have seen "why would you want to do that?" or other questions asking about .exe files or .bat files in the directories and how it could be dangerous so don't do it. My question is just for these html files so there is nothing being called or running and no danger.
Here is my code for stripping the html into the database. Again, works great, but I would like to skip the step of having to move all of the files into one directory.
<?php
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\wdaf\\search\\files\\";
// Enter MySQL database variables here:
$db_hostname = "localhost";
$db_username = "root";
$db_password = "password";
$db_name = "dbname";
$db_tablename = "dbtablename";
/////////////////////////////////////////////////////////////////////////////////////
// Include these files to strip all characters that we don't want
include_once("simple_html_dom.php");
include_once("html2text.php");
//Connect to the database
mysql_connect($db_hostname, $db_username, $db_password) or trigger_error("Unable to connect to the database host: " . mysql_error());
mysql_select_db($db_name) or trigger_error("Unable to switch to the database: " . mysql_error());
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
// first check if $html->find exists
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
// Get our variables from the HTML: Starts with 0 as the title field so use alternate ids starting with 1 for the information
$slug = mysql_real_escape_string(convert_html_to_text($html->find('td', 8)));
$tape = mysql_real_escape_string(convert_html_to_text($html->find('td', 9)));
$format0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 10)));
$time0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 11)));
$writer = mysql_real_escape_string(convert_html_to_text($html->find('td', 12)));
$newscast = mysql_real_escape_string(convert_html_to_text($html->find('td', 13)));
$modified = mysql_real_escape_string(convert_html_to_text($html->find('td', 14)));
$by0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 15)));
$productionCues = mysql_real_escape_string(convert_html_to_text($html->find('td', 16)));
$script = mysql_real_escape_string(convert_html_to_text($html->find('td', 18)));
// Insert variables into a row in the MySQL table:
$sql = "INSERT INTO " . $db_tablename . " (`path`, `fullpath`, `filename`, `slug`, `tape`, `format0`, `time0`, `writer`, `newscast`, `modified`, `by0`, `productionCues`, `script`) VALUES ('" . $path . "', '" . $fullpath . "', '" . $filename . "', '" . $slug . "', '" . $tape . "', '" . $format0 . "', '" . $time0 . "', '" . $writer . "', '" . $newscast . "', '" . $modified . "', '" . $by0 . "', '" . $productionCues . "', '" . $script . "');";
$sql_return = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
}
}
}
?>
Thanks in advance,
Mike
Just wanted to update this post with a answer to my question that works quite well. With some help, we found that scandir used recursively to create an array would work.
I thought I'd post this so if anyone else was looking to do something similar, they would be able wouldn't have to look far! I know I like to see answers!
The code is from the second user-contributed note here with a few modifications: http://php.net/manual/en/function.scandir.php
so in my code above, I replaced
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
with
function import_dir($directory, $db_tablename) {
$cdir = scandir($directory);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($directory . DIRECTORY_SEPARATOR . $value))
{
// Item in this directory is sub-directory...
import_dir($directory . DIRECTORY_SEPARATOR . $value,$db_tablename);
}
else
// Item in this directory is a file...
{
$html = file_get_html($directory . DIRECTORY_SEPARATOR . $value);
and then for the filenames, replaced
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
with
//Get the filename of the file from which it will extract
$filename = mysql_real_escape_string($value);
//define the path of the files
$path = mysql_real_escape_string($directory . DIRECTORY_SEPARATOR);
//Combine the patha and filename
$fullpath = $path . $value;
Thanks to those who answered!
Mike
I'm not sure how long it would take before your PHP query times out, but there is an inbuilt function RecursiveDirectoryIterator which sounds like it might do the trick for you.

Categories