How do I code this the smart way, Ajax/PHP - php

I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>

Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com

Related

Uncaught SyntaxError:

The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"
The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");

PHP autoload is preventing POST

I developed my own PHP classes and used composer to manage all the dependencies between them. But whenever I include "vendor/autoload" on top of any PHP script, the page does not POST. None of the post data from any of the input elements is recognized or received by the script. The following script 'call.php' posts onto itself and nothing happens.
try
{
//------Page url
$url = 'call';
//------Set page timeout parameters
session_start();
if(isset($_SESSION['timeout']) && ((time() - (int)$_SESSION['timeout']) > 600)):
session_destroy();
header('Location: '.$url);
die();
endif;
$_SESSION['timeout'] = time();
//------Add required methods and classes
require dirname(__FILE__).'/../includes/vendor/autoload.php';
//------Get encrypted user id & device id
if(isset($_GET['id']) || isset($_GET['device'])):
//-----Decrypt user id and device id
$decrypt = new decryption();
$user_id = $decrypt->mc_decrypt($_GET['id']);
$device_id = $decrypt->mc_decrypt($_GET['device']);
//-----Validate decrypted data
$check = new validation();
$c_id = $check->check_number($user_id ,'n');
$c_device = $check->check_number($device_id ,'y');
if($c_id==1 && $c_device==1)
{
//-----Create a service object
$service = new service($user_id);
$status = $service->get_user_status();
//-----Check if the user has a valid status
if($status != 100)
{
header('Location: logout?logout&message='.$status.'#re101');
die();
}
else
{
$user_name = $decrypt->mc_decrypt($service->get_user_name());
//-----Check for previous service requests
$details = $service->get_service_call();
if($details)
{
$completed = false;
if($details['b'] == 'pending' )
{
$message = '<h2>Your request has been placed...</h2>';
$image = '<h2><img src="images/call_in.png alt="" height="100px" width="300px"/></h2>';
}
else if($details['b'] == 'processing' )
{
$message = '<h2>Your request is under process...</h2>';
$image = '<h2><img src="images/call_up.png" alt="" height="100px" width="300px"/></h2>';
}
else
{
$completed = true;
$service_id = $details['a'];
$message = '<h2>Your request has been fulfilled...</h2>';
$image = '<h2><img src="images/call_out.png" alt="" height="100px" width="300px"/></h2>';
}
$dated = $details['c'];
}
else
{
//-----Create a new service request
if($service->create_service_call($device_id))
echo "Service created";
$dated = date('d-m-Y', time());
}
}
}
endif;
//-----Once fulfilled, close the service by accepting user rating and feedback
if(isset($_POST['submit'])&&!empty($_POST['submit'])):
$id = !empty($_POST['service'])?$_POST['service']:'';
$rating = !empty($_POST['rate'])?$_POST['rate']:'';
$feedback = !empty($_POST['feed'])?$_POST['feed']:'';
$check = new validation();
$c_text = $check->check_textarea($feedback, 'y');
$feed = new service(0);
if(($rating == 10 || $rating == 5 || $rating == 1) && $c_text == 1)
{
if($feedback == '')
$feedback = 'nil';
if ($feed->give_service_feedback($id, $rating, $feedback))
$give = 'Thank you for your feedback!';
else
$give = 'Sorry, could not post your feedback.';
}
else
$give = 'Sorry, there was an error.';
endif;
}
catch(Exception $e)
{
$log = new misc();
$log->handle_ex($url, $_SESSION['account'], $e->getMessage(), $e->getFile(), $e->getLine());
header('Location: '.SITE.'404.shtml');
die();
}
Post via ajax
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- button to send form post -->
<button id="sendforms">Submit forms</button>
<div id="result"><!-- result of post page goes here --></div>
<script type="text/javascript">
$(document).ready(function () {
$("#sendforms").click(function() {
var combinedFormData = $("#form1").serialize();
$.post(
"test.php",
combinedFormData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
so all the code post is made in the test.php file you can check if is set with php and also return it your form must have a id="form1" and don't need
action="page.php" method="post" please remove this from your form
also the button must be
<button id="sendforms">Submit forms</button>
If you did't understand I can make a implementation for your you if send all code the form and the php part

echo out php variable in jQuery

this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

POST php headers failing

When I call a script from Javascript
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var conf = document.getElementById('confirm').value;
var code = document.getElementById('code').value;
if(code.length == 0 || pass.length == 0 || user.length == 0 || conf.length == 0) {
alert("Entries empty");
} else if(pass != conf) {
alert("Passwords don't match");
}
window.location = "scripts/changepassword.php?Username="+user+"&Password="+pass+"&Code="+code;
changepassword.php in my scripts folder has the following headings its refreshing the current page and not passing the parameters into the script. any ideas?
it gives me error2.
scripts/changepassword.php
if (isset($_GET['Username']) && isset($_GET['Password'])&& isset($_GET['Code'])) {
...
} else {
$response = array('result'=>"error2");
echo json_encode($response);
echo "hi";
}
the window.location changes the page location (url). If you want to execute the php script without refreshing the page, use AJAX

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Categories