How to upload file in PHP if not exist - php

I readed all about this in PHP.net but i can't find the solution. I know how to upload files into a new row in Mysql and PHP, but I don't know how to UPDATE a row and not delete the previous uploaded file if I don't upload anything.
For example, I have this form:
LOGO
Name of Business
Image 1
For example: I have this in MYSQL:
LOGO: /img/logo1.png
NAME: business1
IMAGE 1: ""
I want to do if I don't upload anything in LOGO and I'm editing this business (leaving in blank the input file of LOGO), do not upload my logo and SET a blank one ("").
This is the code of PHP:
define("MAX_SIZE", "2000");
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$errors = 0;
$image = $_FILES['foto0']['name'];
$image1 = $_FILES['foto1']['name'];
if ($image) {
$filename = stripslashes($_FILES['foto0']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$errors = 1;
$falloExtension = true;
} else {
$size = filesize($_FILES['foto0']['tmp_name']);
if ($size > MAX_SIZE * 2024) {
$errors = 1;
$falloLimite = true;
}
$image_name = uniqid() . '.' . $extension;
$newname = "img/detalles/" . $image_name;
$newname2 = "img/detalles/" . $image_name;
$copied = copy($_FILES['foto0']['tmp_name'], $newname2);
if($copied) {
$copiar = "UPDATE negocios SET logo='$newname' WHERE id=$numNegocio";
$resultado = $mysqli->query($copiar);
//header("location: ../anunciate.php");
} else {
//header("location: ../anunciate.php?fallo=true");
}
}
}
if ($image1) {
$filename = stripslashes($_FILES['foto1']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$errors = 1;
$falloExtension = true;
} else {
$size = filesize($_FILES['foto1']['tmp_name']);
if ($size > MAX_SIZE * 2024) {
$errors = 1;
$falloLimite = true;
}
$image_name = uniqid() . '.' . $extension;
$newname = "img/detalles/" . $image_name;
$newname2 = "img/detalles/" . $image_name;
$copied = copy($_FILES['foto1']['tmp_name'], $newname2);
if($copied) {
$copiar = "UPDATE galerias SET imagen1='$newname' WHERE negocios_id=$numNegocio";
$resultado = $mysqli->query($copiar);
//header("location: ../anunciate.php");
} else {
//header("location: ../anunciate.php?fallo=true");
}
}
}
if(isset($_POST['modificanegocio'])) {
$nombrePOST = $_POST['nombre'];
$categoriaPOST = $_POST['categoria'];
$direccionPOST = $_POST['direccion'];
$telefonoPOST = $_POST['telefono'];
$correoPOST = $_POST['correo'];
$descripcionPOST = $_POST['descripcion'];
$horarioPOST = $_POST['horario'];
$paginawebPOST = $_POST['paginaweb'];
$keywordsPOST = $_POST['keywords'];
$latPOST = $_POST['lat'];
$longPOST = $_POST['long'];
$facebookPOST = $_POST['facebook'];
$googlePOST = $_POST['google'];
$twitterPOST = $_POST['twitter'];
$insagramPOST = $_POST['insagram'];
$logoPOST = $_POST['logo'];
if($modificaNegocio = $mysqli->query("UPDATE negocios SET name = '$nombrePOST, logo = '$logoPOST', image1 = $image1POST WHERE id = $id")) {
$modifica = true;
} else {
$modifica = false;
}
}

I solved this spliting the MYSQL code:
$query = "UPDATE negocios SET nombre = '$nombrePOST'";
if($image != "" || $image != null) {
//NOW I WILL UPLOAD THE IMAGE HERE AND UPLOAD THE QUERY
}
$query .= " WHERE id = $id";
if($modificaNegocio = $mysqli->query($query)) {
$modifica = true;
} else {
$modifica = false;
}
}

Related

`mysqli_insert_id` PHP Class

I am creating a social site and I give people the option to upload one or more posts. That part works fine.
My problem is if someone uploads a post without pictures, then it gets submitted to a function and everything is fine. But if someone submits a post with pictures the only thing that's wrong is, I can't get the id of the post so I can put it in one of the columns for the image(s).
I know what the problem is. When I try to use procedural programming to upload the post and images, I get the id and everything is fine. But when I use OOP to upload the post and then try to get the id it doesn't work. No errors or anything the value in the column just comes out to 0. Can someone help me please ?
$post = new Post($con, $userLoggedIn);
$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING )));
$body = trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING )));
$post->submitPost($title, $body, 'none', $imageName);
if (!$errors) {
$id = mysqli_insert_id($con);
$stmt = $con->prepare("INSERT INTO post_images (image, post_id) VALUES (?, ?)");
$stmt->bind_param('si', $file_path, $id);
// Loop through each file
for( $i=0; $i < $file_count; $i++ ) {
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if ($file_size >= $maxsize) {
$errors = "Your file is too large";
} elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" &&
$imageFileType != "png" && $imageFileType != "gif") {
$errors = "File type not allowed.";
}
//Make sure we have a file path
if (!$errors /* && $file_tmp != "" */) {
$picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
$uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);
$file_path = "uploads/" . $picToUpload;
$stmt->execute();
}
}
}
Post.php:
public function submitPost($title, $body, $user_to, $imageName) {
$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING)));
$body = trim(strip_tags(filter_var($body, FILTER_SANITIZE_STRING)));
$check_empty = preg_replace('/\s+/', '', $body); //Deletes all spaces
$check_empty_title = preg_replace('/\s+/', '', $title); //Deletes all spaces
if($check_empty != "" || $check_empty_title != "" || $imageName != "") {
$body_array = preg_split("/\s+/", $body);
$title_array = preg_split("/\s+/", $title);
$body = implode(" ", $body_array);
$title = implode(" ", $title_array);
//Current date and time
$date_added = date("Y-m-d H:i:s");
//Get username
$added_by = $this->user_obj->getUsername();
//If user is on own profile, user_to is 'none'
if($user_to == $added_by) {
$user_to = "none";
}
//insert post
$query = $this->con->prepare("INSERT INTO posts (title, body, added_by, user_to, image)
VALUES (?, ?, ?, ?, ?)");
$query->bind_param("sssss", $title, $body, $added_by, $user_to, $imageName);
$query->execute();
$returned_id = mysqli_insert_id($this->con);
//Insert notification
if($user_to != 'none') {
$notification = new Notification($this->con, $added_by);
$notification->insertNotification($returned_id, $user_to, "profile_post");
}
//Update post count for user
$num_posts = $this->user_obj->getNumPosts();
$num_posts++;
$update_query = $this->con->prepare('UPDATE users SET num_posts = ? WHERE username = ?');
$update_query->bind_param("is", $num_posts, $added_by );
$update_query->execute();
$stopWords = "i you are gay am a about above brandon tisson";
$stopWords = preg_split("/[\s,]+/", $stopWords);
$no_punctuation = preg_replace("/[^a-zA-Z 0-9] +/", "", $body);
if (strpos($no_punctuation, "height") === false && strpos($no_punctuation, "width")
=== false && strpos($no_punctuation, "http") === false) {
$no_punctuation = preg_split("/[\s,]+/", $no_punctuation);
foreach ($stopWords as $value ) {
foreach ($no_punctuation as $key => $value2) {
if (strtolower($value) == strtolower($value2) ) {
$no_punctuation[$key] = "";
}
}
}
foreach ($no_punctuation as $value) {
$this->calculateTrend(ucfirst($value));
}
}
}
}
So in conclusion I'm trying to get the id of the post from a function in procedure style code.
You should return the post ID from submitPost(). Otherwise, if there are other inserts (such as in $notification->insertNotification()) they'll overwrite the ID returned by mysqli_insert_id($con).
It's also a little better to use $query->insert_id rather than mysqli_insert_id($this->con); since it's specific to that INSERT query, rather than the most recent INSERT on the same connection.
$post = new Post($con, $userLoggedIn);
$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING )));
$body = trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING )));
$id = $post->submitPost($title, $body, 'none', $imageName);
if (!$errors) {
$stmt = $con->prepare("INSERT INTO post_images (image, post_id) VALUES (?, ?)");
$stmt->bind_param('si', $file_path, $id);
// Loop through each file
for( $i=0; $i < $file_count; $i++ ) {
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if ($file_size >= $maxsize) {
$errors = "Your file is too large";
} elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" &&
$imageFileType != "png" && $imageFileType != "gif") {
$errors = "File type not allowed.";
}
//Make sure we have a file path
if (!$errors /* && $file_tmp != "" */) {
$picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
$uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);
$file_path = "uploads/" . $picToUpload;
$stmt->execute();
}
}
}
public function submitPost($title, $body, $user_to, $imageName) {
$title = trim(strip_tags(filter_var($_POST['title_post'], FILTER_SANITIZE_STRING)));
$body = trim(strip_tags(filter_var($body, FILTER_SANITIZE_STRING)));
$check_empty = preg_replace('/\s+/', '', $body); //Deletes all spaces
$check_empty_title = preg_replace('/\s+/', '', $title); //Deletes all spaces
if($check_empty != "" || $check_empty_title != "" || $imageName != "") {
$body_array = preg_split("/\s+/", $body);
$title_array = preg_split("/\s+/", $title);
$body = implode(" ", $body_array);
$title = implode(" ", $title_array);
//Current date and time
$date_added = date("Y-m-d H:i:s");
//Get username
$added_by = $this->user_obj->getUsername();
//If user is on own profile, user_to is 'none'
if($user_to == $added_by) {
$user_to = "none";
}
//insert post
$query = $this->con->prepare("INSERT INTO posts (title, body, added_by, user_to, image)
VALUES (?, ?, ?, ?, ?)");
$query->bind_param("sssss", $title, $body, $added_by, $user_to, $imageName);
$query->execute();
$returned_id = $query->insert_id;
//Insert notification
if($user_to != 'none') {
$notification = new Notification($this->con, $added_by);
$notification->insertNotification($returned_id, $user_to, "profile_post");
}
//Update post count for user
$num_posts = $this->user_obj->getNumPosts();
$num_posts++;
$update_query = $this->con->prepare('UPDATE users SET num_posts = ? WHERE username = ?');
$update_query->bind_param("is", $num_posts, $added_by );
$update_query->execute();
$stopWords = "i you are gay am a about above brandon tisson";
$stopWords = preg_split("/[\s,]+/", $stopWords);
$no_punctuation = preg_replace("/[^a-zA-Z 0-9] +/", "", $body);
if (strpos($no_punctuation, "height") === false && strpos($no_punctuation, "width")
=== false && strpos($no_punctuation, "http") === false) {
$no_punctuation = preg_split("/[\s,]+/", $no_punctuation);
foreach ($stopWords as $value ) {
foreach ($no_punctuation as $key => $value2) {
if (strtolower($value) == strtolower($value2) ) {
$no_punctuation[$key] = "";
}
}
}
foreach ($no_punctuation as $value) {
$this->calculateTrend(ucfirst($value));
}
}
}
return $returned_id;
}

How to save an image to the database with a path file

I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.

Update image with information in php

I've been looking for a code to update my image from the database from youtube and here in stackoverflow. But I cant seem to make it work. The image can get updated but the title and the body cannot be edited. please help.
im usig it with php and phpmyadmin
this is the code i've been trying to make the update:
if (isset($_POST['update'])) {
$id = $_POST['editid'];
$edtitle = $_POST['edittitle'];
$edbody = $_POST['editmyTextarea'];
$file = $_FILES['editpgupload'];
$filename = $file['name'];
$fileTmp = $file['tmp_name'];
$filesize = $file['size'];
$fileerror = $file['error'];
$filetype = $file['type'];
$fileExt = explode('.', $filename);
$fileActExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActExt, $allowed)) {
if ($fileerror === 0) {
if ($filesize < 1000000) {
$filenamenew = uniqid('', true).".".$fileActExt;
$fileds = '../../../image/upload/'.$filenamenew;
move_uploaded_file($fileTmp, $fileds);
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody', pg_image = '$filenamenew' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}else{
// echo "your image is too large";
header("Location: ../index.php?error=imagetoolarge");
}
}else{
// echo "There was an error uploading your file";
header("Location: ../index.php?error=errorupload");
}
}else{
// echo "You can not upload this file";
header("Location: ../index.php?error=cannotupload");
}
}
it only updates the image but the title and the body stay the same. it cannot be edited. this should be able to update the title, body and the image.
patients_guide structure
CREATE TABLE `patients_guide` (
`pg_id` int(11) NOT NULL AUTO_INCREMENT,
`pg_title` varchar(100) NOT NULL,
`pg_body` text NOT NULL,
`pg_image` varchar(100) NOT NULL,
PRIMARY KEY (`pg_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf
I got it.
For someone that has the same problem as me here is the code:
if (isset($_POST['update'])) {
$id = $_POST['editid'];
$edtitle = $_POST['edittitle'];
$edbody = $_POST['editmyTextarea'];
$file = $_FILES['editpgupload'];
$filename = $file['name'];
$fileTmp = $file['tmp_name'];
$filesize = $file['size'];
$fileerror = $file['error'];
$filetype = $file['type'];
//remove old image
unlink('../../../image/upload/'.$row['pg_image']);
$fileExt = explode('.', $filename);
$fileActExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActExt, $allowed)) {
if ($fileerror === 0) {
if ($filesize < 1000000) {
$filenamenew = uniqid('', true).".".$fileActExt;
$fileds = '../../../image/upload/'.$filenamenew;
move_uploaded_file($fileTmp, $fileds);
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody', pg_image = '$filenamenew' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}else{
// echo "your image is too large";
header("Location: ../index.php?error=imagetoolarge");
}
}else{
// echo "There was an error uploading your file";
header("Location: ../index.php?error=errorupload");
}
}else{
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}
}

Optional file upload fields

I am trying to make my two file uploads optional when inserting data into mySQL db, and uploading the files to my server. When I uploading both files to a new entry, the upload is successful. If I don't upload 1 or both files, I receive an error. Thank you so much for your help.
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/session.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php
session_start();
if($_SESSION["login_user"] != true) {
echo("Access denied!");
exit();
}
?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/validation_functions.php");?>
<?php
if (isset($_POST['submit'])) {
// Process the form
$visible = mysqli_prep($_POST["visible"]);
$homepage = mysqli_prep($_POST["homepage"]);
$type = mysqli_prep($_POST["type"]);
$publication_name = mysqli_prep($_POST["publication_name"]);
$publication_url = mysqli_prep($_POST["publication_url"]);
$month = mysqli_prep($_POST["month"]);
$date = mysqli_prep($_POST["date"]);
$year = mysqli_prep($_POST["year"]);
$title = mysqli_prep($_POST["title"]);
$author = mysqli_prep($_POST["author"]);
$summary = mysqli_prep($_POST["summary"]);
$full_text = mysqli_prep($_POST["full_text"]);
$tag_1 = mysqli_prep($_POST["tag_1"]);
$tag_2 = mysqli_prep($_POST["tag_2"]);
$tag_3 = mysqli_prep($_POST["tag_3"]);
$tag_4 = mysqli_prep($_POST["tag_4"]);
$tag_5 = mysqli_prep($_POST["tag_5"]);
$tag_6 = mysqli_prep($_POST["tag_6"]);
$tag_7 = mysqli_prep($_POST["tag_7"]);
$image = rand(1000,100000)."-".$_FILES['image']['name'];
$image_loc = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES['image']['type'];
$image_folder="images/";
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_folder="files/";
$image_new_size = $image_size/1024;
$file_new_size = $file_size/1024;
$new_image_name = strtolower($image);
$new_file_name = strtolower($file);
$final_image=str_replace(' ','-',$new_image_name);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($image_loc,$image_folder.$final_image))
if(move_uploaded_file($file_loc,$file_folder.$final_file))
$query = "INSERT INTO `news` (";
$query .= "visible, homepage, type, publication_name, publication_url, month, date, year, title, author, summary, full_text, tag_1, tag_2, tag_3, tag_4, tag_5, tag_6, tag_7, image, image_type, image_size, file, file_type, file_size ";
$query .= ") VALUES (";
$query .= " '{$visible}', '{$homepage}', '{$type}', '{$publication_name}', '{$publication_url}', '{$month}', '{$date}', '{$year}', '{$title}', '{$author}', '{$summary}', '{$full_text}', '{$tag_1}', '{$tag_2}', '{$tag_3}', '{$tag_4}', '{$tag_5}', '{$tag_6}', '{$tag_7}', '{$final_image}','{$image_type}','{$image_new_size}', '{$final_file}','{$file_type}','{$file_new_size}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Item created.";
redirect_to("manage_content.php");
} else {
// Failure
//$_SESSION["message"] = "Item creation failed.";
//redirect_to("new_news.php");
echo "Error: " . $query . "<br>" . $result->error;
}
} else {
// This is probably a GET request
redirect_to("new_news.php");
}
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
you can use this and hence get rid of your error.Hope this helps you.
$final_image = $image_type = $image_new_size = $final_file = $file_type = $file_new_size = "";
if($_FILES) {
$image = rand(1000,100000)."-".$_FILES['image']['name'];
$image_loc = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES['image']['type'];
$image_folder="images/";
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_folder="files/";
$image_new_size = $image_size/1024;
$file_new_size = $file_size/1024;
$new_image_name = strtolower($image);
$new_file_name = strtolower($file);
$final_image=str_replace(' ','-',$new_image_name);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($image_loc,$image_folder.$final_image))
if(move_uploaded_file($file_loc,$file_folder.$final_file))
}

Trying to determine file types

I would be glad if you help me with this PHP code .
I made an upload form which only supports .pdf , .docx and .rtf files .
the file gets uploaded but it can't determine if the file type is pdf , docx or rtl or just non of them . Any solutions to fix this?
well I did a few searches in stackoverflow , some of the members did same as i do but mine still doesn't work.
This code gets a file from an input . It uploads the file to server , on a specific folder , and then it saves the file's name on database.
<?php
function query($q)
{
$dbconnection = mysql_connect('127.0.0.1' , 'root' , '');
$database = mysql_select_db('hire_requests');
mysql_set_charset("utf8",$dbconnection);
$res = mysql_query($q,$dbconnection);
mysql_close($dbconnection);
return $res;
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$error = '';
$alarm = false;
$success = false;
$changedname = '';
$name = '';
$lastname = '';
$phonenumber;
$nnumber;
$type ='';
$mail = '';
$resume;
$type = '';
$notify = '';
$nameErr= "";
$mailErr = "";
$resumeErr = "";
$nnumberErr = "";
$lastnameErr = "";
$phonenumberErr = "";
$notsentErr = "";
$sizeErr = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$phonenumber = mysql_real_escape_string($_POST['phonenumber']);
$nnumber = mysql_real_escape_string($_POST['nnumber']);
$mail = mysql_real_escape_string($_POST['mail']);
if(isset($_FILES['resume']))
{
$filename = $_FILES['resume']['name'];
$filesize = $_FILES['resume']['size'];
$filetype = $_FILES['resume']['type'];
$filetmp = $_FILES['resume']['tmp_name'];
if($_FILES['resume']['error'] !== 0)
{
$alarm = true;
}
$AllowedTypesArray = array('docx' , 'rtf' , 'pdf');
$changedname = 'Rayka_' . rand(1000,9000) . '_' . '5SV4DFS_A245DFA' . '_' . time() . '_' . $name;
$info = pathinfo($filename , PATHINFO_EXTENSION);
if($alarm = true)
{
}
if($filetype == 'application/pdf' )
{
$type = '.pdf';
}
if($filetype == 'application/msword' )
{
$type = '.docx';
}
if($filetype == 'application/rtf')
{
$type = '.rtf';
}
if(!$type)
{
$resumeErr = "file's type is not supported";
}
if(!in_array($info , $AllowedTypesArray)) //checks if filetype is pdf , rtl or docx and also , checks if the file is less than 2 mbs or not .
{
$error = "file's type is not supported";
$alarm = true;
}
if($filesize > 2097152)
{
$sizeErr ="Your file must be less than 2 Mbs";
}
$path = dirname(__FILE__).'/_ufile/'.$changedname . $type;
var_dump($path);
if(!move_uploaded_file($_FILES['resume']['tmp_name'] , $path) )
{
$alarm = true;
$notsentErr = 'File was not sent';
}
}
if(!isset($_FILES['resume']))
{
$resumeErr = 'attachment is not chosen';
$alarm = true;
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST["name"]))
{
$nameErr = "Enter your name";
}
else
{
$name = test_input($_POST["name"]);
}
}
if(empty($_POST['lastname']))
{
$lastnameErr = "Enter your last name";
}
else {
$lastname = test_input($_POST['lastname']);
}
if(empty($_POST['phonenumber']))
{
$phonenumberErr = "Enter your phone number";
}
else
{
$phonenumber = test_input($_POST['phonenumber']);
}
if(empty($_POST['nnumber']))
{
$nnumberErr = "Enter your second phone number";
}
else
{
$nnumber = test_input($_POST['nnumber']);
}
if(empty($_POST['mail']))
{
$mailErr = "enter your email address";
}
else
{
$mail = test_input($_POST['mail']);
}
if((!$nameErr) && (!$lastnameErr) && (!$mailErr) && (!$phonenumberErr) && (!$nnumberErr) && (!$notsentErr) && (!$sizeErr))
{
$query = "INSERT INTO users (`id`,`name`, `lastname`, `phonenumber`, `nnumber`, `mail`, `resume`) VALUES (NULL , \"$name\",\"$lastname\",\"$phonenumber\",\"$nnumber\",\"$mail\",\"$changedname\")";
$notify = "Successful";
$success = true;
$insert = query($query);
$error2 = mysql_error();
}
}
?>
Here what i use (i changed for you needs) :
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['resume']['tmp_name']);
$ok = false;
switch ($mime) {
case 'application/pdf':
case 'application/msword':
case 'text/pdf':
case 'application/rtf':
case 'application/x-rtf':
case 'text/richtext':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$ok = true;
break;
default:
die();
}
Here the complete mime type list : https://www.sitepoint.com/web-foundations/mime-types-complete-list/

Categories