pdf and word file uploading in php - php

In here i have tried to upload jpeg,pdf ,png and word file formats in php. But i could not able to upload pdf,png and word file formats.but i have successfully upload the jpeg file formats. So this is the code i have tried.please help to edit this code to upload other file formats with out the jpeg file format.
<?php
include_once("db.php");
if(isset($_POST['save'])){
if(($_FILES['file']['type']=='pdf/pdf')
||($_FILES['file']['type']=='image/jpeg')
||($_FILES['file']['type']=='image/png')
&&($_FILES['file']['size']<200000))
{
if($_FILES['file']['error']>0)
{
echo"return code :".$_FILES['file']['error'];
}
//else if(file_exists('upload/'.$_FILES['file']['name']))
//{
//echo $_FILES['file'] ['name']."Already exite";
//}
else if(move_uploaded_file($_FILES['file'] ['tmp_name'],'upload/'.$_FILES['file']['name']))
{
$part =$_FILES['file']['name'];
$sql = mysql_query("INSERT INTO stu (ptype,source,letterno,title,descrip,receiver,image)
VALUES ('{$_POST['pt']}',
'{$_POST['so']}',
'{$_POST['ln']}',
'{$_POST['lti']}',
'{$_POST['dic']}',
'{$_POST['re']}',
'{$part}')");
//$sql= "INSERT INTO stu (ptype,source, letterno, title,descrip,receiver,image) VALUES ('$p', '$s', '$l', '$t','$d','$r','$part')";
if ($sql){
echo"jhgjhgjh";
//echo "successfully insert thise record";
//echo "<script type='text/javascript'>alert('successfully insert thise record')</script>";
echo "<script type='text/javascript'>alert('successfully insert thise record')</script>";
}
}
}
}
?>

PDF documents have different MIME type: application/pdf, you should use it.
Microsoft Word documents MIME type application/msword is not in list of your allowed mime types, so it is failed to get through your check.
You have size limit of 200kib, it is about 195kb, probably you have documents larger then this (pretty low) limit.
After raising local file limit - check your upload_max_filesize setting in php.ini since it is next size limitation boundary, you may stuck on.
Besides this your code have logical problem into MIME type checking condition since you didn't group MIME checks into separate logical value. Your condition is actually: if (a OR b OR c AND d) while is should be if ((a OR b OR c) AND d).
It will be even better to rewrite this code as:
$allowed_mime_types = array('image/png','image/jpeg','application/pdf','application/msword');
$size_limit = 200000;
if ((in_array($_FILES['file']['type'], $allowed_mime_types)) && ($_FILES['file']['size'] < $size_limit)) { ... }

try changing :
$_FILES['file']['type']=='pdf/pdf'
to:
$_FILES['file']['type']=='application/pdf'
for doc type:
$_FILES['file']['type']=='application/msword'
for docx:
$_FILES['file']['type']=='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
Note:
also check if the file size of the file that you're trying to upload is not greater than allowed.

Related

Image (src) not refreshing after file-upload -> image [duplicate]

This question already has answers here:
PHP force refresh image
(5 answers)
Closed 2 years ago.
Having an image 'update' problem, whereby the image does not change after new file upload. the SRC attribute is designed to remain same; each uploaded file overwrites the previous one.
Let me elaborate::
I have a simple webpage, say Home.php and the page shows an image 'IMAGE1.jpg' where the image tag's src = "directory456/IMAGE1.jpg", understandably.
This homepage allows the user to change the image, through a file upload button Input type="file" (as we all know) located inside a "form". The form POSTS all the file data to another php file "Upload_File_Check.php".
Inside "Upload_File_Check.php", simple actions are performed:
(1) Check file size <2.0 MB,
(2) Check file "type" ($_FILES['filename']['type']) is one of {image/jpeg image/gif image/png}, and
(3) depending on whichever, utilizes the imagecreatefrom(gif/png/bmp)() function in PHP, to convert them ALL to jpg,
(4) ALL uploaded files are saved as "directory456/IMAGE1.jpg" using same file name hence overwriting the previous file sitting the in the directory. This way, knowing that the image's name will always be IMAGE1.jpg, I will not need to store/retrieve that from database. (comments welcome on this practice).
However, once the user clicks on the "Upload" button, and checks in "Upload_File_Check.php" are completed successfully, I would have thought that since "Home.php" is reloaded (? not sure about this), the image tag would get refreshed and now show the new image which has just been uploaded (SRC has remained same src="directory456/IMAGE1.jpg")?. The old image is showing, only upon manual page reload does the new image show.. how can I get the image tag to now refresh and load recent image pointed to ?
Code for Home.php:
<FORM method='post' action='Upload_File_Check.php' enctype='multipart/form-data'>
<INPUT type='file' name='filename_' size='10'>
<INPUT type='submit' value='upload'>
</FORM><?PHP echo $_SESSION['UPLOAD_FILE_ERR'];?>
Code for Upload_File_Check.php:
<?PHP
if($_FILES['filename_']['error'] > 0)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR: ". $F_error;
header("location: HOME.PHP");}
else
{ $F_name = $_FILES['filename_']['name'];
$F_tmpnm = $_FILES['filename_']['tmp_name'];
$F_type = $_FILES['filename_']['type'];
$F_size = $_FILES['filename_']['size'];
if (!$F_tmpnm) // if file not chosen
{ $_SESSION['UPLOAD_FILE_ERR'] .= "ERROR - must have a file. "; }
if (!(($F_type == "image/bmp")||($F_type == "image/png")||($F_type == "image/jpeg")||($F_type == "image/gif")))
{ $_SESSION['UPLOAD_FILE_ERR'] .= "INVALID - only BMP JPG PNG GIF files allowed "; }
if ($F_size > 2097152)
{ $_SESSION['UPLOAD_FILE_ERR'] .= "File must be < 2.0MB "; }
if (($_SESSION['UPLOAD_FILE_ERR']) !== "")
{ header("HOME.PHP"); }
else
{ $F_destpath = "directory456/";
$F_destname = "IMAGE1.jpg";
move_uploaded_file($F_tmpnm, ($F_destpath . $F_name));
//convert MOVED file to jpg.
switch($F_type)
{ case "image/png":
$Converted_image=imagecreatefrompng($F_destpath . $F_name); break;
case "image/bmp":
$Converted_image=imagecreatefrombmp($F_destpath . $F_name); break;
case "image/gif":
$Converted_image=imagecreatefromgif($F_destpath . $F_name); break;
case "image/jpeg": break;
}
imagejpeg($Converted_image, $F_destpath . $F_destname , 90);
}
header("location: HOME.PHP");
}
?>
How do I get the IMAGE tag to refresh and point to the new image.. Would greatly appreciate your help...
New bie here, would also welcome all comments on the way I have programmed the stuff below.. what are best practices, what are faster (more efficient) methods, etc..
This question is a duplicate of PHP force refresh image.
The image isn't refreshing because the browser is caching the older file. To solve, just add a cache-busting query string to the URL in your img src. Unix timestamps work well for this. Note, however, that this will force the image to reload every time the page is loaded.
<img src="IMAGE1.jpg?t=<?php echo time() ?>">

PHP file upload Issues - Can't Move uploaded File

I am trying to upload image to database and getting this PHP error message:
Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA9E6.tmp' to '/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg' in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Upload Fail.
Here is my php script:
<?php
require("include/functions.php");
check_session();
$logged_user = $_SESSION['username'];
if(isset($_FILES['avator']['name']) && $_FILES['avator']['tmp_name'] !=""){
//setting file properties
$fileName = $_FILES['avator']['name'];
$filetmpLoc = $_FILES['avator']['tmp_name'];
$fileType = $_FILES['avator']['type'];
$filesize = $_FILES['avator']['size'];
$fileErrMsg = $_FILES['avator']['error'];
//explose the filename extention into an array
$kaboom = explode('.',$fileName);
$fileExt = end($kaboom);
list($width ,$height) = getimagesize($filetmpLoc);
if( $width <10 || $height <10 ){
//the image has not dimenssion
echo 'The Image has no dimension.Try again!';
exit();
}else{
// The image is has dimension so its OK
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
//check the size of the image
if($filesize > 1048576){
echo 'Your avator file size was larger than 1mb.';
exit();
}else if(!preg_match('/\.(gif|png|jpg)$/i',$fileName)){
echo"Your avator file was not JPG,PNG or GIF type.Try again.";
exit();
}else if($fileErrMsg == 1){
echo "Unknoan Error occured. Upload Fail.";
exit();
}
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
if( $moveResult !=true){
echo 'Upload Fail.';
exit();
}else{
//resize the image
include_once("include/resizeimage.php");
$target_file = "user/$logged_user/$db_file_name";
$resize_file ="user/$logged_user/$db_file_name";
$wmax = 200;
$hmax = 230;
img_resize($target_file,$resize_file,$wmax,$hmax,$fileExt);
$sql = "UPDATE mygust SET avatar = '$db_file_name' WHERE username='$logged_user' LIMIT 1";
$query = mysqli_query($con,$sql);
mysqli_close($con);
exit();
}
}
}
?>
My HTML code is:
<form id="u_pro_pic" method="post" enctype="multipart/form-data" onSubmit="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<h2>Set your Profile Avator</h2><br>
<div id="av_wrap"><div id="avator_div"><img src="image/blank-profile.png" class="avator" title="Chose a file to upload" onClick="triggerUpload(event,'avator')"></div>
<div id="ad_clarleft">
<input type="button" class="add" title="Choose a file to upload" onClick="triggerUpload(event,'avator')" value="Add Avator"><br>
<hr>
<p>These brethren have uploaded their's and you should too. </p>
</div>
</div>
<input name="avator" type="file" id="avator" form="u_pro_pic" onChange="readURL(this)">
<input type="submit" name="u_avator" id="sumit" class="avt" value="Upload">
</form>
Please any help would be much appreciating.
PHP tries to move your uploaded file to a folder that does not exist:
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
The path "/upload" does not look like a correct windows path. Change it to something like "C:\xampp\htdocs\learnphp\upload". Create this folder manually if it does not exist.
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"C:/xampp/htdocs/learnphp/upload/$logged_user/$db_file_name");
The reason why you're getting an error on the upload, is that the folder itself does not exist; least that's the impression I am getting from it and to be honest, we don't know if efc5ad334bca9f31b19d85a6cc2ada57 exists or not.
Sidenote: Use file_exists() which is referenced further down in this answer.
Since you are using sessions for $logged_user as the username session array, make sure the session was started inside all files using sessions. session_start(); must reside inside all files, and at the top of your code.
It is good practice to check if the session is also set using isset() or !empty().
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
If not (which am pretty sure it doesn't), you would first need to create it using the mkdir() function.
http://php.net/manual/en/function.mkdir.php
The syntax is: mkdir("/path/to/my/dir", 0700); - 0700 can be changed to 0755 which is the usual setting for folders and it must be set so that the folder can be written to, using chmod.
http://php.net/manual/en/function.chmod.php
The syntax being, one of the 3 listed from the manual:
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
So, you will need to use the mkdir() function after the session file and before "moving" it to the folder created by $logged_user and its associated name.
I.e.:
mkdir("/path/to/your/dir", 0700); // you can use variables here
$moveResult = move_uploaded_file(...);
This part of your code /upload/ suggests using a full server path syntax.
move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name")
Either you use what your full server path is, for example:
/var/usr/public/upload/
or as referenced in another answer given C:/xampp/htdocs/learnphp/upload/
or a relative path:
I.e.:
upload/ or ../upload/ depending on the execution location of your script. The former being if executed from the root of the public area.
Nota: I am unsure if -416649605.jpg is the actual filename being uploaded, or if there is anything missing before the hyphen, or the hyphen is being added somewhere. You will need to look into that.
Pulled from my comment:
Now, if you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html.
However, when using a BLOB to insert into the db directly, you will have to use mysqli_real_escape_string() for that, otherwise it won't work; you will get a syntax error thrown back.
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
So, keep on using error reporting until you can figure out where the problems may be occuring.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// if using MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysqli_error($con)) to $query = mysqli_query($con,$sql); to check for database errors.
Reference:
http://php.net/manual/en/mysqli.error.php
Additional reference:
http://php.net/manual/en/function.file-exists.php (check if a file/folder exists)
Footnotes:
Your code in its present state is open to an SQL injection. Use a prepared statement
References:
https://en.wikipedia.org/wiki/Prepared_statement
How can I prevent SQL injection in PHP?
I believe I have given you enough information in order to point you in the right direction that will and hope will lead you to success, cheers!
Replace your $moveResult statement with the following two statement as you have to store the file in folder with a specific name.
$destination = "./".$_FILES['avator']['name'];
$moveResult = move_uploaded_file( $_FILES['avator']['tmp_name'],$destination);

Count the number of files selected for upload within multiple file fields

I've wrote a script where the user can select to upload more than one image to a form. I'm preventing the user from submitting the form until all of the file fields that have been added actually contain files for upload.
EG:
The user has three file fields to fill in, therefore three files must be ready for submission to the database.
I'm using the same id on each of the file upload fields. When I use print_r($_FILES); it returns me an array. If I browse for a file in the first file field, and leave another two blank, it will state that the array object for [1] and [2] are blank, however [0] will obviously have a name, type, size etc as it exists.
How would I go about making sure that all of the file fields are actually filled in using PHP?
Thanks in advance, Rich
Here are my efforts so far:
$imgName1 = $_FILES['upload1']['name'];
$imgTmp1 = $_FILES['upload1']['tmp_name'];
$imgType1 = $_FILES['upload1']['type'];
$imgSize1 = $_FILES['upload1']['size'];
print_r($_FILES);
if(!$imgTmp1){
echo "<span class='error'>You need to include at least one image with this article.</span>";
exit();
} else {
$fileCount=($_FILES['upload1']['name']); // My attempt to count that the file fields are all filled in
$cnt = $_POST['cnt']; // This is the number of file fields that currently exist
echo "<br/>";
echo count($fileCount);
if($cnt != $fileCount){
echo "<span class='error'>You have not uploaded all of your files.</span>";
exit();
}
// etc etc
You have incorrect upload checking. The presence something in $_FILES doesn't mean that file uploaded. A failed upload will STILL create $_FILES entries.
You need to check for BOTH the presence of the $_FILES entry, and its error parameter:
if (isset($_FILES['upload1'])) {
if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded
} else {
... upload failed
}
} else {
... no file upload was even attempted
}

php string comparison not working for image metadata

I am extracting image metadata using php. The logic of my below code is that if the user uploads the default file with metadata(UserComment)=ASCIIsd11, he/she will get an error.
<?php
$exif_s = exif_read_data('e42889ed00.jpg');
$phtchk = $exif_s["UserComment"];
print $phtchk;
print strcmp($phtchk, "ASCIIsd11");
if(strcmp($phtchk, "ASCIIsd11") == 0){ echo "You have not uploaded your own photo"; exit;}
else
{
echo"You have uploaded it.";
}
?>
print $phtchk; returns ASCIIsd11
print strcmp($phtchk, "ASCIIsd11"); returns -1
and the last echo statement "You have uploaded it" is printed. Actually I am expecting strcmp() to return 0. Kindly help.
Do var_dump(phtchk); instead of print $phtchk;
Perhaps you don't see some extra-chars (eg: \n).
If it concerns the collation, you should see:
UTF-8 characters not displaying properly from JPEG IPTC data in PHP

CSV Import to MySQL Table with image copy

Wondering if anyone would be so kind to help me with a addition to this script i have found online:
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
Import File : <input type='text' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
i have a csv which i want to import a bunch of data and this piece of code i have found online should do the trick but i have a couple of extra things i need to apply and hoping someone would be willing to write additional code to this for this to work.
i have 2 fields in the csv container image paths from another url:
image: http://blag.com/images.jpg
images: http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg;http://blag.com/images.jpg
i am wanting to grab the image from the external url and upload it to a path on the site itself and then set the local image path and image name in the database
the images part contains multiple images which i need to do the same but apply to another field with those on them but would need to be able to display those additional images on the page but not sure if possible with that ; seperator in the database but guess you guys will know if its possible to fectha dn display but thats something ele i guess
if someone would be so kind to help me adapt that code so i can do that would be awesome as need to import a lot of data tonight :)
Thanks in advanced!
I wouldn't use php for this task. For importing the csv data I would use mysqlimport as it is much more efficient and less error prone then rolling your own php solution. For retrieving the images and storing them locally you could easily write a ruby or perl or even a bash script with curl to fetch the image and place them in the correct directory.
If this is part of another tool written in PHP then I would = look to using a system command to execute the mysqlimport on the local file. Then I would use the curl facility to grab the images and place them in the appropriate directory.
James,
you can add it easily,...
In this line:
$sql = "INSERT into user(name, email, phone) values('$data[0]','$data[1]','$data[2]')";
add the name of related Database Fields to the first part(for example:)
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]')";
and for add their values from the result array in $data if they are immediately after other items (I mean if it is in this format: Name - Email - Phone - image - images) you just need to add to the index of array, in this condition it would be something like this:
$sql = "INSERT into user(name, email, phone **,image, images** ) values('$data[0]','$data[1]','$data[2]' **,'$data[3]','$data[4]'** )";
------------------------------------------------
UPDATED
OK, that's not hard too... I wrote a sample code for that, let me know if you have any problem:
// List of all images separated by ";"
$all_images = "http://www.google.com/images/nav_logo40.png;http://static.php.net/www.php.net/images/php.gif";
// Make an array from the list of images
$images = explode(";", $all_images);
// We want to copy all of images in the array
foreach ($images as $img_source_path){
// Retrive the name of file from path (It works for most of filenames!)
preg_match("/\/(?P<name>[a-zA-Z0-9._]+)$/", $img_source_path, $img_matches);
$img_filename = $img_matches[name];
// Make destination path
$img_destitation_path = getcwd()."/temp/".$img_filename;
// Copy file and check if it is done successfully
if (!copy($img_source_path, $img_destitation_path)) {
echo "failed to copy $img_filename...\n";
}
else {
echo "$img_filename copied successfully...\n";
}
}

Categories