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

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

Related

How to Prevent Form Resubmission when page is refreshed or back button is clicked

On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code
developerUpload.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}
if(isset($_COOKIE['username'])){
if($_SERVER['REQUEST_METHOD'] =="POST"){
$price = addslashes(trim($_POST['price']));
$description = addslashes(trim($_POST['description']));
if(!empty($price) && !empty($description)){
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
echo '<br>'.$userid;
$pack_id = rand();
//Check file 1
if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){
$file1 = null;
}else{
$target1 = "devFiles/";
$target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
$file1 = addslashes(trim($_FILES['file1']['tmp_name']));
}
//Check file 2
if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){
$file2 = null;
}else{
$target2 = "devFiles/";
$target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
$file2 = addslashes(trim($_FILES['file2']['tmp_name']));
}
//Check file 3
if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){
$file3 = null;
}else{
$target3 = "devFiles/";
$target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
$file3 = addslashes(trim($_FILES['file3']['tmp_name']));
}
//Check file 4
if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){
$file4 = null;
}else{
$target4 = "devFiles/";
$target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
$file4 = addslashes(trim($_FILES['file4']['tmp_name']));
}
//Check file 5
if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){
$file5 = null;
}else{
$target5 = "devFiles/";
$target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
$file5 = addslashes(trim($_FILES['file5']['tmp_name']));
}
//Check video
if($_FILES['video']['error'] !== UPLOAD_ERR_OK){
$video = null;
$videoName = null;
}else{
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
$video = addslashes(trim($_FILES['video']['tmp_name']));
$videoName = addslashes(trim($_FILES['video']['name']));
}
if(file_exists($target_file1)
or file_exists($target_file2)
or file_exists($target_file3)
or file_exists($target_file4)
or file_exists($target_file5)
or file_exists($target_file)){
header("Location: developerUpload.php?invalid");
exit;
}
if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
&& move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
&& move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
&& move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
&& move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
header("Location: submission_successful.php?");
die();
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
}
}
}else {
header("Location: developerLogin.php");
}
?>
submission_successful.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
header("Location: developerUpload.php?invalid");
}
if(isset($_COOKIE['username'])){
echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';
}else{
header("Location: developerLogin.php");
}
?>
I was searching around for days and finally found something. IF you use a HTML command it will remove any input the user put when the user goes back. Because my problem was when the user goes back after be redirected, their information was still there but if you use
<form method="post" enctype="multipart/form-data" autocomplete="off">
it removes everything so it kinda helps. The user will still be allowed to go back but at least now they can't resubmit the data.
Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get
Use a session variable like this
$_SESSION["post_id"] = "";
if($_POST) {
if($_POST["post_id"] != $_SESSION["post_id"]) {
$_SESSION["post_id"] = $_POST["post_id"];
// do database submission here
}
}
This sets a session variable and if they resubmit the form it won't post the data twice.

php- File Type Restriction not working

I am trying to restrict Image file type to only JPG,PNG,JPEG but this script is not allowing any file (even if its above mentioned formats) and the NO FILE selected part is also not working. though I am selecting the file it's still alerting you have to select profile picture(the JS alert msg mentioned in the code) what's wrong in the code?
if(isset($_POST['submit'])){
//this part is part of the HTML form. please neglect this. this's working
$user = $_POST['username'];
$pass = $_POST['password'];
$email =$_POST['email'];
if($_FILES["profpic"]["tmp_name"] =="") { //even $_FILES['profpic']['name']=="" is not working
echo "<script>alert('You have to upload Profile Picture.');</script>";
exit();
}
//$check = getimagesize($_FILES["profpic"]["tmp_name"]);
if(getimagesize($_FILES["profpic"]["tmp_name"])) {
echo "<script>alert('Invalid Image.');</script>";
exit();
}
if ($_FILES["profpic"]["size"] > 1000000) {
echo "<script>alert('Your Image is too big,Maximum Image Size is 1MB');</script>";
exit();
}
$type = $_FILES['profpic']['type'];
$allowedImageType = array('image/jpg','image/png','image/jpeg');
function imageType($image){
global $allowedImageType;
if(in_array($image,$allowedImageType))
return true;
else
return false;
}
if(!imageType($type)) {
echo "<script>alert('Only JPG,JPEG,PNG Image Allowed!');</script>";
exit();
}
//the code if everything went right-------------------------
$sql = $conn->query("INSERT INTO users(id,username,password,email) VALUES('','$user','$pass','$email')");
$id = $conn->insert_id;
$picname = "$id.jpg";
move_uploaded_file($_FILES['profpic']['tmp_name'], "images/$picname");
echo "<script>document.getElementById('noti').innerHTML='Account Creation Successful. <a href=\'login.php\'>Click here</a> to Login';</script>";
}

Alert when uploading file with 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

php - form include image upload

I try to make a form to include image upload. let say I have table participant which I would like to insert to:
INSERT INTO `participant`(`Matric`, `Name`, `IC`, `Address`, `Tel`, `Phone`,
`Email`, `Phone_Ref`, `Institute`, `Course`, `Pic_Participant`, `Exp_Work`)
VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],
[value-8],[value-9],[value-10],[value-11],[value-12])
What I want to do is to insert data and upload an image. Its attribute which is Pic_Participant.
I search about upload using ajax Ajax Image Upload and Resize with jQuery and PHP . Then I think the flow, fill the form then upload image in same page, then after upload image the data for image send to db, but the form does not submit yet. How can I get attribute from table image to add in table participant?
Please help me. I'm new about this.
EDIT
i try this code but get an error: Undefined variable
<?php
session_start();
include 'dbconnect.php';
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "upload/";
//ERROR START HERE
$Matric = $_POST['Matric'];
$Name = $_POST['Name'];
$IC = $_POST['IC'];
$Address = $_POST['Address'];
$Tel = $_POST['Tel'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Phone_Ref = $_POST['Phone_Ref'];
$Institute = $_POST['Institute'];
$Course = $_POST['Course'];
/* $fname = $_POST['fname'];
$lname = $_POST['lname']; */
$image = $_FILES['image'];
$Exp_Work =$_POST['Exp_Work'];
//ERROR END HERE
$Matric = mysql_real_escape_string($Matric);
$Name = mysql_real_escape_string($Name);
$IC = mysql_real_escape_string($IC);
$Address = mysql_real_escape_string($Address);
$Tel = mysql_real_escape_string($Tel);
$Phone = mysql_real_escape_string($Phone);
$Email = mysql_real_escape_string($Email);
$Phone_Ref = mysql_real_escape_string($Phone_Ref);
/* $Total_sales = addslashes($_POST['Total_sales']);
$Date = addslashes($_POST['Date']); */
/* $Cer_name = mysql_real_escape_string($Cer_name); */
$Institute = mysql_real_escape_string($Institute);
$Course = mysql_real_escape_string($Course);
/* $Cat_name = addslashes($_POST['Cat_name']);
$Product_name = addslashes($_POST['Product_name']); */
/* $fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname); */
$image['name'] = mysql_real_escape_string($image['name']);
$Exp_Work = mysql_real_escape_string($Exp_Work);
$TARGET_PATH .= $image['name'];
if ( $Matric == "" ||$Name == "" ||$IC == "" ||$Address == "" ||$Tel == "" ||$Phone == "" ||$Email == "" ||$Phone_Ref == "" || $Institute == "" || $Course == ""|| $image['name'] == ""|| $Exp_Work == "" )
{
$_SESSION['error'] = "All fields are required";
echo "All fields are required";
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
echo"You must upload a jpeg, gif, or bmp";
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
echo"A file with same name exists already";
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into participant (Matric, Name, IC, Address, Tel, Phone, Email, Phone_Ref, Institute, Course, image, Exp_Work) values ('$Matric','$Name','$IC','$Address','$Tel','$Phone','$Email','$Phone_Ref','$Institute', '$Course','" . $image['name'] . "','$Exp_Work')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
echo"Imgage uploaded successfully";
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: fail.php");
exit;
}
?>
As I read your question, you want to upload the image already using the tutorial / code you found and then submit the form separately when the image already has been uploaded.
To know where you can find your image after the file upload, you have two options:
Have the image upload return the file path when the upload is complete and include that variable in your form (as a hidden input for example);
Store the image path in a session variable so that when you submit the data fields, you can access that variable to get the information of the image.
Edit: You need to check the documentation of the Form Plugin for more details, but you can return something from your upload php script. You could for example echo the file name and then you would have it available in your success function:
function afterSuccess(return_value) {
console.log(return_value); // here you have what was echoed out by php
$('#UploadForm').resetForm(); // reset form
$('#SubmitButton').removeAttr('disabled'); //enable submit button
}
If I got it correctly what you want is to insert image into (probably MYSQL) database.
You could achieve this by using base64_encode() of image binary data and insert resulting plaintext in database.
$image = 'path/to/image/image.png';
$imagefordbs = base64_encode($image);
/*now your image is ready to be stored in database*/
However, this method has downsides since base64_encode() takes up about 33% more then original memory, some time to process input binary, and there is dedicated datatype for this kind of requirements in mysql - BLOB.

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