From the script below, can anyone tell me what I've done wrong to get the warning message on output of the script? The upload script is -
Code:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["thumb"]["name"]; // The file name
$fileTmpLoc = $_FILES["thumb"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["thumb"]["type"]; // The type of file it is
$fileSize = $_FILES["thumb"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["thumb"]["error"]; // 0 = false | 1 = true
$fileSplit = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($fileSplit); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling --------------------------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
// END PHP Image Upload Error Handling ----------------------------------------------------
// Place it into your "Avatars" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "Avatars/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfully.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
echo "The file extension is <strong>$fileExt</strong><br /><br />";
echo "The Error Message output for this upload is: $fileErrorMsg";
?>
My form is this
<?php
$profile_pic_btn = 'Toggle Avatar Form';
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="POST" action="process_reguser_exec.php">';
$avatar_form .= '<h4>Change your avatar</h4>';
$avatar_form .= '<input type="file" name="thumb">';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
The output is this
Warning: unlink(C:\xampp\tmp\php8E40.tmp): No such file or directory in C:\xampp\htdocs\MyWebSite\process_reguser_exec.php on line 37
The file named image1.JPG uploaded successfully.
It is 3337452 bytes in size.
It is an image/jpeg type of file.
The file extension is JPG
The Error Message output for this upload is: 0
Line 37 is this
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
When you have used the move_uploaded_file command, the file in the tmp location is no longer there, and therefor cannot be removed, I would say.
Looking a bit harder at your code, consider a restructuring:
if(move_uploaded_file($fileTmpLoc, "Avatars/$fileName"))
{
// do the image stuff
}
else
{
echo "ERROR: An error occured uploading and storing your file. Please try again.";
// Add a test to see whether the file exists
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
The regEx that you are using here
preg_match("/.(gif|jpg|png)$/i", $fileName)
is probably wrong. Because it will return true even for this file name $fileName="adjGIF" and i hope that you do not want this.So instead use this
preg_match("/.(\.(gif|jpg|png))$/i", $fileName)
Note:- Even though its not the answer but it will make your code correct.
//returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.
if (is_readable($fileTmpLoc)) {
unlink($fileTmpLoc);
}
use below code to move image file in to avatar named folder :
move_uploaded_file($fileTmpLoc,"Avatars".$fileName);
Related
Sorry I know there's a lot of posts about that but I can't find a solution in those.
Here's my form :
<form id="form1" action="upload.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name : </td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Image :</td>
<td><input type="file" name="image"/></td>
</tr>
<tr><td id='submitAdd' colspan='2'><input type="submit"
value= " Add " /></td></tr>
</table>
</form>
And here upload.php :
<?php
$ext = strtolower(substr(strrchr($_FILES['image']['name'], '.'),1));
$ret = move_uploaded_file($_FILES['image']['tmp_name'], 'item_images/'.$_POST['name'].'.'.$ext);
if ($ret) {
echo 'works';
}
else {
echo 'doesnt work'."</br>";
echo $_FILES['image']['error'];
}
?>
The directory's permission are ok, no uploading error, but still it won't move the file.
Am I missing something ?
Thanks in advance
I think you need to be specifying the absolute save path rather than the relative path it looks like you have now.
Ex. dirname(__FILE__).'/item_images/'.$_POST['name'].'.'.$ext
I would move the file under the uploaded file name, and then rename it. Also, some file type checking and security should be added to this.. Sanitize the post ect.. Here is how I would do it.
upload.php
<?php
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
//now we do some security checks
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than xxx Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
//give it the new name
$userstring= $_POST['name'];
$string = $fname.$userstring.'.'.$exten;
$image_name = preg_replace('/\s+/', '', $string);
//now we move it.
$moveResult = move_uploaded_file($fileTmpLoc, "item_images/$image_name");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
$imageFile = "item_images/$image_name";
//$imageFile is the variable to use in the rest of your script.
?>
I just how to fix this problem. This worked for me you can give it a try:
Just change
item_images/'.$_POST['name'].'.'.$ext);
to
'item_images/'basename($_FILES["image"]["name"])
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.
▲
Bear with me, im new to PHP. I got this very nice tutorial from here:
Add watermark image PHP - developphp.com
The problem is, the cropping ratio is not proportionate. If I have wider image, it crop 500px width and the height is not proportion to the width the same as the height (tall image crop to 500px and width is lesser px.)
I want to make it proportional as 500px both width and height no matter how wide or tall the image is and should crop center.
Been searching and trying other method but failed. Hope someone can help. Thanks!
Here is the code:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling -------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
// END PHP Image Upload Error Handling ---------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
exit();
}
// Include the file that houses all of our custom image functions
include_once("ak_php_img_lib_1.0.php");
// ---------- Start Universal Image Resizing Function --------
$target_file = "uploads/$fileName";
$resized_file = "uploads/resized_$fileName";
$wmax = 500;
$hmax = 500;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function ----------
// ---------- Start Convert to JPG Function --------
if (strtolower($fileExt) != "jpg") {
$target_file = "uploads/resized_$fileName";
$new_jpg = "uploads/resized_".$kaboom[0].".jpg";
ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt);
}
// ----------- End Convert to JPG Function -----------
// ---------- Start Image Watermark Function --------
$target_file = "uploads/resized_".$kaboom[0].".jpg";
$wtrmrk_file = "watermark.png";
$new_file = "uploads/protected_".$kaboom[0].".jpg";
ak_img_watermark($target_file, $wtrmrk_file, $new_file);
// ----------- End Image Watermark Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
echo "The file extension is <strong>$fileExt</strong><br /><br />";
echo "The Error Message output for this upload is: $fileErrorMsg<br />";
?>
I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>
I am making an application that allows users to upload a file in a directory via PHP.
I am having problems because it dose not allow me to overwrite files with the same name.
Eg I have a file called text.php and I upload it, now when I go back and change the content of file text.php and I upload it again on the server I still have the version without the edits. However if I upload another file it works. So I just can't overwrite files.
if ($_POST["greg"]=='true'){
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 90000000000000) { // if file is larger than we want to allow
echo "ERROR: Your file was larger than 50kb in file size.";
unlink($fileTmpLoc);
exit();
} else if (!preg_match("/.(doc|docx|xls)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your file is not the right format contact the master of the page for clarification.";
unlink($fileTmpLoc);
exit();
}
// Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");
// Check to make sure the uploaded file is in place where you want it
if (!file_exists("documenti/$fileName")) {
echo "ERROR: File not uploaded<br /><br />";
echo "Check folder permissions on the target uploads folder is 0755 or looser.<br /><br />";
echo "Check that your php.ini settings are set to allow over 2 MB files, they are 2MB by default.";
exit();
}
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is a <strong>$fileType</strong> type of file.<br /><br />";
echo "The Error Message output for this upload is: <br />$fileErrorMsg";
}
How can I change this code so that when I upload a file with the same name it overwrites the existing file?
Try this (put it before upload a file)
//checking if file exsists
if(file_exists("documenti/$fileName")) unlink("documenti/$fileName");
//Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");
Maybe the script does not have the rights to overwrite? Try to change the dir to 777 and test again. If it works then, you can figure out the correct value you need
if (file_exists("documenti/$fileName"))
{
unlink("documenti/$fileName");
echo "<font face='Verdana' size='2' >Last Uploaded File has been removed from uploads folder<br>back to uploadform agian and upload your file<br>";// now your file which uploaded before was deleted from uploads folder you can open it and check if it removed or not , so no you should go back to uploadform again and import your file which will uploaded correctly
echo "<font face='Verdana' size='2' ><BR><BR><BR><a href='upform.php'>Back to upform</a><BR>";
}
Have you tried checking if the file exists and deleting it if it does before you move the temporary file to the permanent storage location?
$filePathAndName = "documenti/$fileName";
//check file exists
if(file_exists($filePathAndName))
{
unlink($filePathAndName);
}
//move_uploaded_file() function
move_uploaded_file($fileTmpLoc, $filePathAndName);