Laravel 8 - Upload multiple files at the same time with different inputs - php

I have many input files with different names, but when I upload only one file is saved, that's the reason why?
_form.blade.php :
<input type="file" name="tampak_depan" class="form-control"/>
<input type="file" name="tampak_kiri_depan" class="form-control"/>
<input type="file" name="tampak_kanan_depan" class="form-control"/>
<input type="file" name="tampak_belakang" class="form-control"/>
Controller.php :
tampak depan :
$tampak_depan = $request->file('tampak_depan');
if($tampak_depan !== null) {
$art->tampak_depan = time().'_tampak_depan_'.$tampak_depan->getClientOriginalName();
}
if($tampak_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_depan->move($path,$art->tampak_depan) == false) {
print $tampak_depan->getErrorMessage();
die;
}
}
tampak kiri depan :
$tampak_kiri_depan = $request->post('tampak_kiri_depan');
if($tampak_kiri_depan !== null) {
$art->tampak_kiri_depan = time().'tampak_kiri_depan'.$tampak_kiri_depan->getClientOriginalName();
}
if($tampak_kiri_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kiri_depan->move($path,$art->tampak_kiri_depan) == false) {
print $tampak_kiri_depan->getErrorMessage();
die;
}
}
tampak kanan depan :
$tampak_kanan_depan = $request->post('tampak_kanan_depan');
if($tampak_kanan_depan !== null) {
$art->tampak_kanan_depan = time().'tampak_kanan_depan'.$tampak_kanan_depan->getClientOriginalName();
}
if($tampak_kanan_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kanan_depan->move($path,$art->tampak_kanan_depan) == false) {
print $tampak_kanan_depan->getErrorMessage();
die;
}
}
tampak belakang :
$tampak_belakang = $request->post('tampak_belakang');
if($tampak_belakang !== null) {
$art->tampak_belakang = time().'tampak_belakang'.$tampak_belakang->getClientOriginalName();
}
if($tampak_belakang !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_belakang->move($path,$art->tampak_belakang) == false) {
print $tampak_belakang->getErrorMessage();
die;
}
}

Looks like you're using the right function in the first example, but the wrong function in the others.
In 'tampak depan', you're using $request->file(), but in the others you're using $request->post().
Change those to $request->file() and they should work.

Related

echo don't return me full string on production but work in developpement

When I run my website on localhost with Xampp, I haven't this bug but on my ovh server this doesn't work.
I explain,
I have a ajax function who wait a filename for inject him in balise .
I call my controller who genere the filename and echo him.
So I have a var php who containe a string like "main-2765b74ec.jpg".
I need echo this var for inject him in my balise.
On localhost this work perfectly, but in my ovh server the echo print just "main-2765b74ec".
So that is my question, why echo don't give me the complete string like in my localhost env.
Maybe a problem with ovh ?
EDIT: Same problem with print()
php call with ajax :
public function tmp($request, $response) {
$type = $request->getParam('name');
$uploadedFile = $request->getUploadedFiles()['img'];
$directory = dirname(dirname(__DIR__)) . '/public/img/tmp';
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile($directory, $uploadedFile, $type);
echo $filename;
}
}
above : If I do a var_dump this return the complete string with the extension and if I do a var_dump follow by an echo, the echo return the complete string but I must do more traitement in my js for hide all the var_dump part.
php who genere name :
public function moveUploadedFile($directory, UploadedFile $uploadedFile, $type = 'any') {
$extension = strtolower(pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION));
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
if ($type == 'main') {
$filename = $type.'-'.$filename;
if ($dh = opendir($directory)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..' && explode('-', $file)[0] == 'main') {
unlink($directory.'/'.$file);
}
}
closedir($dh);
}
} else if ($type != 'any') {
$filename = $type;
}
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
ajax :
function uploadFile(file) {
let id = $(file).attr('id').substr(5)
if (id != ('tmp')) {
$('#form_'+id).submit()
} else {
let formData = new FormData()
let params = $('#form_tmp').serializeArray()
formData.append('img', $(file)[0].files[0])
formData.append(params[0].name, params[0].value)
$('#label').html("Uploading...").css({'background-color': 'transparent', 'cursor': 'wait'})
$('#file_tmp').prop("disabled", true)
// for (var pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]) }
$.ajax({
url: '../image/tmp',
method: 'post',
data: formData,
contentType: false, //'text/plain'
processData: false
}).done((filename) => {
closeOverlay()
if (params[0].value == 'main') {
$('.container-main-img').html('<img src="../img/tmp/'+filename+'" id="tmpImgMain">').css({'height':'auto', 'border': 'none'})
} else {
$('.img-list').append(`<div class="img-block">
<div class="toolbar img">
<div>
<button class="btn-tmp-img-up"><i class="icon-up-dir"></i></button>
<button class="btn-tmp-img-down"><i class="icon-down-dir"></i></button>
</div>
<button class="btn-tmp-img-delete"><i class="icon-cancel"></i></button>
</div>
<img src="../img/tmp/`+filename+`">
</div>`)
ajustBtnTool()
}
})
}
}
When returning from a function called by Ajax, you must use 'exit' or 'die()', so add either one of these straight after your line 'echo $filename;'.

how to make a file based user login page

this thing really blown my mind up i want to design a page with a text box where my clients can enter their username and by using php i want to tell the page to check if there is a username such as that in a file named locationn.html if existed create a cookie and let him in another page if not add a new line to the file containing the user name entered.
this is my code in this code "unamec" is the name of the cookie and "$user" is the user name and "umname" is the name of the username text box which its value is sent to the page itself using a post method.
<?php
if(isset($_POST["uname"])){
$user=$_POST["uname"];
$pass=$_POST["passs"];
$see=file_get_contents("locationn.html");
$lines=explode("\n",$see);
foreach($lines as $line){
if($line == $user){
setcookie("unamec",$user,time()+86400,"/");
echo '<script>window.location="main.html";</script>';
}
}
}
?>
I can help you with the storage and retrieval of a username from a file. You could adapt this and couple with session management, to achieve your aims.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = isset($_POST['username']) ? $_POST['username'] : null;
if($username !== preg_replace('/[^a-zA-Z0-9]+/', '', $username))
throw new Exception('Invalid username.');
$userStore = new UserStore('/tmp/creds.txt');
if(! $userStore->isStored($username)) {
if($userStore->storeUsername($username)) {
echo $username . ' stored.';
}
} else {
echo $username . ' is on file.';
}
}
class userStore
{
public $fp;
public $filename;
public function __construct($filename)
{
$this->filename = $filename;
if(!file_exists($this->filename))
file_put_contents($this->filename, null);
$this->fp = fopen($this->filename, "r+");
}
public function isStored($username) {
$username_exists = false;
if(! $size = filesize($this->filename))
return false;
$contents = fread($this->fp, $size);
$lines = array_filter(explode("\n", $contents));
foreach($lines as $line) {
if(trim($line) == $username) {
$username_exists = true;
break;
}
}
return $username_exists;
}
public function storeUsername($username)
{
$fp = $this->fp;
if (flock($fp, LOCK_EX)) {
fwrite($fp, "$username\n");
fflush($fp);
flock($fp, LOCK_UN);
} else {
return false;
}
return true;
}
}
?>
<form method='POST'>
<input type='text' name='username'>
<input type='submit' value='login'>
</form>

Why is strpos() not working when searching this .txt file?

So I am trying to collect and store emails addresses in a text file and is is working other than it not recognising if an address has already been submitted. It will add an address to the text file even if it is already present. Thank you for your insight.
<?php
function showForm() {
echo '
<form method="post" action="">
Email Address: <input type="email" name="email"> <br />
<input type="submit" value="Submit" name="submit">
</form>
';
}
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
$pos = strpos($logcontents, $email);
if ($pos === true) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
} else {
showForm();
}
?>
strpos() returns the position at which the string has been found, or false.
Checking $pos === true can never succeed because the return value of strpos() cannot be true.
Try if ($pos !== false) { ... instead.
Your this line:
$pos = strpos($logcontents, $email);
returns position of the string found, not boolean value.
AND
if ($pos === true) {
may contain 0 as position.
You should change this to:
if ($pos != false) {
Reference
strpos won't ever return true. It can return position zero which will be interpreted by PHP as false unless you use strict comparison.
if ($pos !== false)

Adding ajax function in validation

Again, I am working with this form validation. Everything works fine and I like the way it works. Unless I want to add ajax function to check weather username already exist from database. Any body can help? I am not really familiar with ajax and Jquery.
This the php consist of html form, index.php :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo " Form submited....!!!! <br/>";
echo '<br/> Username = '.$_POST['username'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body >
<form method="POST" action="">
<div class="form-group">
<label for="txtUserName" class="col-lg-3 control-label">Username :</label>
<div class="col-lg-9">
<input type="text" id="txtUserName" name="username" placeholder="Create Username" >
<p><small id="elmUserNameError" class="errorMsg"></small></p>
</div>
</div>
<button type="button" onClick="return check_form(this.form);">Submit</button>
</form>
<script>
function check_form(form) {
if(validateForm(form) === true ) {
form.submit();
return true;
}
}
function validateForm(theForm) {
with(theForm) {
return (
isNotEmpty(txtUserName, "Please Create username!", elmUserNameError)
&& isUsernameMinMax(txtUserName, 6,10, "Username must between 6 - 10 characters", elmUserNameError)
&& isUpperCase(txtUserName, "Create Username with UPPERCASE!", elmUserNameError)
&& isMatching(txtUserName, "Username must be UPPERCASE with number and underscore. No white space allowed", elmUserNameError)
// problem here......
&& isUserExis(txtUserName, "Username already exist!", elmUserNameError)
);
return false;
}
return true;
}
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim() !== "");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUsernameMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUpperCase(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[^a-z]*$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isMatching(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\w+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
// Show errMsg on errElm, if provided.
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.innerHTML = errMsg;
}
// Set focus on Input Element for correcting error, if provided.
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.add("errorBox"); // Add class for styling
inputElm.focus();
}
} else {
// Clear previous error message on errElm, if provided.
if (errElm !== undefined && errElm !== null) {
errElm.innerHTML = "";
}
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.remove("errorBox");
}
}
}
</script>
</body>
</html>
I need to add this function but I have no idea how to return ajax call to validate the result. For example here, as I manually write, when user enter 'DADADA', it will return error 'Username already exist!'.
function isUserExis(inputElm, errMsg, errElm){
// maybe ajax call here....
var isValid = (inputElm.value.trim() !== "DADADA");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
This my php file to be called, check_username.php :
<?php
include('config.php'); // class and configuration
$users = new Users($db);
if($_REQUEST)
{
$username = $_REQUEST['username'];
if ($users->UsernameExist($username) === true) {
echo 'That Username already exist!';
}
}
?>

CCJavascript Return True Page Refresh Error

I am writing a form validation code in PHP. Below is the code.
the element with id #questionSubmit is a form with 6 text fields (code, question, answer, option1, option2, option3, option4, option5) and a submit button.
<form id="createQuestionForm" action="" method="POST">
Question Code: <input id="code" class="createQuestionTextBox1" type="text" name="questionCode">
Question Name: <input id="question" class="createQuestionTextBox1" type="text" name="questionName">
Correct Answer: <input id="answer" class="createQuestionTextBox1" type="text" name="correctAnswer">
Option 1: <input id="option1" class="createQuestionTextBox2" type="text" name="option_1">
Option 2: <input id="option2" class="createQuestionTextBox2" type="text" name="option_2">
Option 3 <input id="option3" class="createQuestionTextBox2" type="text" name="option_3">
Option 4 <input id="option4" class="createQuestionTextBox2" type="text" name="option_4">
Option 5 <input id="option5" class="createQuestionTextBox2" type="text" name="option_5">
<input type="Submit" id="questionSubmit" value="Create Question"></input>
</form>
function SubmitFormCreationData() {
$("#questionSubmit").click(function() {
if (CheckCodeField($("#code").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#question").val()) == false) {
return false;
} else if (CheckCorrectAnswerField($("#answer").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option1").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option2").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option3").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option4").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option5").val()) == false) {
return false;
} else {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize());
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
return false;
});
}
function CheckAnswerNameFields(value) {
var isValid = true;
if (value == "")
isValid = false;
if (value == null)
isValid = false;
for(LCV = 0;LCV <= (count(value)-1); LCV++) {
if(value[LCV] == "'")
isValid = false;
if(value[LCV] == '"')
isValid = false;
}
return isValid;
}
function CheckCodeField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 100000)
isValid = false;
if(value > 999999)
isValid = false;
return isValid;
}
function CheckCorrectAnswerField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 1)
isValid = false;
if(value > 5)
isValid = false;
return isValid;
}
function isInteger(possibleInteger) {
return /^[\d]+$/.text(possibleInteger);
}
Now if the first field is entered correctly then the output is as wanted, false is returned. However if the first field is entered correctly and the rest are blank then the page refreshes, however it should be returning false because I check if the question and option fields are blank. Why is this happening?
$("#questionSubmit").click(function() {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize(), function(data){
if(data=='SUCCESS'){
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
else{
var alertx='';
for(i=0;i<data.split('-').length-1;i++) alertx += data.split('-')[i].toString()+"\n";
alert(alertx);
}
});
return false;
});
insertnewquestion.php
extract($_POST);
$errors = '';
if(!in_array($questionCode,range(100000,999999))) $errors .= 'Invalid code-';
if(!in_array($correctAnswer,range(1,5))) $errors .= "Invalid answer-";
for($i=1;$i<=6;$i++){
$var = $i==6 ? $questionName : ${'option_'.$i};
if(empty($var) || strstr($var,'"') || strstr($var,"'")) $errors.= "Invalid ".($i==6?"question name":"option $i")."-";
}
echo $errors=='' ? 'SUCCESS':$errors;
Try and write if work correctly

Categories