If file doesnt exist loop (PHP) - php

I want people to upload photos on my website, and save each photo as a random file name. I created the upload form. and this is the uploading php function:
if($_FILES['myprofilepicture']['type']!='image/jpeg' && $_FILES['photo']['type']!='image/jpg' && $_FILES['photo']['type']!='image/png'){header("location:wrongfile.php");}else{
$info = pathinfo($_FILES['photo']['name']);
$randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
$target = 'picture/'.$randomfile; $now=time();
move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
header("location:home.php");
the problem is, if there was a picture uploaded with the same filename before, it will get overwritten, I want to improve the code so that
if no photo was uploaded with the same file name before->save photo
if a photo was uploaded with the same file name before->generate another random string and continue this loop until no photo was previously uploaded with the same name and then save the photo
any help?

Use file_exists() function to check if a file exists:
if($_FILES['myprofilepicture']['type'] != 'image/jpeg' &&
$_FILES['photo']['type'] != 'image/jpg' &&
$_FILES['photo']['type'] != 'image/png')
{
header("location: wrongfile.php");
}
else
{
$info = pathinfo($_FILES['photo']['name']);
$randomfile = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$length);
$target = 'picture/'.$randomfile;
if(!file_exists($target)) //if file doesn't exist
{
$now = time();
move_uploaded_file( $_FILES['myprofilepicture']['tmp_name'], $target);
mysql_query("Insert into photos(name,photo,date)values('$myname','$randomfile','$now')")or die('database error occured');
header("location:home.php");
}
}
The if conditional statement in the above piece of code will check if the file already exists, and if not, execute the statements in the block. However, if you want to repeat the process until a unique file path is found, you can use a loop instead:
while(!file_exists($target))
{
# code ...
}
As a sidenote: you're currently inserting user input directly into your SQL query. This is a very bad practice and it makes your query vulnerable to SQL injection. You should stop using the deprecated mysql_* functions and start using PDO or MySQLi.

Related

How to catch an error for a file name error? [duplicate]

This question already has answers here:
PHP Upload IF ISSET always says it is?
(5 answers)
Closed 3 years ago.
I am working on an instagram clone for school and I am currently working on the "update profile" feature,whenever I try to update the profile picture it works like a charm, but whenever I dont update the profile picture but I just update the description or username I get the following error.
"getimagesize(): Filename cannot be empty"
What is the best way to catch this error when I am not uploading a new profile picture?
I have tried a "try catch" method but it doesn't seem to work.
(could be possible I implemented it the wrong way
if(isset($_FILES["file"])){
if(getimagesize($_FILES["file"]["tmp_name"]) !== false){
$target_dir = "uploads/";
$extention = explode(".", $_FILES["file"]["name"]);
$i = count($extention) - 1;
$target_file = $target_dir . basename($_FILES["file"]["tmp_name"] . "." . $extention[$i]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// File has been moved to Uploads/[temp_name].[extention]
$user->setImage($target_file);
$a["image"] = $target_file;
} else {
// The file did not move to the destonation folder
}
}
}
I expect this to not return the error to me when I am not uploading a new picture but just tring to update my username or description.
You can check if error index is zero (UPLOAD_ERR_OK), if error is not zero cause no file was uploaded, UPLOAD_ERR_NO_FILE will be there
If you just want to check if upload went good you can write:
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
// file is good (and not an error)
}
If you want to check file wasn't uploaded
if ($_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
// file is empty, no upload
}
Check PHP Reference for more!

PHP - Uploaded file not sending to file directory

On my website, I allow users to submit files and they are sent to the database and a file directory, devFiles, I created. It sends to the database fine, but when i send it to the directory, it never sends and i get my error message i created to see if it sends or not. I believe the problem is with the
if(is_file($dir.'/'.$file_name)==false){
//code...
}
but i tried change the condition but it didn't work. So what i want to do is, send the file that was submitted to the file directory on hand that was created. Here is my code
PHP
$query = "INSERT INTO pack_screenshots(pack_id, file_name, file_tmp)VALUES(:packid, :file_name, :file_tmp)";
$stmtFileUpload = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
try{
$stmtFileUpload->bindParam(':packid', $packid, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
if(!move_uploaded_file($file_tmp,$dir.'/'.$file_name)){
die("File didn't send!");
}
}else{
$_SESSION['invalid'] = true;
header("Location: developer_invalid.php");
exit;
}
$stmtFileUpload->execute();
$_SESSION['thankyou'] = true;
header("Location: developerUpload_thankyou.php");
exit;
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
PHP Documentation bool move_uploaded_file ( string $filename , string $destination )
You did :
move_uploaded_file($file_tmp,$dir.'/'.$file_name)
move_uploaded_file is expecting $file_tmp to be a path to the tmp file but you used
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
so $file_tmp is no longer the path but the content it self
So to solve the upload problem just use the tmp file path instead.
if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){
Also, you should remove addslashes() on the file name because it could create unexpected results. Instead, you can sanitize the filename using something like this:
$file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name'][$key]));
You should also consider adding a random number to the file name so users don't overwrite other users files that have the same name: me.png could be common for an avatar for example. Would be safer to save as
$filename = strtotime("now")."_me.png";
One last thing, using is_file() can also cause problems in certain cases
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
use file_exists() instead

Check File is zip type before upload

I want people to be able to upload zip files to my server. I have a form for them to upload to and it redirects to an upload page. I can successfully upload pictures (png and jpg) but whenever I try a zip I canot upload it, its not show me any error, Is there a way to accept the zip files?
<?php
function uploadfile()
{
$allowedExts = array("zip", "rar");
$split = explode(".",$_FILES["filework"]["name"]);
$type = strtolower($split[sizeof($split)-1]);
$rname = time().".".$type;
if (($_FILES["filework"]["type"] == "application/zip") || ($_FILES["filework"]["type"] == "application/x-zip") || ($_FILES["filework"]["type"] == "application/x-zip-compressed") && ($_FILES["filework"]["size"] < 20000000) && in_array($split, $allowedExts)) {
$destination = "uploads/".$rname;
$temp_file = $_FILES['filework']['tmp_name'];
move_uploaded_file($temp_file,$destination);
return $rname;
} else {
return $_FILES["filework"]["error"];}
}
}
?>
try
in_array($type, $allowedExts)
also, nothing will be returned if your if fails and no actual error is generated, see php documentation
And as DanFromGermany said the process of upload is as follows:
user sends the form with the selected file
server loads the file to a temp folder (that's why you need $temp_file = $_FILES['filework']['tmp_name'];)
server executes php script to render the action page of the form
Because your php is executed last, it cannot check for file extension prior to upload, however you can just ignore the temp file if it doesn't meet criteria.

cannot upload images to mysql using php

I want to upload images to mysql server using php.
I have created html and sql connectivity but the image upload shows error.
I cant upload the image, it shows error of valid image i.e. you must upload jpeg,bmp,gif; and read/write in directory.
Can any1 help me solving this problem
the php file is
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Check to see if the type of file uploaded is a valid image type
function valid($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
//echo $file['type'];
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH = "image/";
$TARGET_PATH = $TARGET_PATH . basename( $_FILES['image']['name']);
$pimage = $_FILES['image']['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!valid($pimage))
{
$_SESSION['ERRMSG_ARR'] = array('You must upload a jpeg, gif, or bmp');
header("Location: admin.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['ERRMSG_ARR'] = array('A file with that name already exists');
header("Location: admin.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($_FILES['image']['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (p_category, p_name, p_quantity, p_desc, p_image) values ('$pcategory', '$pname','$pquantity','pdesc', '" . $pimage['name'] . "')";
$result = mysql_query($sql);
//Check whether the query was successful or not
if($result) {
$_SESSION['ERRMSG_ARR'] = array('Product added');;
$_SESSION['MSG_FLAG'] = 0;
session_write_close();
header("location: admin.php");
exit();
}else {
die("Query failed: ".mysql_error());
}
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['ERRMSG_ARR'] = array('Could not upload file. Check read/write persmissions on the directory');
header("Location: admin.php");
exit;
}
?>
I think
$pimage = $_FILES['image']['name'];
should be
$pimage = $_FILES['image'];
You probably missed this because your code is quite inconsistent - sometimes you use $pimage, while elsewhere you reference the $_FILES array directly. This makes it harder to maintain should the file field's name change. You could also type hint the valid() function to make PHP complain if $file isn't an array:
function valid(array $file) { ... }
What level of error reporting do you have set? It would highlight errors like trying to access undefined array keys.
See you are passing the image type in the line if (!valid($pimage))
But in the valid() function you are again trying to get the type of image $file['type'].
What George said should also work, but since you are making variables for the image type $ptype and name $pimage, you can use them itself.
So the changes should be $file['type'] becomes $file and $file['type'] & in the insert query $pimage['name'] becomes $pimage
I'm sure this solves it, Bahua ;)

How to test if a user has SELECTED a file to upload?

on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.
You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.
There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.
You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.
I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))
We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}
if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";
if ($_FILES['logo']['error'] === 0)
is the only right way

Categories