I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.
I'm a new php learner and currently I'm trying to develop a job portal system. Everything else is running smoothly but I encounter problems when I need to prepare the php for uploading resume and image into the database. I have both the source code to upload image and pdf file separately but I don't know what to do if I have to combine them. Can anyone give me ideas of combining the php source code for both image and pdf file?
edit: I have a form where users need to upload their picture and attach their resume, hence the reason why I need to combine both of my resume and image source code below.
image.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM user WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/logo/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['image']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $imageFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['image']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($imageFileType == "jpg" || $imageFileType == "png") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: candidateform.php");
exit();
}
//sql new registration insert query
$sql = "INSERT INTO user(email, password,logo) VALUES ('$email', '$password', '$file')";
if($conn->query($sql)===TRUE) {
//If data inserted successfully then Set some session variables for easy reference and redirect to company login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
and here is the resume.php
resume.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your resume. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myResume.pdf will return pdf. If it was resume.doc then this will return doc.
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/resume/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql = "INSERT INTO users(email, password,resume, hash) VALUES ('$email', '$password','$file', '$hash')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
Thank you very much for every guidance, suggestions and helps in advance
From your question it appears that you want to upload multiple files (one PDF and one image) in a form and send it to PHP. There are multiple guides written on this:
Upload two files using PHP
Or for more verbosity, check:
http://findnerd.com/list/view/How-to-upload-two-separate-files-in-php/3268/
If you want to add multiple files to the same upload button, then check:
https://daveismyname.blog/upload-multiple-files-with-a-single-input-with-html-5-and-php
In terms of your code, you will need to do something like:
<input type="file" name="resume" />
<input type="file" name="image" />
Then in your PHP, you will need to do something like:
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/logo/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['image']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $imageFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($imageFileType == "jpg" || $imageFileType == "png") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
// Code for resume
//Folder where you want to save your resume. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myResume.pdf will return pdf. If it was resume.doc then this will return doc.
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/resume/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql = "INSERT INTO users(email, password,resume, hash) VALUES ('$email', '$password','$file', '$hash')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidateform.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidateform.php");
exit();
}
Please note that this can be further shortened and is not the best programming IMHO.
Finally I have figured this out and not only that, I can upload different type of files without confusing them anymore. I hope my answer can be off help to another. Here it is;
adduser.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user Actually clicked register button
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
// Code for image
$folder_dir = "uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
// Code for resume
$folder_dir = "uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf"|| $resumeFileType == "doc") {
if($_FILES['resume']['size'] < 500000) {
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
$hash = md5(uniqid());
//sql new registration insert query
$sql="INSERT INTO users (user_name, ic_no, gender, email, password, address, nationality, contactno, highest_qualification, university, major, current_position,
position_applied, current_monthly_salary, expected_monthly_salary, prefered_working_location, avaibility, malay, english, mandarin, other, logo, resume, hash, aboutme) VALUES
('$user_name', '$ic_no', '$gender', '$email', '$password', '$address', '$nationality', '$contactno', '$highest_qualification', '$university', '$major', '$current_position',
'$position_applied', '$current_monthly_salary', '$expected_monthly_salary', '$prefered_working_location', '$avaibility', '$malay', '$english', '$mandarin',
'$other', '$file', '$file1', '$hash', '$aboutme')";
if($conn->query($sql)===TRUE) {
// Send Email
// $to = $email;
// $subject = "Job Portal - Confirm Your Email Address";
// $message = '
// <html>
// <head>
// <title>Confirm Your Email</title>
// <body>
// <p>Click Link To Confirm</p>
// Verify Email
// </body>
// </html>
// ';
// $headers[] = 'MIME-VERSION: 1.0';
// $headers[] = 'Content-type: text/html; charset=iso-8859-1';
// $headers[] = 'To: '.$to;
// $headers[] = 'From: hello#yourdomain.com';
// //you add more headers like Cc, Bcc;
// $result = mail($to, $subject, $message, implode("\r\n", $headers)); // \r\n will return new line.
// if($result === TRUE) {
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
// $_SESSION['registerCompleted'] = true;
// header("Location: login.php");
// exit();
// }
// //If data inserted successfully then Set some session variables for easy reference and redirect to login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: candidate-register.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: candidate-register.php");
exit();
}
?>
I have this simplified situation :
<form action='process.php' method='post'>
<div class="dropzone no-margin">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</div>
</form>
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5
});
test2.php works just fine, it upload files dropped on the dropzone immediately. but, the problem is, I need to pass those file names of uploaded files to the form as hidden text input.
here's test2.php looks like :
<?php
$target_dir = "user/product/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm a beginner in javascript or jquery world. So, I really need your help to give me a clue how to pass the file names to the form as hidden text input so it can be written into database later on.
thank you so much and I really appreciate you help.
Try this :
there is method in Dropzone i.e sending that will use to send data before file is sent.if multiple files are uploaded then use sendingmultiple method.
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5,
sending:function (data, xhr, formdata) {
console.log("data :",data);
//here you can get file name from data variable.you can add that to your form by following line.
formdata.append('hidden field name', 'file name');
//you can add as much parameter you want to pass to your post data by formdata.append() function. That will add data to your form data.you can refer that value by using $_POST['hidden_field_name'] at PHP side.
}
});
Please check following link for detail :
http://www.dropzonejs.com/#events
I need to store different types of documents inside the project folder in single button click using Angular.js and PHP. I am explaining my code below.
var fileData={'image':file,'regdoc':regDocs,'compRegDoc':compRegDocs};
$scope.upload=Upload.upload({
url: 'php/uploadAll.php',
method:'POST',
file: fileData
}).success(function(data, status, headers, config) {
console.log('file',data);
}).error(function(data, status) {
console.log('err file',data);
})
uploadALL.php:
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
header("HTTP/1.0 401 Unauthorized");
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
header("HTTP/1.0 401 Unauthorized");
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
//$today=('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
move_uploaded_file($file_tmp,"../upload/".$file_name);
echo " uploaded file: " . "upload/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
header("HTTP/1.0 401 Unauthorized");
$errors[]="No image found";
print_r($errors);
}
?>
Here I have one image and the other two are .pdf/docx type files. When the user clicks the submit button these 3 files should be stored inside upload folder.
// use this code in php page...
it's used to upload all file
if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"upload/".$name);
}
$org_file_name = $_FILES['file1']['name'];
$file_size = $_FILES['file1']['size'];
$ext = strtolower(pathinfo($org_file_name, PATHINFO_EXTENSION));
$file_path = 'docs/';
$rand = rand(111,999);
if($ext == 'csv')
{
if(file_exists($file_path))
{
$file_path = 'docs/'.$org_file_name;
}
if(!move_uploaded_file($_FILES['file1']['tmp_name'],$file_path))
{
die ('<script> alert("file not uploaded successfully."); </script>');
}
}
else
{
die ('<script> alert("Uploaded only CSV files."); </script>');
How Do I rename CSV file when uploading and insert into database with renam and after insert show csv column headings in buttons
CSV headers (if present) are located right on the first line. So you can simply do:
$delimiter = ',';
$headers = fgetcsv(fopen($file_path, 'r'), $delimiter);
if (is_array($headers)) {
foreach($headers as $header) {
echo "<input type=\"button\" name=\"$header\"
value=\"$header\"/>'";
}
}
}
And to rename the file while moving, you should change the second parameter of move_uploaded_file() to the desired name. If you like, you can get a unique ID using sha1_file($_FILES['file1']['tmp_name']). It will also avoid duplicated storage of identical files.