I am attempting to create a page that will register information. I also need to be able to upload an image to the form, but when I add the image it gives me an error when I attempt to upload saying the file is not an image. I have attempted to change the parameters of what it will take as far as .jpeg, .png, etc. Can anyone see what I am doing wrong with the uploading?
if ($valid) {
$filetype = pathinfo($_FILES['profileimg']['name'], PATHINFO_EXTENSION);
if ((($filetype == "gif") or ($filetype == "jpeg") or ($filetype == "png")) and $_FILES['profileimg']['size'] < 200000) {
if ($_FILES['profileimg']['error'] > 0) {
$valid = false;
$fileError = $_FILES['profileimg']['error'];
$imageError = "<p class='error'>Return code: $fileError<br>";
switch ($fileError) {
case 1:
$imageError .= 'The file exceeds the uploads_max_filesize setting in php.ini.</p>';
break;
case 2:
$imageError .= 'The file exceeds the max_file_size setting in the HTMl form.</p>';
break;
case 3:
$imageError .= 'The file was only partially uploaded.</p>';
break;
case 4:
$imageError .= 'No file was uploaded.</p.';
break;
case 5:
$imageError .= 'The temporary folder does not exist.</p>';
break;
default:
$imageError .= 'something unexpected happened.</p>';
break;
}
} else {
$imageError = $_FILES['profileimg']['name'];
$file = "uploads/$imageName";
$fileInfo = "<p>Upload: $imageName<br>";
$fileInfo = "Type: " . $_FILES['profileimg']['type'] . "<br>";
$fileInfo .= "Size: " . ($_FILES['profileimg']['size'] / 1024) . "Kb<br>";
$fileInfo .= "Temp file: " . $_FILES['profileimg']['tmp_name'] . "</p>";
if (file_exists("$files")) {
$imageError = "<span class='error'>$imageName already exists.</span>";
$valid = false;
} else {
move_uploaded_file($_FILES['profileimg']['tmp_name'], $file);
if (move_uploaded_file($_FILES['profileimg']['tmp_name'], $file) == true) {
$fileInfo .= "<p>Your file has been uploaded. Stored as: $files</p>";
$query = "INSERT INTO 'membership' VALUES (default, '$first', '$last', '$username', '$email', '$password', '$imageName');";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (!$result) {
die(mysqli_error($conn));
} else {
$row_count = mysqli_affected_rows($conn);
if ($row_count == 1) {
$memberID = mysqli_insert_id($conn);
$loggedIn = true;
$msg = "<p>Record inserted</p>";
} else {
$msg = "<p>Insert failed</p>";
}
}
} else {
$imageError .= '<p><span class="error">Your file could not be uploaded.';
}
}
}
} else {
$imageError .= '<span class="error">Invalid file. This is not an image.</span>';
$valid = false;
}
}
}
Related
I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}
other queries working through the foreach loop.but file upload for 1st index of array.this is not multiple file upload.i wanna upload same file in different names for each users.
foreach($_POST['groupmem'] as $user){
//Some Queries
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
$extension2 = pathinfo($filename2, PATHINFO_EXTENSION);
$file2 = $_FILES['proposal']['tmp_name'];
$size2 = $_FILES['proposal']['size'];
if (!in_array($extension2, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file2, $destination2)) {
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
} else {
echo "Failed to upload file.";
}
}
}
you can not do move_uploaded_file inside the loop
$user1 = $_POST['groupmem'][0];
$filename1 = str_replace(" ", "_","{$user1}.{$_FILES['proposal']['name']}");
$destination1 = '../img/proposal/' . $filename1;
$extension1 = pathinfo($filename1, PATHINFO_EXTENSION);
$file1 = $_FILES['proposal']['tmp_name'];
$size1 = $_FILES['proposal']['size'];
if (!in_array($extension1, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file1, $destination1)) {
foreach($_POST['groupmem'] as $user){
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
if ($user <> $user1) {
if (!copy($destination1, $destination2)) echo "failed to copy $file...\n";
}
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
}
} else {
echo "Failed to upload file.";
}
}
I am used to writing AJAX using the following structure, where I would end up sending variables to PHP
function requestToggle(type, user, elem) {
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "request_system.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText == "request_sent") {
_(elem).innerHTML = 'OK Request Sent';
} else if (ajax.responseText == "unrequest_ok") {
_(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type=" + type + "&user=" + user);
}
The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.
Here is the PHP
<?php
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
echo $result;
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
exit();
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
exit();
}
$sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
//delete old pic if set
if($avatar != ""){
$picurl = "users/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
//move file from temp folder to users folder
$moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
if ($moveResult != true) {
$result = "File upload failed";
echo $result;
exit();
}
include_once("image_resize.php");
//replace original file with resized version
$target_file = "users/$log_username/$db_file_name";
$resized_file = "users/$log_username/$db_file_name";
$wmax = 400;
$hmax = 600;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
//header("location: user.php?u=$log_username");
$result = "upload_success";
echo $result;
exit();
}
?>
UPLOAD FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);
Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:
$files= $_REQUEST['files'];
I am working on php upload and i have an issue on how to automatically rename a file it does exist already in file folder. Could you give me any road or tips about it? thanks
here is my full code - the code is for testing purpose only
$destination = 'C:/upload_test/';
$max=75200;
if (isset($_POST['upload'])) {
if (isset($_FILES['image']['tmp_name'])) {
$fileTaille= $_FILES['image']['size'];
if ($fileTaille==true) {
if ($fileTaille > $max) {
echo "Your file is too large, select a file smaller than". " ".$fileTaille;
exit(include 'form.php');
}
}
else {
echo "No file selected";
exit(include 'form.php');
}
}
$file_type=getimagesize($_FILES['image']['tmp_name']);
if ($file_type==true) {
echo "File is an image - " .$file_type["mime"]." ";
}
else{
echo "Could not get file type";
}
$fileType = exif_imagetype($_FILES['image']['tmp_name']);
$allowed = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
if (!in_array($fileType, $allowed)) {
echo "File type not accepted, Only JPEG file allowed";
exit(include 'form.php');
}
$sanitize_file = preg_replace("/[^A-Z0-9\.\_-]/i", " ", $_FILES["image"]["name"]);
$fileName = $recipient . basename($recipient);
if (file_exists($fileName)) {
echo "File already exist";
exit(include 'form.php');
}
}
if (isset($_FILES['image']['tmp_name'])) {
$result = move_uploaded_file($_FILES['image']['tmp_name'], $recipient . $sanitize_file);
if ($result == true) {
echo "file moved "." ";
}else
{
echo "Could not move filed";
}
$permission = chmod($$recipient . $sanitize_file, 0644);
if ($permission==false) {
echo "No permission to the file";
}
else
{
echo "permission given";
}
}
How can I import 200k data faster?
And when I importing csv (delimited by comma) file using online, I got 403 error, and it inserted 200-400 data only. Also when I try to import it using localhost (xampp) i got
"Exception EAccessViolation in module xampp-control.exe at 001AA712.
Access violation at address 005AA712 in module 'xampp-control.exe'.
Read of address 00000042"
And the SQL Database connection is gone.
This is the code I used.
set_time_limit(0);
ignore_user_abort(true);
$file = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$temp = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if( ! $file)
{
$data['error'] = "Please select a file!";
}
else if($type != "application/vnd.ms-excel" && $type != "application/octet-stream")
{
$data['error'] = "Invalid file type!";
}
else
{
$newname = $file." - ".date("Ymd His");
move_uploaded_file($temp, "uploads/".$newname);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "uploads/".$newname;
if( ! file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if( ! $file)
{
echo "Error opening data file.";
exit;
}
$size = filesize($csvfile);
if(!$size)
{
echo "File is empty.";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$row = 1;
$data_imported = 0;
$file3 = fopen($csvfile,"r");
$total_file_count = (count(file(FCPATH."/".$csvfile)) - 2);
$i = 0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
while($datas = fgetcsv($file3, 10000, ","))
{
$i++;
ob_implicit_flush(true);
if($row == 1)
{
// Ignore 1st line
}
else
{
$row1 = isset($datas[0]) ? $datas[0] : "";
.
.
to
.
.
$row33 = isset($datas[32]) ? $datas[32] : "";
if($i == 200 OR $total_file_count == $data_imported)
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
);";
}
else
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
),";
}
if($i == 200 OR $total_file_count == $data_imported)
{
$this->QModel->query($insert);
$i=0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
}
$data_imported++;
}
$row++;
}
fclose($file3);
echo "Success imported ".number_format($data_imported)." data.";
Any ideas?
Thank you.