How can I raise an error in my Django form? - php

I have a PHP script in a server that returns {"available":true} or {"available":false}, depending on whether the email address is available or not. Here is the code:
<?php
$servername = "localhost";
$username = "root";
$password = "mysqlpass";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username FROM testtable";
$result = $conn->query($sql);
$query = $_GET['query'].'#groupdesignace.com';
$arr = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$arr[] = $row['username'];
}
if (in_array($query, $arr)) {
$output = array('available' => false);
echo json_encode($output);
} else {
$output = array('available' => true);
echo json_encode($output);
}
} else {
echo "0 results";
}
$conn->close();
?>
On a different server where users are requesting their email address through a form, I am using Django. I have written the following code to check whether the email is available, if not, it should raise an error. Here is the code:
class RequestEmailAddressForm(forms.Form):
email = forms.CharField(label='Email', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
def clean_email(self):
email = self.cleaned_data.get('email')
if email:
import requests
payload = {'query': email}
r = requests.get('http://172.16.16.172/check_email.php', params=payload)
result = r.json()
print r.url
status = result['available']
if status == False:
raise forms.ValidationError('This login name is unavailable!')
return email
Here is my view that is handling the form:
def request_email_address(request):
if request.method == "POST":
form = RequestEmailAddressForm(request.POST)
if form.is_valid():
data = form.cleaned_data
# do something here
else:
pass
return HttpResponseRedirect('/core/home/')
else:
form = RequestEmailAddressForm()
return render(request, "core/request_email_address.html", { "form": form })
However, the form is going to the submitted page but it is not raising validation error. What am I doing wrong?

You are doing nothing on if form is invalid. When ValidationError is raised django sets form.errors dict with data about what went wrong during validation. Read more https://docs.djangoproject.com/en/1.10/ref/forms/validation/
def request_email_address(request):
if request.method == "POST":
form = RequestEmailAddressForm(request.POST)
if form.is_valid(): # <- form validation is called on this line
data = form.cleaned_data
# do something here
# do redirect here
return HttpResponseRedirect('/core/home/')
else:
pass
else:
form = RequestEmailAddressForm()
return render(request, "core/request_email_address.html", { "form": form })

Related

why i cant get the json from this scrip in php using alamofire?

i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}

Only output invalid YouTube ID's from database if video doesn't exists

I have YouTube video IDs stored in my database. I'm trying to output the IDs that are only invalid. I'm using get_headers / oembed which allows me to check if a video exists on YouTube. Then I am looping through the ID's. This is currently working but it's showing all YouTube IDs from my table and then adding the text "is invalid" to the ones that are invalid. I need to only display the ones that are invalid - nothing else!
I could use some help if anyone wouldn't mind. I would really appreciate it.
Code:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT src_id FROM youtube_videos ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo 'Video ID: '.$row["src"];
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo " is invalid";
} else {
echo "";
}
echo 'no results';
}
Just print the video ID if the header code is not 200?
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}
Might also want to look into a better way of grabbing response-headers, that thing might not be 100% accurate for all scenarios. I would suggest using something like
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (substr($headers[0], 9, 3) != 200) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}

Sending an array from PHP to javascript

In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.
Your Javascript may look something like this:
var matches = <?php echo($myarray[0]); ?>
There are 4 ways you can do to insert dynamic content to your javascript code.
Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags
Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.
If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS

How to use SELECT with WHERE & AND in conditional checks using PHP and MySql

On my server, I am attempting to find a specific string in a database table, if that string is found, I want to check to see what an integer value is in another field of the same row and UPDATE that integer if it is needed, or exit the PHP script.
The code below is only some of what I have tried. I don't see what is incorrect with the commands, and there are no error messages produced when it is ran/called.
What happens is, if the string is found, the script automatically runs the $there query.
What do I need to do to make this work correctly?
Thank you very much.
// This script checks to see if a member name sent by the page exists in the database.
//-------------------------------------------------------------
// The database section starts here.
$servername = "localhost";
$username = "manager";
$password = "********";
$dbname = "golf_ledger";
//------------------------------
// Make a connection with the server.
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection.
if($conn === false){
die("ERROR: Couldn't connect. " . mysqli_connect_error());
}
else {
echo "The connection worked."."<br>"."<br>";
}
//------------------------------------------------------------------
// This is the test string to be searched for.
$memName = "Richardson";
//----------------------------------------
// Populate $result with the search query.
// Database name Table name
$result = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName'");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, the name was not found";
die();
}
//----------------------------------------
// Something is wrong with this one, possibly.
$there = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 1");
// "if ($there)" is the same as "if ($there == true)" in PHP.
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
//----------------------------------------
$notThere = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 0");
if ($notThere == true) {
mysqli_query($conn,"UPDATE `golf_ledger`.`member_table` SET `pay_Status` = 1 WHERE `member_table`.`name` = '$memName'");
echo "The name has been found, they have NOT paid, but the status has been updated.";
die();
}
Instead of this code:
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
try that:
// Check if found any records
if (mysqli_num_rows($there) > 0) {
echo "The name has been found, and they have paid.";
die();
}

PHP/MYSQL Echo Mysql Data with hyperlink onto next page?

In my table I have various requests each with their own reference number.
a user can see the number of requests on the page, but I want the user to be able to click on each request separately and be taken to a new page to see the specific details for that request.
I am trying to echo the reference in a hyperlink when the request is clicked and on the next page when I run my query to retrieve the name etc of that request it will only show the information which matches that reference number, i.e. 'SELECT * WHERE reference = $row['reference'].
However I am not sure on how to to do this, also I am concerned is this secure, if my query is checking against the reference in my url, i.e. mypage.php?reference=1234, whats to stop a user just manually typing in the url with a different reference number?
'mypage.php?reference=2468
the user should only be able to view the page if they actually clicked on the request, they should never be able to enter it directly into the url as this poses a security risk.
could I potentially mask my reference into a string? and echo out mypage.php?reference=$someString
page1.php
<div class="results_area">
<h44>Existing Supplier Request's</h44>
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' AND action_taken='actioned'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div class="table_header"><p>Request By</p><p>Date Requested</p><p>Status</p><p>Supplier Name</p><p>Description</p><p>Action</p></div>'; ?>
</div>
<div class="results_area"><?php
while($row = $result->fetch_assoc()) {
echo '<div class="request"><a href="ns_application.php?ns_request='.$row['reference'].'/">';
mypage.php
$reference = $row['reference'];
<?php
$conn = new mysqli($host, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "select * from new_supplier_request where status!= 'complete' WHERE reference = $reference Limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h44>New Supplier Request: ' .$reference. ' </h44><br>';
echo 'The name of this supplier is, '.$reference['name'].';
} } ?>
</div>
You can use JavaScript to solve this problem.
I don't think that this will be 100% secure but actually it's more secure way than you are using now.
echo "<div .... onclick='showuniquereference('".$row['reference']."')'>"."</div>";
And Function like this
function showuniquereference(code)
{
var reference = code;
var form = document.createElement("form");
form.method = "POST";
form.action = "mypage.php";
var input = document.createElement("input");
input.name = "reference";
input.value = reference;
input.type = "hidden";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
You can use this posted data to show unique reference to users.

Categories