move_uploaded_file() does not work - php

I run my test php project on local computer using XAMPP. I have a form where user can browse image from their computer and upload to my database.
I use move_uploaded_file() function to move image to desired folder. The script runs without error but no image was moved to desired folder. It does not echo error message if move_uploaded_file() failed. Here is my code:
$upload_dir= 'uploads';
for($i=0; $i < count($_FILES['file']['tmp_name']);$i++){
if(!empty($_FILES['file']['name'][$i])){
$temp = explode(".", $_FILES["file"]["name"][$i]);
$extension = end($temp);
$allowedExts = array("gif", "jpeg", "jpg", "png");
if(!in_array($extension, $allowedExts)){
echo "Only image ending with .jpg, .jpeg, .gif, .png is allowed";
}
// copy the file to the specified dir
else{
$name[$i] = sha1(microtime()) . "." . $extension;
if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$name[$i])){
$image_path_array[$i]=$upload_dir.'/'.$name[$i];
}
else{
/*** an error message ***/
echo "error with move_uploaded_file";
}
}
}
}

Neither of your echo statements is likely to work that way. It should be
echo "error with move_uploaded_file";
No "=" sign.
Also, are you sure your web server has permission to write into the upload directory?

Try this:
1) I think you should give full directory path to your $upload_dir variable something like this:
$upload_dir=$_SERVER['DOCUMENT_ROOT']."/uploads";
2)Yes the echo that you have given for display "error with move_uploaded_file" need to correct other wise it will give syntax error:
//an error message
echo "error with move_uploaded_file";
I hope this fix your problem :)

You should have separate move_uploaded_files() function for image on server and image on client machine.
Image from client machine will be uploaded to your server temp folder
Image on online server will be fetched as url to that image

Related

How to compress image size before uploading using php

I already searched lots of stuff, some of them are from stackoverflow. But none of them helped me. What I want to do is reduce the image file size, and after reducing the image will now be uploaded. Here's my current code:
<?php
include 'cloud_functions.php';
// GET THE USER'S ID
$userid = _clean($con, $_POST['userid']);
if(!is_dir("uploads/user/".$userid."/")){
mkdir("uploads/user/".$userid."/", 0755);
}
$temp = explode(".", _clean($con,$_FILES["file"]["name"]));
$targetPath = "uploads/user/".$userid."/";
// RENAME THE IMAGE USING ROUND();
$newFN = round(microtime(true)) . '.' . end($temp);
$targetPath = $targetPath . $newFN;
// GET THE FILE EXTENSION
$type = pathinfo(_clean($con, $_POST['filename']), PATHINFO_EXTENSION);
$all_types = array('jpg', 'png', 'jpeg');
$type = strtolower($type);
if(in_array($type, $all_types)){
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)){
// image uploaded w/o compressing size
echo "1/".$newFN;
}else{
echo $targetPath;
echo "There was an error uploading the file, please try again!";
}
}else{
echo "Please upload a valid image.";
}
?>
In that way I can upload image successfully without compressing its size. Please tell me how to do compress image size before upload. Thanks.
You need to compress image on client side. All the code you posted here is of server side. This code will run after uploading the image to the server.
There are lot of client side libraries for this purpose.
This link will further help. You can choose use any library of your choice.
https://github.com/brunobar79/J-I-C - js library
I think better way - compress image on server after uploading, that to decrease using user memory. It's special important for slow smartphones.

PHP move_uploaded_file doesn't work occasionally?

I now there are lots of same questions here, but I didn't find my answer.
I want to upload an image using move_uploaded_file() function in PHP. Here is my logic?
//check if file uploaded
if (!isset($_POST) || !isset($_FILES)) {
return back();
}
// allowed extensions
$extensions = ['jpg', 'jpeg', 'gif', 'png'];
$fileName = pathinfo($_FILES['profile-image']['name'], PATHINFO_FILENAME);
// save file extension into a variable for later use
$parts = explode('.',$_FILES['profile-image']['name']);
$extension = strtolower(end($parts));
$fileSize = $_FILES['profile-image']['size'];
// check the extension
if (!in_array($extension, $extensions)) {
return back()->withErrors(['File Extension is not valid']);
}
// check if file size is less than 2MB
if ($fileSize >= 2e+6) {
return back()->withErrors(['File Size is too large.']);
}
//check if there is other errors
if ($_FILES['profile-image']['error']) {
return back()->withErrors(['You have anonymus error']);
}
// generate a unique file name
$profile_image = Hash::make($fileName) . '-' . time() . '.' . $extension;
// make a directory if there isn't one
if (!is_dir('public/img')) {
mkdir('public/img');
}
// if current user has an image then delete it
$user = App::get('database')->find('users', compact('id'));
if ($user->profile_image) {
unlink('public/img/' . $user->profile_image);
}
// move image into directory and final check for errors
if( ! move_uploaded_file($_FILES['profile-image']['tmp_name'], 'public/img/' . $profile_image) ) {
return back()->withErrors(['Your file doesn\'t uploaded']);
}
// Insert Uploaded Image into DB.
App::get('database')->update('users', compact('id'), compact('profile_image'));
return redirect('dashboard')->withMessage('Thank for uploading the file.');
I try this code, everything works properly but just sometimes. I don't know why sometimes my uploaded file doesn't move to the directory and sometimes it does. I tried for the same image, sometimes it uploaded and sometimes it failed. This is interesting, because when I upload an image and it fails, can't catch any errors at all.
Did you check max_file_uploads and post_max_size in your php.ini file ?
Maybe the file is bigger than the maximum size allowed.
Regards.
OK, I find the problem. When I hash the image name and save it to DB, sometimes it includes / inside file name, then when I use the file name in image src attribute, it considers the part before the / as another directory.
It might have trouble with,
Your Destination Directory have some writing permission issue.
Try this for manage file permission,
if (!is_writable($url)) {
try {
chmod($url, 0644);
} catch (Exception $e) {
die($e->getMessage() . ' | File : ' . $url . ' | Needs write permission [0644] to process !');
}
}
All the Best !

How to render an image on a php page by dynamically taking the path returned on the same page from MySQL database

So i want my page to show the image whose path I am getting from the mysql database and displaying on the same screen. This is my code, I have tried everything, please let me know where I'm going wrong.
while ($row = mysqli_fetch_array($return_data)) {
echo "ID:".$row['demo_id']."<br>";
echo "Name: ".$row['demo_name']."<br>";
echo "Version: ".$row['demo_version']."<br>";
echo "Details: ".$row['demo_details']."<br>";
echo "File Link: ".$row['file']."<br>";
$new = $row['file'];
echo '<img src = \"$new\"/>';
}
mysqli_free_result($return_data);
echo "Data retrieved successfully!"."<br>";
?>
<img src = "<?php echo $new?>">
echo "File Link: " returns me the whole path of the uploaded file.
How do I render the image at that path in the same page?
neither of the image tags are working. Thanks in advance!
edit
File Link: C:/Apache24/htdocs/demo_webpages_project/neweruploads/footer.jpg
this is the path I get as an output.
Basically this is the folder where I have uploaded the image from another php file
<?php
//this module is used to temporarily store the uploaded file to the server
$target_dir = "random/"; //we randomly assign a value to the upload target directory
$target_file = $target_dir . basename($_FILES["image_file"]["name"]); /*here ["name"] is the original name of the file before it was updated
target file is assigned this name by appending it to the $targer_dir
now target_file is the uploaded file name along with the path*/
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);/*this returns various kind of info about the path for eg Directory, Basename
in our case it returns extension of the file*/
//this sub module is to check whether the file is really an image file
if(isset($_POST["submit"])) { //isset is used to confirm whether the value has actually being submitted
$check = getimagesize($_FILES["image_file"]["tmp_name"]);/*here ["tmp_name"] is the location of temporary file on server
getimagesize confirms image format by returning dimensions etc*/
if($check !== false) {
echo "A file is of an image format<br>";
}
else {
echo "The file is not an image!<br>";
}
}
//Test module to upload files to a destination directory and check whether they have been uploaded or not
if (is_uploaded_file($_FILES['image_file']['tmp_name']) && $_FILES['image_file']['error']==0) { /*code to check two things: 1. whether the file exists in the temp memory 2. whether the file has any error*/
$path = 'C:\Apache24\htdocs\demo_webpages_project\neweruploads\\' . $_FILES['image_file']['name']; /*this sets the destination directory(along with expected file name)*/
if (!file_exists($path)) { //if the file does not exists at that path
if (move_uploaded_file($_FILES['image_file']['tmp_name'], $path)) { //use the php file move function to move it
echo "The file was uploaded successfully."; //success
}
else {
echo "The file was not uploaded successfully."; //failure
}
}
else {
echo "File already exists. Please upload another file."; //detects existence of file with exact same name
}
}
else {
echo "The file was not uploaded successfully."; //if any problem with original uploading
echo "(Error Code:" . $_FILES['image_file']['error'] . ")";
}
?>
Does this help?
edit 2
http://localhost:8080/demo_webpages_project/download.php?project_name=footer&version=&submit=Search
this is my local directory path.
the solution you provided is allowing me to read images which are in the demo_webpages_project folder pointing directly there), not to neweruploads folder
If your uploaded files are stored in the neweruploads subdirectory, then replace this code:
$new = $row['file'];
echo '<img src = \"$new\"/>';
By this one :
$new = basename( $row['file'] ); // GET FILE NAME ONLY, GET RID OF PATH.
echo '<img src = \"neweruploads/$new\"/>'; // FILENAME WITH UPLOAD PATH.
▲

php move_uploaded_file() image permission issue

my code is successfully working for upload images. but problem is it fails to display uploaded images. i checked image path output is correct in html source view but image till not displaying. i think its a file permission issue. how can i upload these images with read write full permission so images can display properly.
if(isset($_POST["submit_img"])) {
$target_dir = "../assets/img/temp_img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$randstr = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 3);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_dir.$randstr))
{
$q =mysqli_query($conn,"INSERT INTO temp_img (product_img_url) VALUES ('$randstr')");
if ($q>0) {
echo "<br>The file has been uploaded.";
}
} else {echo "<br>Error uploading your file.";}
}
//show all uploaded images
$q2 = mysqli_query($conn,"SELECT product_img_url FROM temp_img");
while ($row = mysqli_fetch_array($q2)) {
$product_img_url = $row['product_img_url'];
$img_format = ".jpg";
$broken_url = "assets/img/temp_img/";
echo '<img src="'.$main_url.$broken_url.$product_img_url.$img_format.'" class="img-rounded" alt="Cinque Terre" width="304" height="236">';
}
image missing picture
I think the following link will help you change permissions of your file.
http://php.net/manual/en/function.chmod.php
Note:
1.check whether the uploaded file is in specified folder.
2.try setting the path without "../" in the variable targetdir

what's wrong with the upload code?

<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$HTTP_POST_FILES['ufile']['name'];
if($ufile !=none) {
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)) {
echo "Successful<BR/>";
//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$HTTP_POST_FILES['ufile']['name']."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
echo "<img src="$path" width="150" height="150">";
} else {
echo "Error";
}
}
?>
it is an toturial form here http://tutorialblog.info/2010/08/06/php-upload-single-file.html
when i tried in my local environment. it displays an error? what's wrong with the code? thank you.
first, i think this is wrong. if($ufile !=none) it should be if($_POST['ufile' !=none)
am i right?
I agree with Stephen, this is not a good example, you also need to validate your upload. you are not going to allow anyone to upload anything.
but if you want just find the issues: well HTTP_POST_FILES is no longer accepted by PHP newer versions. should be $_FILES
$ufile !=none can be if ($_FILES['ufile']['tmp_name'])
copy($HTTP_POST_FILES['ufile']['tmp_name'], $path) better be move_uploaded_file($_FILES['ufile']['tmp_name'], $path)
Your html form enctype should be enctype="multipart/form-data"
the $path path should have the right permission

Categories