How can I move a file to another folder using php? - php

I have an upload form where users can upload images that are currently being uploaded to a folder I made called 'temp' and their locations are saved in an array called $_SESSION['uploaded_photos']. Once the user pushes the 'Next Page' button, I want it to move the files to a new folder that is dynamically created right before that.
if(isset($_POST['next_page'])) {
if (!is_dir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id'])) {
mkdir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id']);
}
foreach($_SESSION['uploaded_photos'] as $key => $value) {
$target_path = '../images/uploads/listers/'.$_SESSION['loggedin_lister_id'].'/';
$target_path = $target_path . basename($value);
if(move_uploaded_file($value, $target_path)) {
echo "The file ". basename($value). " has been uploaded<br />";
} else{
echo "There was an error uploading the file, please try again!";
}
} //end foreach
} //end if isset next_page
An example for a $value that is being used is:
../images/uploads/temp/IMG_0002.jpg
And an example of a $target_path that is being used is:
../images/uploads/listers/186/IMG_0002.jpg
I can see the file sitting in the temp folder, both of those paths look good to me and I checked to make sure that the mkdir function actually created the folder which it did well.
How can I move a file to another folder using php?

As I read your scenario, it looks like you've handled the upload and moved the files to your 'temp' folder, and now you want to move the file when they perfom a new action (clicking on the Next button).
As far as PHP is concerned - the files in your 'temp' are not uploaded files anymore, so you can no longer use move_uploaded_file.
All you need to do is use rename:
if(isset($_POST['next_page'])) {
if (!is_dir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id'])) {
mkdir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id']);
}
foreach($_SESSION['uploaded_photos'] as $key => $value) {
$target_path = '../images/uploads/listers/'.$_SESSION['loggedin_lister_id'].'/';
$target_path = $target_path . basename($value);
if(rename($value, $target_path)) {
echo "The file ". basename($value). " has been uploaded<br />";
} else{
echo "There was an error uploading the file, please try again!";
}
} //end foreach
} //end if isset next_page

Related

uploading binary file to server

I'm converting an image to a binary file in IOS, which works just fine. This will be handled by my php script which is suppose to upload this image to my ubuntu server. The problem is i keep getting file=unsuccessful. i've tried different directory paths, but cant seem to solve this issue.
This $directory will return this: /var/www/User/core/ios/
<?
if(!empty($_POST))
{
$message = $_POST['message'];
$directory = $_SERVER['DOCUMENT_ROOT'] . '/User/core/ios/';
$file = basename($_FILES['userfle']['upload']);
$uploadfile = $directory . $file;
var_dump($_FILES);
$randomPhotoID = md5(rand() * time());
echo 'file='.$file;
echo $file;
if (move_uploaded_file($_FILES['userfle']['tmp_name'], $uploadfile)) {
echo 'successful';
}
else
{
echo 'unsuccessful';
}
}
else
{
echo('Empty post data');
}
?>
Check the error file of your php(you can make sure if you enabled the error log in php.ini),
if you don't have the permission or for some other reasons it can't move the file ,there will be a record in that file.
Some time you can try the command setenforce 0 if you confirm you(I means the user of apache) have the permission to move the file but it not work.
By the way if the file you want to move is not upload by post, there is no error log and the move function will return false.

deleting image from a file in php

I am trying to delete a file from folder in php here is my model function
function deleteFiles()
{
$file = "http://localhost/copycopy/img/uploaded/long.jpeg";
if(is_file($file))
{
#unlink($file); // delete file
echo $file.'file deleted';
}
else
{
echo "no file";
}
}
but I always see "no file" and file is never deleted, file is in folder,because the url in $file actually displays the file in browser
help me
instead of using web url
$file = "http://localhost/copycopy/img/uploaded/long.jpeg";
use local path to file:
$file = $pathToYourWebSite . "/copycopy/img/uploaded/long.jpeg";
be sure to set $pathToYourWebSite to real location of your website;

Upload image to existing folder PHP

<?php
include('includes/db.php');
$drinks_cat = $_POST['drinks_cat'];
$drinks_name = $_POST['drinks_name'];
$drinks_shot = $_POST['drinks_shot'];
$drinks_bottle = $_POST['drinks_bottle'];
$drinks_availability = 'AVAILABLE';
$msg = "ERROR: ";
$itemimageload="true";
$itemimage_size=$_FILES['image']['size'];
$iname = $_FILES['image']['name'];
if ($_FILES['image']['size']>250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$itemimageload="false";}
if (!($_FILES['image']['type'] =="image/jpeg" OR $_FILES['image']['type'] =="image/gif" OR $_FILES['image']['type'] =="image/png"))
{$msg=$msg."Your uploaded file must be of JPG , PNG or GIF. Other file types are not allowed<BR>";
$itemimageload="false";}
$file_name=$_FILES['image']['name'];
$add="images"; // the path with the file name where the file will be stored
if($itemimageload=="true")
{
if (file_exists($add) && is_writable($add))
{
if(move_uploaded_file ($_FILES['image']['tmp_name'], $add."/".$_FILES['image']['name']))
{
echo "Image successfully updated!";
}
else
{
echo "Failed to upload file Contact Site admin to fix the problem";
}
}
else
{
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
echo $msg;
}
$dir = $add."/".$iname;
echo "<BR>";
// Connects to your Database
mysql_query("INSERT INTO `product_drinks`(`drinks_id`, `drinks_cat`, `drinks_name`, `drinks_shot`, `drinks_bottle`, `drinks_image`, `drinks_availability`) VALUES (NULL,'".$drinks_cat."', '".$drinks_name."','".$drinks_shot."','".$drinks_bottle."','".$dir."','".$drinks_availability."')") or die("insert error");
Print "Your table has been populated";
?>
The code I'm working on works but i have to create a new "image" folder for my admin folder. Is there any way that I could upload the file outside the admin folder and move it to to the original "image" folder". I know it's quite confusing but my directory looks like this.
clubmaru
-admin
-images
-css
-images
-js
You may be looking for PHP's rename function. http://php.net/manual/en/function.rename.php
Set the oldname parameter to the file (with its path) and the newname parameter to where you want it to be (along with the new path, obviously)
Just ensure the "image folder" you want to move the file to has the correct permissions set ensure it's writable. You also may want to consider changing the parameter in your move_uploaded_file to put the file where you want it in the first place!
Yes there is a way, you need to change the path. Right now you have the path as images/$name which means that it will put the file in the images directory found in the local directory to the script that is running.
Using directory layout:
clubmaru
->admin
->script.php (the upload file)
->images
->css
->images
->js
You make the path relative (or find another alternative)
$add="../css/images";
This means, go up a directory, go into css then into images.

Uploading A file via a form

I have written a form which has 3 text inputs and one file input.
This form posts to a PHP script, which saves the file, as well as performing some other business logic. The program worked well in my localhost, and even on my server.
The program is now embedded in a Facebook application, where it still works- but the uploaded files were not saving, initally; So I changed the uploads directory permissions to 777 (a broad stroke, I know). Now the uploaded files are being saved as a string of numbers "13474022561" with no extension.
Can anyone tell me why? Or how to fix this?
snippet of source code below:
if($_FILES['resume']['type']!='')
{
$target_path = "resumes/";
$target_path = $target_path .time().basename( $_FILES['resume']['name']!="");
if($_FILES['resume']['type']=="application/vnd.openxmlformats-officedocument.wordprocessingml.document" || $_FILES['resume']['type']=="application/pdf")
{
if(move_uploaded_file($_FILES['resume']['tmp_name'], $target_path))
{
echo "success";
}
else
echo "failure";
}
else
{
echo "<center>Resume must be MS DOC or PDF <br/>";
exit;
}
}
This line of code:
$target_path = $target_path .time().basename( $_FILES['resume']['name']!="");
Should be:
$target_path = $target_path . time() . basename( $_FILES['resume']['name']);
Your current code is evaluated like this:
$target_path = 'resumes/' . time() . basename(true);
Which is probably not what you want.

Running php in JavaScript

I am making an application on my server, where the user uploads an image through some HTML combined with javascript.
The user finds an image on the computer through
<form action="uploadimage.php" method="post"
enctype="multipart/form-data">
<label for="file">Filnavn:</label>
<input type="file" name="file" id="file" value="100000" />
Then the point behind the javascript, is to validate on the users image
if(picture_headline.value == "" || picture_uploaded.value == "" || !ischecked)
{
// Don't execute, stay on same site
}
else
{
// execute php and upload image
}
the php is an upload image php script
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I must say I am a bit confused here, since I have only been working with html, php and javascript for a few days now.
Am I totally off or what?
I found some "simple" examples online, which I put on my server through cuteFTP, but everytime i press upload, the website just sends me to the .php file and says the site doesn't exist.
Like Boann points out you're trying to access a non-existent file in your PHP code ("uploaded" and "uploadedfile" rather than "file" (which is what you named the field in your HTML form)).
But regarding "running PHP from JavaScript": You don't have to. The JavaScript should only return false if the form is invalid. If it's valid you don't need to do anything and the form will submit, in turn running your PHP script:
form.onsubmit = function () {
if (!formIsValid()) {
return false;
}
};
If the form is invalid it won't submit (the return false bit (you could use event.preventDefault() instead)), if it is valid nothing will happen and the form will do what it does (ie submit the data to the server).
Each array key in $_FILES corresponds with the name attribute of a file field in the form, so to match your form it should be 'file' rather than 'uploaded' or 'uploadedfile':
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['file']['name'] ) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}

Categories