Alert when uploading file with php - php

I have a file upload page that works but I'm trying to do some error alerts to choose if you want to replace or not.
This is my php file that does the upload
<?php
require ("connect.php");
$filename = "docs/".$_FILES['datafile']['name']."";
$d=explode(".",$_FILES['datafile']['name']);
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
} else {
$target_path = "docs/";
$target_path = $target_path . basename( $_FILES['datafile']['name']);
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['datafile']['name'])." has been uploaded";
$error = 0;
}
else
{
echo "There was an error uploading the file, please try again!";
$error = 1;
}
}
if ($error != 1)
{
$r1 = mysql_query("insert into full_dump (file_name) values ('".$_FILES['datafile']['name']."')")or die(mysql_error());
$file1 = "docs/".$_FILES['datafile']['name']."";
$lines = file($file1);
$count = count($lines);
$fp = fopen("docs/".$_FILES['datafile']['name']."","r");
$data=fread($fp,filesize("docs/".$_FILES['datafile']['name'].""));
$tmp=explode ("\n", $data);
for ($i=0; $i<$count; $i++)
{
$a=$tmp[$i];
$b=$i+1;
$r2 = mysql_query("update full_dump set field_".$b."='".$a."' where file_name='".$_FILES['datafile']['name']."'")or die(mysql_error());
}
echo"</br>";
echo "Uploading Complete</br>";
echo "Uploaded File Info:</br>";
echo "Sent file: ".$_FILES['datafile']['name']."</br>";
echo "File size: ".$_FILES['datafile']['size']." bytes</br>";
echo "File type: ".$_FILES['datafile']['type']."</br>";
}
?>
What I want to have is instead of
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
}
to have an alert if I would like to replace the file or not. If it's yes it would replace the file, delete the old record in the db and insert the new record. I it's no don't do nothing...or show a message "canceled by user". Could I have $error to be assigned a value for YES or NO on user choosing or not to replace?
UPDATE
This is the form page for upload.
<html>
<head>
<script language="Javascript">
function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
}
else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
}
else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "Uploading...";}
</script>
</head>
<body>
<form enctype=\"multipart/form-data\" method=\"POST\">
<input type="file" name="datafile" />
<input type="button" value="upload" onClick="fileUpload(this.form,'file_upload.php','upload'); return false;" >
<div id="upload"></div>
</form>
<?php
require("connect.php");
$result = mysql_query("SELECT * FROM full_dump")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Job number: ".$row['file_name']."</br>";
}
?>

you should do this with ajax... when you will send ajax request you will check if file exist or not .. if yes return eg -1 and ask user for relapsing ...
Enjoy :)

instead of using upload code on same page. do one thing, upload file by using ajax request. then check on backend site file is aleady exist or not and according to that show message as you like

Related

PHP multiple file upload will only upload the first 10 files selected (tried changing max_file_uploads) host says its my code?

When I try to upload more than 10 images via...
index.php
<?php include("file-upload.php"); ?>
<div>
<form action="" method="post" enctype="multipart/form-data" class="mb-3">
<div class="user-image mb-3 text-center">
<div class="imgGallery">
<!-- Image preview -->
</div>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
<label class="custom-file-label" for="chooseFile">Select image files</label>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
Upload Images
</button>
</form>
<!-- Display response messages -->
<?php if(!empty($response)) {?>
<div class="alert <?php echo $response["status"]; ?>">
<?php echo $response["message"]; ?>
</div>
<?php }?>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#chooseFile').on('change', function() {
multiImgPreview(this, 'div.imgGallery');
});
});
</script>
file-upload.php
// Database
include 'config/database.php';
if(isset($_POST['submit'])){
$uploadsDir = "uploads/";
$allowedFileType = array('jpg','png','jpeg');
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $id=>$val){
// Get files upload path
$uploadDate4file = date('dmYHis');
$fileName = $_FILES['fileUpload']['name'][$id];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$id];
$targetFilePath = $uploadsDir . $uploadDate4file . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
if(in_array($fileType, $allowedFileType)){
if(move_uploaded_file($tempLocation, $targetFilePath)){
$sqlVal = "('".$fileName."', '".$uploadDate."')";
} else {
$response = array(
"status" => "alert-danger",
"message" => "File could not be uploaded."
);
}
} else {
$response = array(
"status" => "alert-danger",
"message" => "Only .jpg, .jpeg and .png file formats allowed."
);
}
// Add into MySQL database
if(!empty($sqlVal)) {
$insert = $conn->query("INSERT INTO productimages (images, date_time) VALUES $sqlVal");
if($insert) {
$response = array(
"status" => "alert-success",
"message" => "Images successfully uploaded."
);
///Prints $rmfirstclassuk as array
echo "Images uploaded: ".$_FILES['fileUpload']['name'].", ";
echo "<pre>";
print_r ($_FILES['fileUpload']['name']);
echo "</pre>";
} else {
$response = array(
"status" => "alert-danger",
"message" => "Images couldn't be uploaded due to database error."
);
}
}
}
} else {
// Error
$response = array(
"status" => "alert-danger",
"message" => "Please select image files to upload."
);
}
}
database.php
$hostname = "HIDDEN";
$username = "HIDDEN";
$password = "HIDDEN";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Database connected successfully";
} catch(PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
...only the first 10 ever actually upload.
On reading other answers on here I have changed max_file_uploads to 50 on the PHP Configuration page and also tried ini_set('max_file_uploads', 50); on the page itself but try as I might I can't get it to upload more than 10 files.
Note: despite me trying to set the limit to 50 I only actually want to upload 12 at a time so I'm falling just 2 short!
So then I contacted my host with the issue who first tried upping my max_file_uploads to 100 and asked me to try again but when that didn't work have now said...
I've checked this further. It doesn't look to be an issue with the
server block I've both our mod security rule and server restrictions
but all looks to be allowing it. It does seem to be that the code is
preventing this from working.
but as much as I look over the code I can't see anything that would be preventing more than 10 files uploading, any ideas please?

Why Image Uploads to folder but not insert into mysql DB?

Hi Guys i got a Problem i upload an image to Upload Folder upload is working fine but he dont submit the value into mysql database and i really dont know where the failure ist here ist the whole code.
Unique Value is id from the user and the field for the image name is company_logo.
My dashboard code:
The Form:
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
JQuery Code
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').on('change', function() {
$("#preview").html('');
$("#preview").html('<div class="spinner"></div>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
And Finally The ajaximage.php
<?php
session_start();
ob_start();
$valid_user_id = trim($_SESSION["VALID_USER_ID"]);
if(isset($_SESSION["VALID_USER_ID"]) && !empty($valid_user_id))
{
include "database_connection.php"; //Include the database connection script
//Check the logged in user information from the database
$check_user_details = mysql_query("select * from `signup_and_login_table` where `email` = '".mysql_real_escape_string($_SESSION["VALID_USER_ID"])."'");
//Get the logged in user info from the database
$get_user_details = mysql_fetch_array($check_user_details);
//Pass all the logged in user info to variables to easily display them when needed
$user_id = strip_tags($get_user_details['id']);
$firstname = strip_tags($get_user_details['firstname']);
$lastname = strip_tags($get_user_details['lastname']);
$company = strip_tags($get_user_details['company']);
$company_logo = strip_tags($get_user_details['company_logo']);
$email = strip_tags($get_user_details['email']);
$passwd = strip_tags($get_user_details['password']);
// User Id for Image Upload
$session_id = strip_tags($get_user_details['id']);
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
else
{
//Send every user who tries to access this page directly without valid session to the login page.
//The login page is the door that every user needs to pass to this page
header("location: login.html");
}
?>
Use the following sql query:
INSERT INTO signup_and_login_table (company_logo, id) VALUES ('$actual_image_name', '$session_id')
You've made instead a UPDATE Query, which only updates already EXISTING rows.
Kind regards!
Try this query
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id=".$session_id);

upload error with weird error

when I'm upload a pdf it give me the code below. it doesn't show what kind of error like the file is too large or the file is not pdf instead it print out the form in the browser.
it's not the matter the file size, I've upload the file under 5 MB, and i already change the file size into 15 MB and set my php.ini more than 10MB and it's still the same. I think there's some problem on script that i missed. if it's error it supposes show error messages from error handler or from php it self rather than the code above.
<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
<div class="form-group has-error"><label for="title" class="control-label">Title</label><input type="text" name="title" id="title" class="form-control"><span class="help-block">Please enter the title!</span></div><div class="form-group has-error"><label for="description" class="control-label">Description</label><span class="help-block">Please enter the description!</span><textarea name="description" id="description" class="form-control"></textarea></div><div class="form-group has-error"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf"><span class="help-block">No file was uploaded.</span><span class="help-block">PDF only, 5MB Limit</span>
</div> <input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
</fieldset>
</form>
<!-- END CONTENT -->
</div><!--/col-9-->
</div><!--/row-->
</div><!--/container-->
</div><!--/wrap-->
<div id="footer">
<div class="container">
<p class="text-muted credit"><span class="pull-left">Site Map | Policies</span> <span class="pull-right">© Knowledge is Power - 2013</span></p>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
0
here's the PHP code:
<?php
// This page is used by an administrator to add a PDF to the site.
// This script is created in Chapter 5.
// Require the configuration before any PHP code as the configuration controls error reporting:
require('./includes/config.inc.php');
// If the user isn't logged in as an administrator, redirect them:
redirect_invalid_user('user_admin');
// Require the database connection:
require(MYSQL);
// Include the header file:
$page_title = 'Add a PDF';
include('./includes/header.html');
// For storing errors:
$add_pdf_errors = array();
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check for a title:
if (!empty($_POST['title'])) {
$t = escape_data(strip_tags($_POST['title']), $dbc);
} else {
$add_pdf_errors['title'] = 'Please enter the title!';
}
// Check for a description:
if (!empty($_POST['description'])) {
$d = escape_data(strip_tags($_POST['description']), $dbc);
} else {
$add_pdf_errors['description'] = 'Please enter the description!';
}
// Check for a PDF:
if (is_uploaded_file($_FILES['pdf']['tmp_name']) && ($_FILES['pdf']['error'] === UPLOAD_ERR_OK)) {
// Get a reference:
$file = $_FILES['pdf'];
// Find the size:
$size = ROUND($file['size']/1024);
// Validate the file size (5MB max):
if ($size > 15120) {
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
}
// Validate the file type:
// Create the resource:
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
// Check the file:
if (finfo_file($fileinfo, $file['tmp_name']) !== 'application/pdf') {
$add_pdf_errors['pdf'] = 'The uploaded file was not a PDF.';
}
// Close the resource:
finfo_close($fileinfo);
// Move the file over, if no problems:
if (!array_key_exists('pdf', $add_pdf_errors)) {
// Create a tmp_name for the file:
$tmp_name = sha1($file['name']) . uniqid('',true);
// Move the file to its proper folder but add _tmp, just in case:
$dest = PDFS_DIR . $tmp_name . '_tmp';
if (move_uploaded_file($file['tmp_name'], $dest)) {
// Store the data in the session for later use:
$_SESSION['pdf']['tmp_name'] = $tmp_name;
$_SESSION['pdf']['size'] = $size;
$_SESSION['pdf']['file_name'] = $file['name'];
// Print a message:
echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
} else {
trigger_error('The file could not be moved.');
unlink ($file['tmp_name']);
}
} // End of array_key_exists() IF.
} elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file.
switch ($_FILES['pdf']['error']) {
case 1:
case 2:
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
break;
case 3:
$add_pdf_errors['pdf'] = 'The file was only partially uploaded.';
break;
case 6:
case 7:
case 8:
$add_pdf_errors['pdf'] = 'The file could not be uploaded due to a system error.';
break;
case 4:
default:
$add_pdf_errors['pdf'] = 'No file was uploaded.';
break;
} // End of SWITCH.
} // End of $_FILES IF-ELSEIF-ELSE.
if (empty($add_pdf_errors)) { // If everything's OK.
// Add the PDF to the database:
$fn = escape_data($_SESSION['pdf']['file_name'], $dbc);
$tmp_name = escape_data($_SESSION['pdf']['tmp_name'], $dbc);
$size = (int) $_SESSION['pdf']['size'];
$q = "INSERT INTO pdfs (title, description, tmp_name, file_name, size) VALUES ('$t', '$d', '$tmp_name', '$fn', $size)";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
// Rename the temporary file:
$original = PDFS_DIR . $tmp_name . '_tmp';
$dest = PDFS_DIR . $tmp_name;
rename($original, $dest);
// Print a message:
echo '<div class="alert alert-success"><h3>The PDF has been added!</h3></div>';
// Clear $_POST:
$_POST = array();
// Clear $_FILES:
$_FILES = array();
// Clear $file and $_SESSION['pdf']:
unset($file, $_SESSION['pdf']);
} else { // If it did not run OK.
trigger_error('The PDF could not be added due to a system error. We apologize for any inconvenience.');
unlink ($dest);
}
} // End of $errors IF.
} else { // Clear out the session on a GET request:
unset($_SESSION['pdf']);
} // End of the submission IF.
// Need the form functions script, which defines create_form_input():
require('includes/form_functions.inc.php');
?><h1>Add a PDF</h1>
<form enctype="multipart/form-data" action="add_pdf.php" method="post" accept-charset="utf-8">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
<?php
create_form_input('title', 'text', 'Title', $add_pdf_errors);
create_form_input('description', 'textarea', 'Description', $add_pdf_errors);
// Add the file input:
echo '<div class="form-group';
// Add classes, if applicable:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo ' has-error';
} else if (isset($_SESSION['pdf'])) {
echo ' has-success';
}
echo '"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf">';
// Check for an error:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo '<span class="help-block">' . $add_pdf_errors['pdf'] . '</span>';
} else { // No error.
// If the file exists (from a previous form submission but there were other errors),
// store the file info in a session and note its existence:
if (isset($_SESSION['pdf'])) {
echo '<p class="lead">Currently: "' . $_SESSION['pdf']['file_name'] . '"</p>';
}
} // end of errors IF-ELSE.
echo '<span class="help-block">PDF only, 5MB Limit</span>
</div>';
?>
<input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
</fieldset>
</form>
<?php // Include the HTML footer:
include('./includes/footer.html');
?>

How to check if file field is empty in codeigniter?

I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link

MySql insert into query not working in PHP page

Hi i am new to PHP and MySql and I'm facing one problem:
I am having a page that allows users to upload an image and some details like their name and their email address to my database but the code that i have used is not working.
In fact, it is not adding data to my database but the image is being uploaded.
I also want to ask that is there any way to make all the form fields compulsory for users to fill in the form.
The html form is as below:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="content"><br><div align="center">
<form enctype="multipart/form-data" action="upload1.php" method="POST">
Your Full Name: <input type="text" name="name" maxlength="40"><br>
Your Image Please: <input type="file" name="photo"><br>
<input type="submit" value="Upload!">
</form>
</div>
</body>
</html>
And this is the code of upload1.php:
<?php
// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(00000000000000,99999999999999);
//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables
$new_file_name=$random_digit.$file_name;
//This is the directory where images will be saved
$target = "g/".$new_file_name;
$target = $target . basename( $_FILES['photo']['name']);
//This is our size condition
if ($photo_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
if (!($uploaded_type=="image/gif")) {
$ok=0;
}
if (!($uploaded_type=="image/jpg")) {
$ok=0;
}
if (!($uploaded_type=="image/png")) {
$ok=0;
}
if (!($uploaded_type=="image/bmp")) {
$ok=0;
}
if (!($uploaded_type=="image/jpeg")) {
$ok=0;
}
if ($ok=0)
{
Echo "Sorry your file was not uploaded";
}
else
{
//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$pic=($_FILES['photo']['name']);
$banner="/$target";
$url="xxxxxxxxxx";
$clicks='0';
// Connects to your Database
mysql_connect("xxxxxxxxxxx", "xxxxxxxxxxx", "xxxxxxxxx") or die(mysql_error()) ;
mysql_select_db("xxxxxxx") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO girls (name, banner, clicks, url, email) VALUES ('{$name}','{$banner}','{$clicks}','{$url}','{$email}') ");
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo " The file has been uploaded and renamed to '$target' your information has also been added to the database.<br>To view your image online visit www.facesnap.tk/$target ";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem in your upload. Be sure that you follow instructions.";
}
}
?>
You have to put '' only in varchars not in int values, if '{$clicks}' is an int in your database try remove the ''.
To make fields required now, do this in your upload1.php script:
session_start();
//connect to db
$errors = array();
//validate name
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Your name is required.';
}
else {
$name = mysql_real_escape_string(trim($_POST['name']));
}
//validate email
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Your email is required.';
}
else {
$email = mysql_real_escape_string(trim($_POST['email']));
$regex = '/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/';
//change the 128 to your email field length in your db
if (preg_match($regex, $email) && strlen($email) <= 128) {
$email = strtolower($email);
}
else {
$errors[] = 'Your email is not valid.';
}
}
//validate the file upload
if (!isset($_FILES['photo']) || empty($_FILES['photo'])) {
$errors[] = 'Your photo is required.';
}
else if ($_FILES['logo']['name'] == '') {
$errors[] = 'Your photo is required.';
}
else if (!file_exists($_FILES['photo']['tmp_name']) || !is_uploaded_file($_FILES['photo']['tmp_name'])) {
$errors[] = 'The file could not be uploaded, please try again later.';
}
else {
//validate the extention with your function is_img_ext()
if (is_img_ext($_FILES['photo']['name'])) {
$errors[] = 'The file you uploaded is not an image.';
}
//validate image size
if ($_FILES['photo']['size'] > 350000) {
$errors[] = 'The image you uploaded is too large.';
}
//if no errors and the file not exist move it to the target dir
if (empty($errors)) {
//generate a new filename for the image
$random_digit=rand(00000000000000,99999999999999);
$new_file_name = $random_digit.$file_name;
$target = "g/".$new_file_name;
$target = $target . basename( $_FILES['photo']['name']);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo " The file has been uploaded and renamed to '$target' your information has also been added to the database.<br>To view your image online visit www.facesnap.tk/$target ";
}
else {
echo "Sorry, there was a problem in your upload. Be sure that you follow instructions.";
}
}
}
if(!empty($errors)) {
$_SESSION['form_error'] = $errors;
header('Location: your_form.php');
die();
}
//your rest script
.....
function is_img_ext($filename) {
$ext = explode('.', $filename);
$ext = strtolower(end($ext));
if ($ext == jpeg || $ext == jpg || $ext == png || $ext == gif || $ext == bmp) {
return true;
}
else {
return false;
}
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_error'])) {
$errors = $_SESSION['form_error'];
unset($_SESSION['form_error']);
}
echo '<ul>';
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
echo '</ul>';
//your form here

Categories