Hey i have a system were in uploading a file. I have a script I've found online and it seems to work well.
Here is the PHP code:
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000))
{
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname))
{
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
echo "It's done! The file has been saved as: ".$newname;
}
else
{
echo "Error: A problem occurred during file upload!";
}
}
else
{
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
}
else
{
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
}
else
{
echo "Error: No file uploaded";
}
No this works fine if i want to upload a jpg file. But i want to be able to put the file into another directory. because at the moment the upload page is for admin users, they are on a subdomain called admin.mysite.com but the location i want the file to go to is in the members section which is mysite.com/members/video/
Now there are a few bits of code that im not 100% with like "dirname(FILE)" what does this do? I guessed it would get the current locations, but i've changed the whole line where so it looks like this:
$newname = '../mysite.com/members/video/'.$filename;
and
$newname = 'http://www.mysite.com/members/video/'.$filename;
But nothing. Anyone know how i can change this code so i can copy the file to a new directory?
Thanks for the help.
Change $newname to whatever location you want!
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
dirname(_ FILE _) returns the current directory of the file, in this case, file_upload.php
So, in this script, the $newname will save the uploaded file to /upload/name_of_new_file_uploaded.ext.
You should try to use realpath() instead dirname. Like this:
$newname = realpath("../../members/video/") . $filename;
depending on you file structure, add/remove the dots.
PS: Remember to change folder permissions, so the php can write on a folder.
For security, you should
Put the file in a location that is not accessible by the general web. /home/uploadedfiles/
Change the name of the file. Store the name of that file in a database and don't let the end users see that actual name.
Related
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 !
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.
▲
Need to insert uploaded file into respected folder
Here i am creating folder based on unique id.
I am not able to insert file into the folder.
when file is uploaded both file and folder are stored separately.
if ($file_check_error == 0){
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
echo"inside 2"."<br>";
echo"Your File Successfully Uploaded";
}
$path_user = '/home/devestctrl/public_html/wp-content/plugins/est_collaboration/Files/'.$send_id;
if (!file_exists($path_user)) {
if (mkdir( $path_user,0766,false )) {
$path_move = $path_user."/".$path;
echo $path_user;
rename($path,$path_move);
echo "Success+++++++++++";
}
else{
echo $path;
echo "Failure+++++++++++";
}
}
}
$send id is unique id.
Please let me know where i have gone wrong?
You are messing up your logic. First you move your uploaded file
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
and only than you try to create new directory
if (mkdir($path_user,0766,false )) {
and only if current user never uploaded anything you rename file moving it to other dir
rename($path,$path_move);
Correct logic:
Format uploaded file path $path = $upload_directory.DIRECTORY_SEPARATOR.$send_id
Check if dir exists file_exists($path)
If not exists, create it mkdir($path, 0766, false)
Upload file move_uploaded_file($file['tmp_name'], $path)
E.g.:
$path = $upload_directory.DIRECTORY_SEPARATOR.$send_id;
if (!file_exists($path)) {
mkdir($path, 0766, false);
}
move_uploaded_file($file['tmp_name'], $path);
This is a script that Upload a file in all directory. But when i run it, its only upload One time and then fail to upload . whats wrong in this code ?
function read_directory($p_pathname)
{
$d = dir ($p_pathname);
$target = $p_pathname;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target.$_FILES['uploaded']['name']))
{
echo $target. "Done<br>";
}
else
{
echo $target."Sorry<br>";
}
while (($file = $d->read()) !== false)
{
if (($file != ".") and ($file != ".."))
{
$filetype = filetype ("{$d->path}/{$file}");
if ($filetype == "dir")
{
read_directory ("{$d->path}/{$file}");
}
else
{
// echo "\tFILE: {$d->path}/{$file}\n";
}
}
}
$d->close;
}
Use copy() instead of move_uploaded_file(). move_uploaded_file() deletes the source file when it's done, so you can't use it multiple times on the same file. copy() leaves the original file alone, so you can do it as many times as you want.
When the script exits, PHP automatically removes the temp file that was uploaded if it doesn't get moved by the script.
in the first time your moving the file... not copying ... so only next time that file not in the temp directory, so you can't move again..
I am trying to upload a file, and save the path to MySQL.
I want to make a custom path for each file, which will be based on a variable, however the actual file name of the file will stay the same.
I am submitting the file via POST. I believe I have to use $_FILE? The name of the form item is "file".
How would I go about doing this? Note: I DO NOT want to store the actual file on the database, just the path.
EDIT: I also want to save the actual file to a path, too.
Take a look at this page: http://www.php.net/manual/en/features.file-upload.post-method.php There is an example of moving an uploaded file to some folder.
So yes the relevant information is stored in $_FILE
First create appvars.php like something below
<?php
// Define application constants
define('GW_UPLOADPATH', 'foldername/');
define('GW_MAXFILESIZE', 32768); // 32 KB
?>
then create the code to save the file like something like this
<?php
require_once('appvars.php');
$file = mysqli_real_escape_string($dbc, trim($_FILES['file']['name']));
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
//do some checks to make sure the person upload the file type you like
if ((($file_type == filetype) // check for the size also
&& ($file_size > 0) && ($file_size <= GW_MAXFILESIZE)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = GW_UPLOADPATH . $file;
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
// Write the data to the database
mysqli_connect( database info);
$query = "INSERT INTO table (file ) VALUES ($file)";
mysqli_query($dbc, $query);
}
}
}
mysqli_close($dbc);
?>