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
Related
I have this code:
<?php
if (isset ($_FILES['UploadFileField'])){
$UploadName = $_FILES['UploadFileField'] ['name'];
$UploadName = mt_rand (100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField'] ['tmp_name'];
$UploadType = $_FILES['UploadFileField'] ['type'];
$FileSize = $_FILES['UploadFileField'] ['size'];
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
if(($FileSize > 1250000)){
die ("Error - File to Big");
}
if(!$UploadTmp) {
die ("No File Selected");
}
else {
move_uploaded_file($UploadTmp, "Upload/$UploadName");
}
header('Location: /index.php');
exit;
}
?>
This code works, but I need insert a message of successful after that is done Upload file.
Thank you!
if (move_uploaded_file($UploadTmp, "Upload/$UploadName")) {
$message = "Successfully inserted";
header('Location: /index.php?success=true&message='.$message);
}
else {
$message = "Something went wrong";
header('Location: /index.php?success=false&message='.$message);
}
use the if condition for the move_uploaded_file function it will help you. And get the success, message from index file
if ($_GET['success'] == true) {
echo $_GET['message'];
}
Or you can use the SESSION
You can add a parameter when you redirect like :
header('Location: /index.php?upload=true');
And in your index check if you get the parameter and display a message if it's the case and if it's where you want to display the message. You can check also with if else statement if the upload work and change the var to sent
I'v been trying to make a content insert page with php and here is my code
<?php // Initialize variables to null.
$title =""; // Sender Name
$author =''; // Sender's email ID
$date =date('d-m-y'); // Subject of mail
$desc="";//meta description
$keywords="";//meta keywords
$content =""; // Sender's Message
$category="";//chosen category
$pattern1="";//preg_match pattern
$nameError ="";
$contentError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
$img_dir=$_SERVER["DOCUMENT_ROOT"] . '/practise/grafitti/images/';
$img;
if(isset($_POST['submit'])) { // Checking null values in message.
//check and assign title title
if(empty($_POST["title_post"])){
$nameError = "A title is required";
errors($nameError);
exit();
}
else{
if (preg_match("/^(\w|\s)$/",$_POST['title_post']))
{
$titleError = "Only letters,numbers and white space allowed";
errors($titleError);
}else{
$title=$_POST['title_post'];
}
}
// Checking null values inthe content.
if (empty($_POST["content_post"]))
{
$contentError = "You have not posted any content.<br/> Please do to proceed";
errors($contentError);
exit();
}else {
$content=$_POST["content_post"];
}
//check and assign category
if(!empty($_POST["categories_post"]))
{
$category=$_POST["categories_post"];
}
//Chexk and assign authors name
if (!empty($_POST["author_post"]))
{
$author=$_POST["author_post"];
}
//check and assign value of description
if (!empty($_POST["desc_post"]))
{
$desc=$_POST["desc_post"];
}
//check and assign keywords
if (!empty($_POST["keywords_post"]))
{
$keywords=$_POST["keywords_post"];
}
//process images
if(isset($_FILES["img_post"])){
echo "good to go";
$name=$_FILES["img_post"]["name"];
$tmp_name=$_FILES["img_post"]["tmp_name"];
$type=$_FILES["img_post"]["type"];
$size=$_FILES["img_post"]["size"];
$img_dir;
if(upload($name,$type,$size,$tmp_name,$img_dir)){
if(move_uploaded_file($tmp_name,$img_dir.$name)){
echo "success";
}else{echo php_info;}
$img_upload_Success="File was uploaded successfully";
errors($img_upload_Success);
}else{
$img_upload_Error="File could not be uploaded";
errors($img_upload_Error);
exit();
}
}
echo $title."<br/>";
echo $author."<br/>";
echo $desc."<br/>";
echo $keywords."<br/>";
echo $category."<br/>";
echo $date."<br/>";
}
// Function for filtering input values.function test_input($data)
function errors($err){
echo "<script>
var err='$err'
alert(err)
</script>
";
}
#validate file upload
function upload($fl_name,$fl_type,$fl_size,$fl_tmp_name,$dir){
#check to see if the file is an image or not
if($fl_type!="image/jpeg" && $fl_type!="image/png" && $fl_type!="image/jpg" && $fl_type!="image/gif"){
$typeError="The file type you uploaded is not supported";
errors($fl_type);
exit();
}
#check file size limits
if($fl_size>512000){
$sizeError="Size of the file is too big. Should be at least 500KB";
errors($sizeError);
exit();
}
if(file_exists($dir.$fl_name)){
$existError="Sorry. File already exists";
errors($existError);
exit();
}
}
?>
the problem is,when I want to validate with the file upload. If I don't upload anything the the code still assumes that my $_FILES['img_post'] isset and it therefore runs the code that satisfies that conditions.
Moreover, if I manage to set the $_FILE variable, it still won't upload.Its like the
if(upload($name,$type,$size,$tmp_name,$img_dir))
returns a false value but the upload() is executed.Can someone please tell me how to handle the isset problem and at least a way to show the error causing the file not to be uploaded
you can try this.
if($_FILES['img_post']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['img_post']['error']];
// do whatever with the error message
}
For more details you can refer this.
Use this condition below:
if($_FILES['img_post']['error'] == 0){
//uplode file
}
This will check is it's empty or file been selected. If selected, then it will only upload the file.
change this code
if(isset($_FILES["img_post"])){
to
if(isset($_FILES["img_post"]["tmp_name"])){
Use below code:-
if(isset($_FILES["img_post"]["tmp_name"]) && $_FILES["img_post"]["tmp_name"] != ''){
//uplode file
}
OR
if(!empty($_FILES["img_post"]["tmp_name"])){
//uplode file
}
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>";
}
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);
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.