what's wrong with the upload code? - php

<?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

Related

In Codeigniter How to check if the uploaded file is actually a pdf or jpg or png?

In Codeigniter How to check if the uploaded file is actually a pdf or jpg or png? Because, if we upload an .exe file with .pdf extension then also it gets uploaded without any problem. So, it there a proper way to actually check the file and its content to be able to determine whether it is actually a pdf or exe. Because with just the file extension anything can be uploaded. Please, help me find a proper solution for this. Is there any native php function through which we can achieve this. If so a sample code might be helpful.
you can use mime_content_type() function which is in built in php it provides actual content type even if the extension is changed
php docs
<?php
echo mime_content_type('abcd.pdf') //application/pdf
?>
checking mime_content_type while uploading
$mimetype = mime_content_type($_FILES['file']['tmp_name']);
if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {
move_uploaded_file($_FILES['file']['tmp_name'], '/whatever/something/imagedir/' . $_FILES['file']['name']);
echo 'OK';
} else {
echo 'It is not an image';
}
You need to check real file type and given file type like this:
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$this->load->library('upload', $config);
$file = $_FILES['userfile'];
// given file type
$gftype=pathinfo($file['name'], PATHINFO_EXTENSION);;
// real file type
$rftype = explode('/',mime_content_type($file['tmp_name']))[1];
if($gftype === $rftype){
if (! $this->upload->do_upload('userfile')){
echo "Error";
}else{
echo "Success";
}
}else{
echo 'This is not real extension';
}

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

Image upload to Temp Folder warning

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);

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories