Sorry if this is easy but I'm slightly new to programming so I'm having problems renaming a temporary uploaded file. Here is my code:
HTML:
<input type="file" class="upload-img" name="logo" id="image" accept="image/*" />
PHP:
if(move_uploaded_file($_FILES['logo'] ['tmp_name'], "images/".[logo])) {
print '<p> Your image has been uploaded </p>';
} else {
print '<p> There was an error with the image</p>';
}
Would anyone be able to tell me how to correctly rename the temporary uploaded image to 'logo'?
I currently get an error that says:
Warning: fopen(images/logo.png): failed to open stream: No such file
or directory in /home/matos/public_html/pdftest/tfpdf.php on line 1443
FPDF error: Can't open image file: images/logo.png
first you should know the type of the file. $_FILES['logo']['type'] will give you the type. Check below code.
$extension = explode("/", $_FILES['logo']['type']);
$rename="logo.".$extension[1];
if(move_uploaded_file($_FILES['logo']['tmp_name'], "images/" . $rename)) {
print '<p> Your image has been uploaded </p>';
} else {
print '<p> There was an error with the image</p>';
}
What is the absolute path of images folder?
I assume that the form submit file to /pdftest/tfpdf.php
and /home/matos/public_html/pdftest/tfpdf.php is the script handle uploaded file. If the images folder's absolute path is /home/matos/public_html/images
your code should be
move_uploaded_file($_FILES['logo'] ['tmp_name'], "../images/logo.png")
Because the base path on your context is the folder of main script which I assume is /pdftest/tfpdf.php, it was /home/matos/public_html/pdftest/ on your local. When you save the uploaded file the real path will be
/home/matos/public_html/pdftest/../images/logo.png
shorted /home/matos/public_html/images/logo.png
Related
I'm following a tutorial for uploading image files using php on udemy. I can choose an image and upload it to a folder without any problems.
When I click on the image after it has been uploaded to the folder, windows photo viewer says: "photo.png It appears that you don't have permission to view this file. Check the permissions and try again".
When I checked permissions it said "You must have read permissions to view the properties of this file".
I used the chmod function set to 0755, which allows the owner to read and write, and lets everyone else read it. I tried changing the chmod codes but it didn't help.
I'm thinking it has something to do with my server permissions, but can't find any solution on google. My images are uploaded to Abyss Web Server.
Here is the code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function upload_file() {
//setup
$tmp_name = $_FILES['file']['tmp_name'];
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['file']['name']);
$max_file_size = 5000000; //5mb
$allowed_file_types = array('application/pdf; charset=binary');
$allowed_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
//check if image type is allowed
$image_check = getimagesize($tmp_name);
if(! in_array($image_check[2], $allowed_image_types)) {
//if not allowed image check if allowed file type
exec('file -bi' . $tmp_name, $file_check);
if(! in_array($file_check[0], $allowed_file_types)) {
return 'This file type is not allowed';
}
}
//check if file already exists
if(file_exists($target_file)) {
return 'Sorry that file already exists';
}
//check file size
if(file_exists($target_file)) {
return 'Sorry this file is too big';
}
//store the file
if(move_uploaded_file($tmp_name, $target_file)) {
chmod($target_file, 0644);
return 'Your file was uploaded';
}
else {
return 'There was a problem storing your file. Try again?';
}
}
if(! empty($_FILES)) {
echo upload_file();
}
?>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file">
<input type="submit" Value="upload">
</form>
Since loading the file using a custom made HTML page specifically for testing motives does show the image correctly, then it's most likely a hotlink protection issue. (This was found out after a few comments to the question).
In cPanel, for example, there is a tool to manage this feature and it revolves around the usage of a file called .htaccess. This file is used for a lot of things in the web development world.
Some people don't like their copyrighted images to be accessed, so one way to avoid inexperienced people (let's say, "people in userland") from doing that is to enable this protection. This works for any given file extension that you set it up to.
One way to address this issue is to go to cPanel and disable (or modify accordingly) the Hotlink Protection feature. Another way, is to find the .htaccess file that is causing the issue, which requires understanding the way it works and the syntax it uses.
I am trying to make a simple file upload form using PHP. Here's my code:
<?php
$uploads_dir = '/uploads';
if(isset($_FILES['thefile'])){
$errors= array();
$file_name = $_FILES['thefile']['name'];
$file_size =$_FILES['thefile']['size'];
$file_tmp =$_FILES['thefile']['tmp_name'];
$file_type=$_FILES['thefile']['type'];
$tmp_name = $_FILES['thefile']["tmp_name"];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($tmp_name, "$uploads_dir/$file_name");
echo "Success";
}
else{
print_r($errors);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="thefile" />
<input type="submit"/>
</form>
</body>
</html>
I realize that I'm not limiting file types, but I'll worry about that once I can get a simple .jpg or .zip file uploaded. Using the above code, I go to the page on my local server located at
C:\wamp\www\simpleupload (this contains index.php, the file posted above)
When I select a small image file and click submit, I'm presented with the following errors:
Warning: move_uploaded_file(/uploads/session_timeout_formatting_bug.png): failed to open stream: No such file or directory in C:\wamp\www\project_fileshare\index.php on line 18
and
Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpEFDE.tmp' to '/uploads/session_timeout_formatting_bug.png' in C:\wamp\www\project_fileshare\index.php on line 18
Line 18 is the line that calls the move_uploaded_file() function.
How do I fix this error? I have an 'uploads_dir' folder located in the same folder as my index.php file. (reference the file path above). What am I doing wrong here? I must be misunderstanding some small part of this process and have put my directory in the wrong place, or I'm doing something wrong in the code.
Can someone spot my mistake and tell me what I need to do to fix it?
You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).
Since you are working in windows and your document root is C:\wamp\www\simpleupload
Which means, your files are located like this:
C:\wamp\www\simpleupload\index.php (your upload script)
C:\wamp\www\simpleupload\uploads (where the files should be uploaded)
Why don't you use absolute path like this:
$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';
The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads
Try this.
If your upload directory is in the same location as your index.php remove the "/" in your $uploads_dir variable. This, or add a "." before the slash because now it refers to the root which might be something else then your current working directory. Speaking of the devil; http://php.net/manual/en/function.getcwd.php
$uploads_dir = getcwd() . '\uploads';
$uploads_dir = __DIR__ . '\uploads'; #php > 5.6
Also, check if your directory is writeable for php:
http://php.net/manual/en/function.is-writable.php
Also what Latheesan said, better to go cross platform as I made the same mistake seen in my edit.
<?php
function buildPath(...$segments){
return join(DIRECTORY_SEPARATOR, $segments);
}
echo buildPath(__DIR__, 'uploads');
?>
And i would change
if(isset($_FILES['thefile'])){
for this
if($_FILE['thefile']['error'] === UPLOAD_ERR_OK){
Because I think that this is the best way to know if the user upload a file or the input is blank.
Or
if (isset($_FILE["thefile"]["name"])){
Ok, I used google over the last 2 days and didn't got what is wrong with my code. First it seemed that I used the wrong path but the official "Hilfe Center" (like helping center or so) from 1&1 said that this must be the right path "e:\Kunden\Homepages\11\d12345678\www\UploadTest" (obviously you have to adapt it to your path, which i got throught phpinfo() )
so I'm using the following code:
<form action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"datei\"><br>
<input style=\"position:absolute;left:5px\" type=\"submit\" value=\"Hochladen\">
</form>
on the site where you upload the file and
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = "e:\\Kunden\\Homepages\\11\\d12345678\\www\\UploadTest";
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.'); // if we upload large file then we get error.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.'); // if we have no enough permission then got error.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)){
// if everything is fine then we upload file and go to somewhere else
header ('location: whereeveryouwantogo.php');
} else {
echo 'There was an error during the file upload. Please try again.';
}
on the site where the php script is running (upload.php). I got the code on another thread here and wanted to use it for troubleshooting. Later I'm going back to my own code.
I am now at the last error:
'There was an error during the file upload. Please try again.';
I just want to upload .txt files that are later used on a news based site. Thx for any helps in advance!
I think the problem is name of the input or name of the files variable.
$files=$_FILES['datei']['tmp_name'];
I want to upload multiple files to the server.
As far as I can see files are not writable.
What can I do so my code can actually work and upload files.
PHP:
if(isset($_FILES ['uploaded_files']))
{
foreach($_FILES['uploaded_files']['name'] as $key=>$value)
{
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{
$filename = $_FILES['uploaded_files']['name'][$key];
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
{
//code
}
else
{
die ('There was a problem uploading the pictures.');
}
}
else
{
die ('There is a problem with the uploading system.');
}
}
}
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="input_clone_id" name="input_clone_id" value="'.$row['id'].'"/>
<input type="hidden" id="input_clone_var" name="input_clone_var" value="V"/>
<input type="file" name="uploaded_files[]" id="input_clone" multiple="multiple" /><br />
<input type="submit" style="margin-left:0" value="Upload Files" />
</form>
I see two problems with this. The first is a security issue and the second is probably what is causing your problem
You have a security problem here:
$filename = $_FILES['uploaded_files']['name'][$key];
...
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
...
Problem a: Since $filename comes from the $_FILES array, it CANNOT be trusted. The user told your site what the name of their file was and put it there. They could feed you some bogus filename that could cause your script to fail in interesting ways. You need to sanitize that filename before using it in any way.
Problem b: By allowing the user to specify the filename, they could potentially overwrite other files in your "images/gallery" directory simply by specifying a conflicting filename. The way to avoid this is to use a database, generate a unique identifier for the uploaded file, store the file under that unique name, and in the database keep a record of the original filename and other information. That way you always know what the original filename was and you don't have the chance of someone trying to overwrite files in that directory.
Writing problem:*
Your "check for writable" statement is wrong. The filename that comes back is the one that the user used when submitting. This will not point to any point on your filesystem...it points to a spot on theirs (sometimes) which you cannot see. What you need to check is that your "../images/gallery" directory is writable rather than $filename. If that fails, you need to do either "chmod -R 777 gallery" while in the images folder if you have command line access or give it world write access through whatever FTP client you are using if you are using FTP to talk to your server.
So, what you should have instead for that check is:
if (is_writable("../images/gallery")) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
After doing that, if your script comes back and says "the file is writable", it should have been able to copy the file into your images/gallery folder (remember to not use the name of the file the user gave you). If not, perhaps you don't have permissions to move uploaded files.
As for the location of uploaded files, I think sometimes they are deleted after the script execution ends sometimes, but if not, you can echo the 'tmp_name' of the file and if you go to that directory you should find it sitting there. That would be just a verification test to make sure the file was actually getting to your server. So long as you have write permissions (that what chmod 777 does) on the directory you are moving the uploaded file to, you should be able to copy it there.
You are checking to see if a file that you recently uploaded, but not yet saved is writable, I don't think such a file will ever be writable.
Better remove that if, or just check if the folder you are uploading to is writable.
Other than that, I checked your code and it works.
When I upload a file using this code, it puts a copy of the file in the "uploads" folder(which is what I want) but it also puts a copy in my root. I only want the files going to the uploads folder.
define ('GW_UPLOADPATH', 'uploads/');
$upfile= GW_UPLOADPATH . $_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
if(!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) //this is saying if the file isn't moved to $upfile.
{
echo 'Problem: could not move file to destination directory';
exit;
}
}
else
{
echo 'Problem: Possible file upload attack. Filename: '; //this could be an attack b/c it might be from localhost.
echo $_FILES['userfile']['name'];
exit;
}
echo 'File uploaded successfully<br><br>';
What would be your temporary dir? Is it possible that somehow the uploaded file lands in the root but PHP can not delete it? Figuring this out requires a lot more knowledge about your setup.