ron tornambe ron tornambe - 6 months ago 6
Javascript Question

Why can't PHP find an element that is reachable using JS or jQuery?

I have been staring at this problem for hours. For the life of me, I cannot find an explanation. PHP cannot find the userid and subgenre elements. All the others are found.

HTML Form

<form action="php/writers.php" method="post" enctype="multipart/form-data" target="upload-target" onsubmit="startUpload();" >
<h1>Writers</h1>
<p>
<input id="title" name="title" class="form-control" placeholder="Title" required autofocus="true" />
</p>
<p>
<label for="work-type" class="fixed50">Form:</label>
<select id="work-type" name="work-type">
<option value="fiction">Fiction</option>
<option value="non-fiction">Non-Fiction</option>
<option value="screenplay">Screenplay</option>
<option value="play">Play</option>
</select>
</p>
<p>
<p>For an explanation of the genres shown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a></p>
<label for="genre" class="fixed50">Genre:</label>
<select id="genre" name="genre">
</select>
</p>
<p>
<label for="subgenre" class="fixed50">Sub-Genre:</label>
<select id="subgenre" name="subgenre">`
<option value="0">None</option>
</select><br/>
</p>
<p>
<label for="nbrPages" class="fixed50">Number of pages:</label>
<input id="nbrPages" name="nbrPages" required style="width: 48px" placeholder="Pages" /><br/>
</p>
<p>For a limied time, writers can upload their sysnopsis or query letterr for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="tips">The objective of a sysnopsis or query letter is to entice enablers into requesting your manuscript.
It must be brief and to the point, now more than twp pages and, of course very well written.
</div>
<div class="form-group">
<p id="file-warning">Your synopsis or query letter must be a PDF file.
<a target="_blank" href="https://www.freepdfconvert.com/" target="_blank">Free file conversion to PDF</a></p>
</div>
<div class="form-group">
<label for="file2upload">PDF to Upload</label>
<input id="file2upload" name="file2upload" type="file" required value="File to upload" />
</div>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="writers-submit" class="btn btn-default">Submit</button>
</div>
<input id="userid" name="userid" type="hidden" />
<iframe id="upload-target" name="upload-target" src="#" ></iframe>
</form>


The following JS function writes the correct values to the console.

JS

function startUpload() {
$("#userid").val(window.localStorage.getItem('user-id'));
console.log("jquery val=" + $("#subgenre").val());
console.log("getElementById value=" + document.getElementById('subgenre').value);
showMessage(1, "Uploading...");
return true;
}


console.log


userid=51 VM39985:122

jquery val=0 VM39985:123

getElementById value=0

/php/writers.php:1 POST 500 (Internal Server
Error)


PHP

$uploadDirectory = '/home/deje/public_html/writers-tryst/uploads/'; //specify upload directory ends with / (slash)
require_once "dbconnect.php";
$result = 0;
$File_Name = basename($_FILES['file2upload']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name

var_dump($_REQUEST);
$target_path = $uploadDirectory . $NewFileName;

if (@move_uploaded_file($_FILES['file2upload']['tmp_name'], $target_path)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $uploadDirectory . $NewFileName);
finfo_close($finfo);
if ($mime_type != 'application/pdf') {
unlink($UploadDirectory . $NewFileName);
$data = array('File MUST be a PDF!');
$result = 0;
} else $result = 1;
}
if (!isset($_REQUEST["title"]) || empty(trim($_REQUEST["title"])))
throw new Exception('You must enter a title.');
else {
$title = filter_var(trim($_REQUEST["title"]), FILTER_SANITIZE_STRING);
$title = htmlspecialchars_decode($title, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || empty(trim($_REQUEST["userid"])))
throw new Exception('Userid is missing.');
else {
$userrid = filter_var(trim($_REQUEST["userid"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userid, ENT_QUOTES);
}
if (!isset($_REQUEST["work-type"]) || empty(trim($_REQUEST["work-type"])))
throw new Exception('You must enter a work type.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
if (!isset($_REQUEST["genre"]) || empty(trim($_REQUEST["genre"])))
throw new Exception('You must enter a title.');
else {
$genre = filter_var(trim($_REQUEST["genre"]), FILTER_SANITIZE_STRING);
$genre = htmlspecialchars_decode($genre, ENT_QUOTES);
}
if (!isset($_REQUEST["subgenre"]) || empty(trim($_REQUEST["subgenre"])))
throw new Exception('You must enter a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["subgenre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
if (!isset($_REQUEST["nbrPages"]) || empty(trim($_REQUEST["nbrPages"])))
throw new Exception('You must enter the number of pages your work contains.');
else {
$nbrPages = filter_var(trim($_REQUEST["nbrPages"]), FILTER_SANITIZE_STRING);
$nbrPages = htmlspecialchars_decode($nbrPages, ENT_QUOTES);
}

$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare(
"INSERT Writers(fkAccounts, Title, WorkType, Genre, SubGenre, Filename)
VALUES(:fk, :title, :worktype, :genre, :subgenre, :filename)"
);

$stmt->bindParam(':fk', $userid, PDO::PARAM_INT, 10);
$stmt->bindParam(':title', $title, PDO::PARAM_STR, 255);
$stmt->bindParam(':worktype', $worktype, PDO::PARAM_STR, 30);
$stmt->bindParam(':genre', $genre, PDO::PARAM_STR, 100);
$stmt->bindParam(':subgenre', $subgenre, PDO::PARAM_STR, 100);
$stmt->bindParam(':filename', $NewFileName, PDO::PARAM_STR, 30);

$stmt->execute();


echo "<script type='text/javascript'>stopUpload(" . $result . ");</script>";
sleep(1);
exit();

$data = array();
require_once 'cookies.php';

if (isset($_REQUEST['files'])) {
$error = false;
$files = array();

foreach ($_FILES as $file) {
if ($file["size"] > $filesize_limit) {
// $data = array('Maximum file size (' . $filesize_limit . ') exeeded.');
// $error = true;
} else {
$File_Name = basename($file['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name

if (move_uploaded_file($file['tmp_name'], $UploadDirectory . $NewFileName)) {
$files[] = $UploadDirectory . $file['name']; //$NewFileName; //
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $UploadDirectory . $NewFileName);
//$data = array('Mime-Type (' . $mime_type . ')');
finfo_close($finfo);
if ($mime_type != 'application/pdf') {
unlink($UploadDirectory . $NewFileName);
$data = array('File MUST be a PDF!');
$error = true;
};
} else {
$error = true;
}
}
}
if ($error) {
$data = array('error' => $data);
} else {
$data = array('files' => $files);
}
} else {
$data = array('success' => 'Form was submitted', 'formData' => $_REQUEST);
};

echo json_encode($data);


PHP error_log


[17-May-2016 00:59:49 UTC] PHP Notice: Undefined variable: userid in
/home/deje/public_html/writers-tryst/php/writers.php on line 34

[17-May-2016 00:59:49 UTC] PHP Stack trace:

[17-May-2016 00:59:49 UTC] PHP 1. {main}()
/home/deje/public_html/writers-tryst/php/writers.php:0

[17-May-2016 00:59:49 UTC] PHP Fatal error: Uncaught exception
'Exception' with message 'You must enter a sub-genre.' in
/home/deje/public_html/writers-tryst/php/writers.php:49

Stack trace:

0 {main} thrown in /home/deje/public_html/writers-tryst/php/writers.php on line 49



Answer

Firstly, you're passing a non-existing variable to a function, on these two lines

$userrid = filter_var(trim($_REQUEST["userid"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userid, ENT_QUOTES);

Where $userid isn't defined when you do the call to htmlspecialchars_decode, it's a typo where you probably intended to type

$userrid = filter_var(trim($_REQUEST["userid"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userrid, ENT_QUOTES);

The second error is that PHP is throwing on this line

if (!isset($_REQUEST["subgenre"]) || empty(trim($_REQUEST["subgenre"])))
    throw new Exception('You must enter a sub-genre.');       

That's because the condition is thruthy.
The select element with the name subgenre has a value of 0, and in PHP empty(trim("0")); is thruthy, hence the if condition enters, and the exception is thrown.

Comments