Using ajax how can I pass variables to two different php scripts - php

I have two forms that sends data using ajax. Both forms have their own scripts and I thought that I would be able to access the same $_POST[] variables on the separate scripts, but this is not working. I tried using session_start() and include_once and for some reason I can't figure out why the variables are not passing from script to script. I've been at it for three days researching for a solution so if you know what I'm doing wrong or have an alternative please let me know thanks.
javascript.
$('.test-input').load("test.php", {
'sendTo':sendTo,
'carrier':carrier,
'testSubmit':testSubmit
})
$('#error-display').load("textsms.php", {
'date':scheduleDate,
'firstname':firstName,
'number':number,
'message':message,
'time':time,
'service':service,
'submit':submit
})
test.php
if (isset($_POST['testSubmit'])) {
$sendTo = $_POST['sendTo'];
$carrier = $_POST['carrier'];
$sendToInvalid = false;
$testEmpty = false;
$sendTo = "";
if (!preg_match('/^\(?\b\d{3}[-.)\s]?\s?\d{3}[-.)\s]?\d{4}\b$/', $sendTo) and $sendTo !== '') {
$sendToInvalid = true;
} elseif (empty($sendTo) || empty($carrier)) {
$testEmpty = true;
} else {
$sendTo = preg_replace('/[-.()\s]/','',$sendTo).$carrier;
$_SESSION['sendTo'] = $sendTo;
}
}
Trying to get $sendTo to pass to textsms.php down below.
else {
include 'test.php';
$sendTo = $_SESSION['sendTo'];
$number = preg_replace('/[-.()\s]/','',$number);
$number = "(".substr($number,0,3).") ".substr($number,3,3)."-".substr($number,6,4);
if ($sendTo !== "contactme#aboutryansam.com") {
$header = $name."\r\n#: ".$number;
$sendMsg = $userMsg."\r\nOn: ".$date.$time."\r\nService: ".$service;
//mail($sendTo, "You win!", $sendMsg, $header);
echo $sendTo;
echo "it worked";
}

Of course, on the page you initialize the ajax, include the "header.php" file that has inside session_start(). include_once('header.php') in the test.php as well. It should do the trick.
It's not a good practice nowadays, I better suggest you to use cookies and access them with $_COOKIE. Even better, use a library that takes care of cookies like this one. JQuery also has very good cookie management.

Related

Multiple retry PHP

Is it possible to create a multiple verification about one variable? Like this:
<?php
$name = null;
if(isset($name)){
$name = null;
//Ah the name is again null, let's retry
if(isset($name)){
$name = "Arthur";
//Great! The name is arthur !
}
}
?>
Not sure the application you will give to the script, but this should do. Remember PHP will run the script first, then return the page. You cannot have an infinite loop running like JavaScript.
<?php
$name = null;
while (false === isset($name)) {
// Your code in here
}

php: shellscript running before screen-output

I'm currently putting together a small web-based GUI to generate kickstart-scripts. I got a confirmation page that's sending the relevant data via POST to the PHP-page where the actual shell script is called to build the iso. So far it's working, but the page seems to execute the script before it outputs anything else (for example, the 'echo' I put in at the beginning of the page ...), and I'm absolutely clueless why. Would anyone care to enlighten me?
Here's the code to the PHP-page that's executing the shell script ...
echo 'Generating your ISO; this might take a while...';
sleep(20);
if (!isset($_POST['auth'])) {
$ad = 'N';
}
else {
$ad = 'Y';
}
if (!isset($_POST['oracle'])) {
$oracle = 'N';
}
else {
$oracle = 'Y';
}
if ((!isset($_POST['ip'])) or (!isset($_POST['hostname'])) or (!isset($_POST['rhsel'])) or (!isset($_POST['submit'])) or (!isset($_POST['gw'])) or (!isset($_POST['nm']))) {
die('Please use the correct form !');
}
if (isset($_POST['ip'])) {
$ip = trim($_POST['ip']);
}
if (isset($_POST['gw'])) {
$gw = trim($_POST['gw']);
}
if (isset($_POST['nm'])) {
$nm = trim($_POST['nm']);
}
if (isset($_POST['hostname'])) {
$hostname = trim($_POST['hostname']);
}
if (isset($_POST['rhsel'])) {
$rhsel = $_POST['rhsel'];
}
passthru("/usr/bin/sudo /data/skripte/webconfig.sh $rhsel $oracle $ad $ip $gw $nm $hostname 2>&1");
PHP scripts accessed via a browser are request-response, meaning all processing is done on the server prior to headers and content being sent to the client. This means you will not get a continually updating output like you would see on the command line. There is no way around this. Sorry.

PHP Static var not working

I'm working on a Captcha class and i'm almost done, there is one thing that doesn't work
In the file where I put the form, I start with this line:
include 'captcha.php';
$captcha = Captcha::tryCaptcha(2,4,'#000', '#ffffff');
and this is the captch construct:
static $do_generate = TRUE;
function __construct($aantal_letters = 2, $aantal_cijfers = 4, $voorgrond = '#000000', $achtergond = '#ffffff') {
session_start();
if (self::$do_generate == TRUE) {
$letters = substr(str_shuffle('ABCDEGHJKLMNPQRSTUVWXYZ'),0 ,$aantal_letters);
$cijfers = substr(str_shuffle('23456789'),0 ,$aantal_cijfers);
$imgbreed = 18 * ($aantal_letters + $aantal_cijfers);
$_SESSION['imgbreed'] = $imgbreed;
$_SESSION['captcha'] = $letters . $cijfers;
$_SESSION['voorgrond'] = $this->hex2rgb($voorgrond);
$_SESSION['achtergond'] = $this->hex2rgb($achtergond);
}
}
so in other words I put my stuff in a session if the static var $do_generate == TRUE
So when I post the form, the captcha is getting checked by a procesor.php
like this:
if (Captcha::captcha_uitkomst() == TRUE) {
echo "Great";
} else {
echo "Wrong";
}
And this is the captcha function that checks the etered captcha code:
static function captcha_uitkomst() {
if (strcmp($_SESSION['captcha'], strtoupper(str_replace(' ', '', $_POST['captcha-invoer']))) == 0) {
return TRUE;
} else {
echo "test";
self::$do_generate = FALSE;
return FALSE;
}
}
If I enter a correct captcha code, it's all good, that works I get the echo great.
If wrong I get the echo Wrong,
Perfect, but.... when I go back to form (hit backspace one history back) to enter a correct captcha, it regenerates a new captcha.
In the class: captcha_uitkomst you see that I made the self::do_generate FALSE
And the echo 'TEST' works when it's false, (just for checking)
What am I doing wrong
When you hit "back", the page is reloaded. You get a new CAPTCHA.
The premise of your question is fundamentally flawed, as you have just randomly assumed that this shouldn't happen, whereas in reality this is entirely by design.
It wouldn't be a very effective CAPTCHA if you could repeatedly get it wrong then go back and try again; any bot could just start brute forcing it and learning from the experience.

How do I get a PHP form page to close on succesful submit?

Is there a quick and easy way to make this form.php code close the window after submitting instead of redirecting? I can deal with the redirect if there is no way to do this, but would like to have the window just close, as the original form is being opened in a new window. Code below:
<?php
if (!empty($_POST)) {
// Used for later to determine result
$success = $error = false;
// Object syntax looks better and is easier to use than arrays to me
$post = new stdClass;
// Usually there would be much more validation and filtering, but this
// will work for now.
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
// Check for blank fields
if (empty($post->First) OR empty($post->Last) OR empty($post->Email))
$error = true;
else {
// Get this directory, to include other files from
$dir = dirname(__FILE__);
// Get the contents of the HTML email into a variable for later
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('Hospitality Recycling Program Calculator Results') // Message subject
->setTo(array('bsmith#cleantheworld.org', $post->Email =>$post-> First )) // Array of people to send
->setFrom(array('bsmith#cleantheworld.org' => 'Clean the World')) // From:
->setBody($html_message, 'text/html');
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
}
header("location: http://www.cleantheworld.org/newpartner.asp");
?>
I agree with #jeroen that a better solution would be to use AJAX but you can just output some javascript in the head of the redirect to close the page. Again I don't recommend this as a good solution to the problem but it will work as long as javascript is enabled in the users browser.
<script type="text/javascript>
self.close();
</script>

PHP return false if certain word appears in $_POST[xxx]

I have a coming soon form at a website where user fills out an email form and it will be emailed to me. However, a spammer has hit the site and is spamming the form with goatse and so on. IP ban isn't helping so I need to stop the form sending it if it contains goatse or something. Here's the mailer.
<?php
$SPOSTI =$_POST[sposti];
if ($SPOSTI=="")
{
return false;
}
if ($SPOSTI=="goatse.fr")
{
return false;
}
if ($SPOSTI=="http://www.goatse.info/hello.jpg")
{
return false;
}
else
{
$to = "xxx#gmail.com";
$subject = "xxx";
$message = "$_POST[sposti] haluaa tiedon kun kotisivut.name avautuu.
$_POST[ip]";
$from = "$_POST[sposti]";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
?>
Is there someway to block it from executing the code if the email contains a certain word (goatse in this case)
You need to use exit or die instead of return false which works inside functions/methods:
if ( $SPOSTI =="" || strpos('goatse', $SPOSTI) !== FALSE)
{
exit();
}
strpos() will let you find a substring, but I really recommend a captcha security system as the attacker could simply switch to another annoying word.
Goatse's arn't your problem here, it's the security.
You can use stristr http://php.net/manual/de/function.stristr.php to achive this. I would recommend to using a captcha, since it is more efficient. A popular solution is reCaptcha: https://developers.google.com/recaptcha/docs/php Another, weaker possibility is to add a security question to your form, for instance "What is five plus five in numbers?".
Try the following:
function is_spam($array, $block_pattern){
$block = false;
foreach($array as $k => $v){
if(preg_match('/.*' . $block_pattern . '.*/', $k) ||
preg_match('/.*' . $block_pattern . '.*/', $v)){
$block = true;
break;
}
}
return $block;
}
Usage: is_spam($_POST, 'goatse');
Returns: true if 'goatse' is found in $_POST
The function will search all keys and values of $array for the $block_pattern string and will return true if the pattern is found.

Categories