i have a form where you can put an image uploade, which is optional. with this script at the moment it writes upload/timestamp into my database. but i need to replace that with a placeholder if no file is uploaded. here is the code:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 1024000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path_parts = pathinfo($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
}
}
else
{
echo "Invalid file";
}
and:
$name1 = $_REQUEST['name1'];
$email1 = $_REQUEST['email1'];
$beschreibung1 = $_REQUEST['beschreibung1'] ;
$latitude = $_REQUEST['latitude'] ;
$longitude = $_REQUEST['longitude'] ;
$file = $_REQUEST['file'] ;
$pic = ("upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
include 'bikemap_db_open.php';
$sql = "INSERT INTO input2 (f_name, f_e_mail, f_text, f_adr, f_dat, f_geom, f_foto)";
$sql = $sql . " VALUES ('" . $name1 . "','" . $email1 . "','" . $beschreibung1 .
"','" . $longitude . " " . $latitude . "', '" . date("d-m-Y") . "', ST_GeomFromText('POINT(" . $longitude . " " . $latitude . ")', 4326),'" . $pic . "')";
$result = pg_query($sql) or die('Query failed: ' . pg_last_error());
include 'bikemap_db_close.php';
header( "Location: /danke.html" );exit;
In the first code block
else
{
echo "Invalid file";
$fileupload = false;
}
In second codeblock
if ($fileupload == true){
$pic = ("upload/" . $path_parts['filename'].'_'.time().'.'.$path_parts['extension']);
}
else
{
$pic = 'placeholder.gif'; // you will need to specify the full path
}
Related
I am trying some file upload code which I Googled.
Now Issue is when I try to upload image and if its already in folder then its over write and issues come. I Try Code From here and here as well but I face some error.
Here is my code. Can I do in this code that its upload file with some extra name which stop over write of existing file??
if(isset($_REQUEST['main']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
/*if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {*/
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}
/*}
} else {
echo "Invalid file";
}*/
}
$main = $_REQUEST['main'];
$sql="INSERT INTO image VALUES ('', '$filepath', '$main')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
You can check if the file exists using file_exists.
If it exist, add some extra characters to the file name. Then you can save it.
Here is a function that generates random characters :
function randomString($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
Replace the code :
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
with :
$newLocation = "../img/catalog/" . $_FILES["file"]["name"];
if(file_exists($newLocation)){
$newLocation .= randomString(10); // We append 10 new characters
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], $newLocation) ){
$filepath = str_replace("../img", "img", $newLocation); // make File Path starting with img/
}else{
echo $_FILES["file"]["name"]." unable to store";
}
The above code will check if the file exists. If yes, then a string of 10 random characters is appended to the file name and stored in the destination folder.
You didnt mention your problem but I think you have missed a point in your
if else
part. write it like this :
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$_FILES["file"]["name"] = $_FILES["file"]["name"].$your_new_number;
}
if( move_uploaded_file($_FILES["file"]["tmp_name"], "../img/catalog/" . $_FILES["file"]["name"]) ){
$filepath = "img/catalog/" . $_FILES["file"]["name"];
}else{
echo $_FILES["file"]["name"]." unable to store";
}
}
Using Dreamweaver CS6,I have a problem in uploading files.
The ERROR is "INVALID FILE"
This is my code:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Try Something like this:
if ($_FILES["file"]["error"]== 0) {
$upload_dir = dirname(__FILE__) . "/photos/";
if (file_exists($upload_dir)) {
if (is_writable($upload_dir)) {
$target = $upload_dir;
$newName=$_SESSION['theUsername'];
$target = $target . basename($newName);
$moved = move_uploaded_file($_FILES['file']['tmp_name'], "$target");
} else {
echo 'Upload directory is not writable<br>';
}
} else {
echo 'Upload directory does not exist.<br>';
}
}
Parse error: syntax error, unexpected T_VARIABLE in upload_file.php on line 44
The code worked until I added these lines :
Lines 42-44 :
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
Thanks it sorta worked. The script is for uploading images into a folder. That part of works but I cannot write the image path into the table. I have a table with two fields :
picid - auto incrementing primary key
path - varchar(60)
Any idea what I'm doing wrong? I've added the full script.
UPDATE. FULL CODE
<?php
include "connect.php";
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
$path = "uploads/" . $_FILES["file"]["name"];
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";
?>
You are missing you concatenation operator on line 44:
$Query = "INSERT INTO $Table_7 VALUES ('0','"$path"')";
should be
$Query = "INSERT INTO $Table_7 VALUES ('0','".$path."')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','$path')";
or
$Query = "INSERT INTO $Table_7 VALUES ('0','{$path}')";
the file upload script is below...the storing of the file name in the DB is working fine, but the file is not being moved to the proper directory. the "Avatars" file is located in the "/httpdocs/" directory. I have set the permissions to "777".
<?php
require('dbconfig.php');
//generate a random string
function generateRandomString($length = 40) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$customname = generateRandomString();
$newimagename = "$customname." . pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
header ('Location: /dashboard.php?filetype=invalid');
exit();
}
else
{
//echo "Upload: " . $_FILES["file"]["name"] . "<br>";
//echo "Type: " . $_FILES["file"]["type"] . "<br>";
//echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
//echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"avatars/" . $newimagename);
//echo "Stored in: " . "profile_videos/" . $newimagename;
$storedtoken = $_COOKIE['login_token'];
$mysqlicon = mysqli_connect($db_host, $db_username, $db_password, $db_name);
//identify the user by comparing tokens
$find_user_id = mysqli_query($mysqlicon, "SELECT * FROM logins WHERE token='$storedtoken'");
//grab the user's UUID
while ($row = mysqli_fetch_array($find_user_id)) {
$uuid = $row['userID'];
mysqli_query($mysqlicon, "UPDATE families SET avatarURL='avatars/$newimagename' where husbandID='$uuid' OR wifeID='$uuid'");
mysqli_close($mysqlicon);
}
header ('Location: /dashboard.php');
}
}
}
else
{
header ('Location: /dashboard.php?profile-video-upload=invalid');
mysqli_close($mysqlicon);
exit();
}
?>
I have a problem with my upload code it accepts invalid files and saves the filename in the database. I don't know what part of the code is wrong.
<?php
session_start();
if (!isset($_SESSION['LOGIN_STATUS'])) {
header('location:login.php');
}
?>
<?php
$allowedExts = array(
"gif",
"jpeg",
"jpg",
"png"
);
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 2000000) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
$image = $_FILES["file"]["name"];
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$image = $_FILES["file"]["name"];
}
}
} else if ($_FILES["file"]["name"] == null) {
$image = $_SESSION['IMAGE'];
} else {
echo "Invalid file";
}
?>
<?php
include("includes/dbConnect.php");
$Department = $_SESSION['DEPARTMENT'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$alias = $_POST['alias'];
$place = $_POST['place'];
$address = $_POST['address'];
$gender = $_POST['gender'];
$nationality = $_POST['nationality'];
$age = $_POST['age'];
$complexion = $_POST['complexion'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$build = $_POST['build'];
$haircolor = $_POST['haircolor'];
$pecularities = $_POST['pecularities'];
$other = $_POST['other'];
$clname = $_POST['clname'];
$cfname = $_POST['cfname'];
$cmname = $_POST['cmname'];
$cnumber = $_POST['cnumber'];
$caddress = $_POST['caddress'];
$relationship = $_POST['relationship'];
$description = $_POST['description'];
$lastseen = $_POST['lastseen'];
mysql_query("INSERT INTO `persons`(LastName,FirstName,MiddleName,Image,Alias,Place,Address,Gender,Nationality,Age,Complexion,Height,Weight,Build,HairColor, Pecularities, Other, CLastName, CFirstName, CMiddleName, ContactNumber, Relationship, Status, CAddress,Description,Department,lastseen) VALUES ('$lname','$fname','$mname','$image','$alias', '$place','$address','$gender','$nationality','$age','$complexion','$height','$weight','$build','$haircolor','$pecularities', '$other','$clname','$cfname','$cmname','$cnumber','$relationship','Missing','$caddress','$description','$Department','$lastseen')");
header('location:admin_search.php');
mysql_close($con);
?>
The code above verifies the user input but it also saves invalid file the file name only not the file itself. I don't know what part has the error it execute the query part but the verification for upload image accepts different file type but I have extension allowExts.
you need to put exit as the code below.
else {
echo "Invalid file";
exit;
}