Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

my login.php did not select from mysql

$
0
0

Hi am new to php and am facing some difficulty concerning the login.php. My register.php is inserting to the database but when i try to select it so i can login it keeps showing me the errmsg. These are the codes..

<?php
 ob_start();
 session_start();
 require_once 'dbconnect.php';

 // it will never let you open index(login) page if session is set
 if ( isset($_SESSION['user'])!="" ) {
  header("Location: home.php");
  exit;
 }

 $error = false;

 if( isset($_POST['btn-login']) ) {

  // prevent sql injections/ clear user invalid inputs
  $userlogin = trim($_POST['userlogin']);
  $userlogin = strip_tags($userlogin);
  $userlogin = htmlspecialchars($userlogin);

  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  // prevent sql injections / clear user invalid inputs

  if(empty($userlogin)){
   $error = true;
   $userloginError = "Please enter your loginid.";
  }

  if(empty($pass)){
   $error = true;
   $passError = "Please enter your password.";
  }

  // if there's no error, continue to login
  if (!$error) {

   $usepassword = hash('sha256', $pass); // password hashing using SHA256

   $res=mysql_query("SELECT `id`, `loginid`, `firstname`, `middlename`, `lastname`, `phone`, `email`, `password`, `cpassword`, `answer` FROM icpl WHERE userlogin='$userlogin' AND usepassword='$usepassword'");
   $row=mysql_fetch_array($res);
   $count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row




   if( $count == 1 && $row['password']==$usepassword && $row['loginid']==$userlogin ) {
	  $_SESSION['user'] =true;
    $_SESSION['user'] = $row['loginid'];





    header("Location: home.php");
   }


   else {
    $errMSG = "Incorrect Credentials, Try again...";

   }

  }

 }
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="login-registration-php-new/assets/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
#apDiv1 {
	position: absolute;
	width: 200px;
	height: 115px;
	z-index: 1;
	left: 236px;
	top: 139px;
}
#apDiv2 {
	position: absolute;
	width: 200px;
	height: 115px;
	z-index: 1;
	left: 501px;
	top: -17px;
}
.container #login-form form .col-md-12 .form-group #apDiv2 .form-group h2 {
	color: #F00;
}
</style>
</head>
<body>


<div class="container">

 <div id="login-form">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

     <div class="col-md-12">

         <div class="form-group">
             <div id="apDiv2">
               <div class="form-group">
                 <h2 class="">Sign In.</h2>
               </div>
               <div class="form-group">
                 <div class="form-group"><span class="text-danger"><?php echo $passError; ?></span></div>
                 <span class="text-danger"><?php echo $userloginError; ?></span>
                 <hr />
                 <?php
   if ( isset($errMSG) ) {

    ?>
               </div>
               <div class="form-group">
                 <div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?></div>
               </div>
               <?php
   }
   ?>
               <div class="form-group">
                 <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
                   <input type="text" name="userlogin" class="form-control" placeholder="Your LoginId" value="<?php
				   echo $userlogin; ?>" maxlength="40" />
                 </div>
               </div>
               <div class="form-group">
                 <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                   <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
                 </div>
               </div>
               <div class="form-group">
                 <hr />
               </div>
               <div class="form-group">
                 <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
               </div>
               <div class="form-group">
                 <hr />
               </div>
               <div class="form-group"> <a href="../../register.php">Sign Up Here...</a></div>
             </div>
             <h2 class=""> </h2>
        </div>
</div>

    </form>
    </div>

</div>

</body>
</html>
<?php ob_end_flush(); ?>

Implementing lenght prefix with stream

$
0
0

The following script seems to work, however, might have a couple of issues.

 

First, LengthPrefixStream::send()seems to work, however, the receiving client doesn't respond correctly to it.  See any issues with it?

 

LengthPrefixStream::parseBuffer() works by making sure that $this->buffer always starts with a new packet/message (don't know the right word to use for this), and then knows that the first four bytes indicate the length of the message.  See any issues?  One concern I have is "if" it is sent content with more or less bytes than the length prefix indicates, $this->buffer might not always start with a new message, and I will lose the ability to find out the length prefix.  Should this be a concern?

 

Thanks

<?php
require 'vendor/autoload.php';

$port = isset($argv[1])?$argv[1]:1337;
$host = isset($argv[2])?$argv[2]:'0.0.0.0';

$server=new Server($port,$host);
$server->start();

class Server
{
    private $port,$host,$client;

    public function __construct($port,$host)
    {
        $this->port=$port;
        $this->host=$host;
    }

    public function start() {
        $loop = React\EventLoop\Factory::create();
        $socket = new React\Socket\Server($loop);
        $socket->on('connection', function (\React\Socket\ConnectionInterface $stream){
            $client = new DataLogger\Server\LengthPrefixStream($stream,'o');
            $this->client=$client;
            echo("New connection accepted.".PHP_EOL);
            $client->on('data', function($rsp) use ($client){
                echo('received: '.json_encode($rsp).PHP_EOL);
            });

        });

        $loop->addPeriodicTimer(15, function() {
            $this->client->send(["method"=>"discovery.Start"]);
        });

        $socket->listen($this->port,$this->host);
        echo("TCP Socket Server Started: {$this->host}:{$this->port} \r\n");

        $loop->run();
    }
}
<?php
namespace DataLogger\Server;

use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
use React\Stream\DuplexStreamInterface;

class LengthPrefixStream implements EventEmitterInterface {
    use EventEmitterTrait;

    private $socket,
    $buffer='',
    $messageLength=false,
    $type;  //Type of data provided and returned.  Can be s for string, a for array, or o for object.  If array is associated, will be sent as an object.

    public function __construct(DuplexStreamInterface $socket, $type='s'){
        if (!in_array($type,['s','a','o'])){
            trigger_error("Invalid LengthPrefixStream type.", E_USER_ERROR);
        }
        $this->socket = $socket;
        $this->type=$type;

        $this->socket->on('data', function($data){
            //echo("LengthPrefixStream on data: $data".PHP_EOL);
            $this->buffer .= $data;
            $this->parseBuffer();
        });
    }

    public function send($message){
        //How should drain be implemented?
        if($this->type!='s') {
            $message = json_encode($message);
        }
        echo("send: $message".PHP_EOL);
        $lng=pack("V", strlen($message));  //Is this correct?
        $this->socket->write($lng.$message);
    }

    private function parseBuffer(){
        //Question.  What happens if something goes wrong and I lose $this->messageLength so I can't find the length prefix?
        if(!$this->messageLength) {
            //Save the first time data is received or if not enough stream was provided to determine the length
            $this->messageLength=$this->getLength($this->buffer);
        }
        while (strlen($this->buffer)>=($this->messageLength+4)){
            $message = substr($this->buffer, 4, $this->messageLength);
            if($this->type=='s') {
                $this->emit('data', [$message]);
            }
            else {
                //emit either an array or object
                $message = json_decode($message,$this->type=='a');                
                if (json_last_error() == JSON_ERROR_NONE){
                    $this->emit('data', [$message]);
                }
            }
            $this->buffer = substr($this->buffer, $this->messageLength+4);
            $this->messageLength=strlen($this->buffer)>=4?$this->getLength($this->buffer):false;
        }
    }

    private function getLength($string){
        // Appears length prefix is given as unsigned long (always 32 bit, little endian byte order)
        /*
        L     unsigned long (always 32 bit, machine byte order)
        N     unsigned long (always 32 bit, big endian byte order)
        V     unsigned long (always 32 bit, little endian byte order)
        */
        return unpack('Vlen', substr($string,0,4))['len'];
    }
}

Current Status and Previous States where to start

$
0
0

HI All, 

 

Sorry for sounding crap but searching the net has come up with nothing and that's what I have nothing...and to be honest dont know where to start looking for what I need 

 

I will try and explain as best I can

 

In the db I have  current_status, this is updated from a select list in a form on website one

 

status 1 

status 2

status 3

etc etc

 

So when the user changes the "status" from website 1 it updates the database and shows the current status in website 2

 

What I want is to show the previous states with a time  stamp on when it was changed something like image attached

 

Am I right in thinking I will not be able to do this with only working with one row in the db or is this possible with php alone
 
Can someone give me a pointer where to start, I am not after anyone to write code just a little advice
 
Thanks in advance
 

 

Attached Thumbnails

  • test.jpg

Best guess date from messy string.

$
0
0

Without writing a regx, is there a php function/library that will take a string and try and convert it to a date? PHP's date is not adequate.

 

For example, these are all "dates".  I would expect it to succeed on any of these.  On those that are ambiguous, there should be attribute that can be set like, expect year between 78 and 16.  This is strictly best guess, I do not supply a format.  Failure is expected.

 

feb 21, 1999

Feburary 21, 1999

02/21/99

2/21/99

99/2/21

2-21-1999

19990221

sun, Feb 21, 1999

Sunday Feburary 21, 1999

anything returned by a mysql date (now(), datetime ...)

Today's date is DATESTUFF

 

 

 

You get the idea.

 

Returns false on couldn't do it, and some array or seconds after N if successful.

 

Thank you.

Where is the mistake?

$
0
0

Please help me. I know this question is a beginner's question, now I am learning Switch Operator and  I can't understand why my code doesn't work in browser. I asked on other forums this question but people there say that there are errors in every line and that I am a fool that I don't see it. But I don't see it. I tried to write it correctly, but I don't know why it doesn't work. Please tell to a fool one where is the mistake?

 

HTML

<!doctype html>
<html>
<meta charset = "utf-8">
<head>
<body>
  <form action = "index.php" method="get">
  <tr>
  <td>What do you you select?</td>
  <select name = "find">
  <option value = "a">  A
  <option value = "b">   B
  <option value="c" >   C
  </select></td></tr>
  <input type="submit" name="submit" value="Send My Posting" />
  </form>
</body>
</html>

 

 

PHP

<?php

 $find = $_POST["find"];
 switch($find){
 case "a";
 echo "you selected A";
 break;
 case "b";
 echo "you selected B";
 break;
 case "c";
 echo "you selected C";
 break;
 
?>
 

Close and unset $this

$
0
0

Is it possible to close a connection and delete an object when within that object?  For instance:

<?php
//....
$socket->on('connection', function (\React\Socket\ConnectionInterface $stream){
    $client = new DuplexStreamInterface($stream);
    //....    
});
//....

class LengthPrefixStream
{
    public function __construct(DuplexStreamInterface $socket){
        $this->socket = $socket;
        $this->socket->on('data', function($data){
            $this->buffer .= $data;
            $this->parseBuffer();
        });
    }

    public function parseBuffer(){
        //...
        if($badConnectionSoCloseSelf) {
            $this->socket->close();
            unset($this);
        }
        //...
    }
}

A help with passing parameters to PHP contact form.

$
0
0

Hello respected developers,

 

This is my HTML code:

<div class="row">
<div class="col-xs-10 col-xs-offset-1">
<div class="empty-space h50-md h30-xs"></div>

<form class="contact-form">
<div class="row col-xs-b30">
<div class="col-sm-6 col-xs-b30 col-sm-b0">
<div class="input-wrapper">
<input name="name" class="input" type="text">
<label>Name</label>
<span></span>
</div>
</div>
<div class="col-sm-6">
<div class="input-wrapper">
<input name="email" class="input" type="text">
<label>Email</label>
<span></span>
</div>
</div>
</div>
<div class="row col-xs-b30">
<div class="col-sm-12">
<div class="input-wrapper">
<input name="subject" class="input" type="text">
<label>Subject</label>
<span></span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="input-wrapper">
<textarea name="message" class="input"></textarea>
<label>Message</label>
<span></span>
</div>
</div>
</div>

<div class="empty-space col-xs-b40"></div>

<div class="text-center">
<div class="button type-Techenotic">
SEND MESSAGE
<input type="submit"/>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

This is my Javascript file "Contact.form.js"

$(function() {

    "use strict";

    $('.contact-form').on("submit", function(){
        var $this = $(this);
                        
        $('.invalid').removeClass('invalid');                        
        var msg = 'The following fields should be filled:',
            successMessage = "Your email is very important to us. One of our representatives will contact you at first chance.",
            error = 0,
            pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);


        if ($.trim($('.contact-form input[name="name"]').val()) === '') {error = 1; $this.find('inpute="name"]').parent().addClass('invalid'); msg = msg + '\n - Name';}
if (!pattern.test($.trim($('.contact-formut[name="email"]').val()))) {error = 1; $this.find('inpute="email"]').parent().addClass('invalid'); msg = msg + '\n - Email';}
        if ($.trim($('.contact-form textarea[name="message"]').val()) === '') {error = 1; $this.find('textareae="message"]').parent().addClass('invalid'); msg = msg + '\n - Your Message';}

if (error){
    updateTextPopup('ERROR', msg);
}else{
var url = 'Send_mail.php',
    name = $.trim($this.find('inpute="name"]').val()),
    email = $.trim($this.find('inpute="email"]').val()),
    subject = ($this.find('inpute="subject"]').length)?$.trim($this.find('inpute="subject"]').val()):'',
    message = $.trim($this.find('textareae="message"]').val());

$.post(url,{'name':name,'email':email,'subject':subject,'message':message},function(data){
         updateTextPopup('THANK YOU!', successMessage);
         $this.append('<input type="reset" class="reset-button"/>');
         $('.reset-button').click().remove();
         $this.find('.focus').removeClass('focus }
         return false;
    });

    $(document).on('keyup', '.input-wrapper .input', function(){
        $(this).parent().removeClass('invalid');
    });

    function updateTextPopup(title, text){
        $('.text-popup .text-popup-title').text(title);
        $('.text-popup .text-popup-message').text(text);
        $('.text-popup').addClass('active');
    }

});

My problem is that I don't know how to pass the parameters to "Send_Mail.php" if anyone can help me make this PHP file I would be very thankful.

 

Thank you so much.

"Host key verification failed" when trying to set up SSH tunnel for MySQL

$
0
0

I see all over the internet tutorials that are basically saying that setting up the ssh tunnel for mysql is easy, but I get an error, and no joy:

 

Host key verification failed

 

This error is in a log file that I created. I am attempting to use PHP's shell_exec on my Ubuntu desktop:

shell_exec('ssh -p 2233 -f -L 3307:127.0.0.1:3306 acct@remote-server.com sleep 60 >> ./ssh.logfile 2>&1');

So, pretty standard according to the internet, but it's not working for me.

 

1) The remote server is a hosted website. It's a "semi-dedicated" plan, and just a glorified shared hosting account.

2) I can already do a passwordless SSH connection to the remote server by using the terminal. So my key based authentication is working for me.

3) I use SQLyog (MySQL tunneling through SSH) to this remote server. It's not key based, but the tunnel is there.

4) The host was not helpful. They were trying (I think), but nothing worked.

5) Yes, the remote server requires SSH connections on port 2233.

 

Why is this failing? I need somebody to walk me through this. I saw somewhere online that the error message may mean that apache was not able to check a known_hosts file. I created an .ssh directory at /var/www/.ssh, and I put a known hosts file in there. Chowned these to www-data:www-data. Permission set at 600.

 

Don't know what else to do or check.


Any good articles on interfaces?

$
0
0

Still struggling a bit with interfaces.

 

When I just started messing around with them, I started making an interface for all my end classes.

 

But, then started thinking I am going about it wrong, and should start the interface much earlier and not duplicate the capabilities.  For instance, all things exist but this hardly deserves an interface, all vehicles start, stop, turn, etc, so I should make an interface for vehicles, only a motorcycle can pop a wheelie so I should extend the interface, and dirtbikes don't do much more than normal motorcycles (other than being more fun!) so probably should extend it.

 

Now I am thinking that I might not want an interface for a motorcycle, but I want an interface for something that can pop a wheelie.  But isn't that a motorcycle?

 

How should interfaces really be used for these classes?

 

Also, does anyone know of any good tutorials or articles on interfaces?

 

Thanks

Thing->Vehicle->VehicleThatCarriesHumans->Motorcycle->DirtBike
Thing->Vehicle->VehicleThatCarriesHumans->Automobile
Thing->Vehicle->Drone->Phantom

Taking form data directly to an array?

$
0
0

Hey guys and gals,

 

I'm new at coding, and I'm having some difficulty figuring out what might be the problem. 

 

In words, I'm taking a few text boxes from a html form (such as the user enters a couple of numbers) and put that directly into an array in php.

 

Essentially it is this:

 

<input type="text" name="height[]" id="height[]" required="required">

<input type="text" name="weight[]" id="weight[]" required="required">

 

a submit button takes the data via post to the calculate.php.

 

There we have

$height = $_POST['height'];

$weight = $_POST['weight'];

 

 

print_r($height);

 

So what is going on is that when the user submits , say 55 in the height and 25 in the weight.  It as expected gets loaded into the $height and $weight arrays.  But when I try to add a new height and weight to the array via a new submit, say 22 and 95, the old values get replaced by the new ones, instead of adding to the $height and $weight array. 

 

So it always looks like

array[0] => 55

array[0] => 22

 

What I want it to do is to increment,

array[0] => 55, array[1] => 22 ...

 

I check the data coming from POST, it seems to be a string, is it because the array should be numeric and the data coming into the array are strings? 

 

My thoughts are that the data from post are being put into a variable, but I just don't think this is right. 

 

Thanks for any help

Help with Contact Form security question choices

$
0
0
I realize this is old code (that I didn't write) but works well for a temporary 'under construction' page.
After filling in the simple Form fields the simple Security question is presented : Is fire Hot or Cold?
When I enter text into the answer field it works successfully, except, of course on a mobile device. In order for it to work on a mobile device, I believe I need to present a choice, rather than entering text - correct?
So, I'm looking for a possible simple tweak on this code, so that it will work for a mobile device, please. I don't really want to re-write all of it, and I know it's not super-secure, but it will do for now.
 
Here's the last part of the Form:
 
<div>
<p>Security Question:<br> Is Fire Hot Or Cold?:
<input type="text" name="ans"/></p><br>
<p><input class="btn btn-action" type='submit' value="Send message"></p>
</div>
</form>
And
 

<?php
// create an empty error array to hold any error messages\
$error = array();
$mailto     = 'someone@somewhere.com';
$mailsubj   = "ContactForm Submission";
$mailhead   = "From:SomehereForm\n";
$mailbody   = "--- Contact form results ---\n";
foreach($_REQUEST as $key => $value)
{
if($key != 'PHPSESSID')
{
$mailbody .= $key.": ".$value."\n";
}
}
if(isset($_POST['ans']) && $_POST['ans']!='hot')
{
// add error to error array
$error[] = header('Location: ww.somesite.com/WrongAnswer.html');
exit;
}
// if no errors are set, continue
if(empty($error))
{
header('Location: ww.somesite.com/ThankYou.html');
exit;
}
?>

Is it possible to add something like:

<option value="ans">hot</option>
<option value="">cold</option>

and then change this somehow:

$error['anything other than hot'] = header('Location: ww.somesite.com/WrongAnswer.html');
exit;

Any tweak help will be appreciated.

CodeIgniter - Blocking access to admin pages

$
0
0

The thing is that I never created a login page, or anything like that.

So my website is completely done, is finally ready to be published, but the only thing that I need now, is the blocking of the admin pages to the public.

I have a controller called Admin in which I have all the function and pages of "admin" , here is my controller.(all ths needs to be blocked)

<?php
class Admin extends CI_Controller {


public function __construct()
{
parent::__construct();
$this->load->model('about_model');
$this->load->model('blog_model');
$this->load->model('categorias_model');
$this->load->model('cookies_model');
$this->load->model('news_model');
$this->load->model('portfolio_model');
$this->load->model('privacy_model');
$this->load->model('terms_model');
$this->load->model('skills_model');
$this->load->model('profesion_model');
$this->load->model('slider_model');
$this->load->library('pagination');


}


public function index(){

$data['title'] = 'Admin Panel';
// Siempre poner minusculas al poner nombre de un model //
$data['blog'] = $this->blog_model->get_blog();
$data['portfolio'] = $this->portfolio_model->get_portfolio();


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/dashboard',$data);
$this->load->view('templates/footer', $data);
}
//// Paginas de administracion ///

public function sliders(){

$data['title'] = 'Sliders';
$data['slider'] = $this->slider_model->get_slider();

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/sliders',$data);
$this->load->view('templates/footer', $data);



}

public function posts(){

$data['title'] = 'Posts';
$data['blog'] = $this->blog_model->get_blog();

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/posts',$data);
$this->load->view('templates/footer', $data);



}

public function portfolio(){

$data['title'] = 'Portfolio';
// Siempre poner minusculas al poner nombre de un model //
$data['portfolio'] = $this->portfolio_model->get_portfolio();



$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/portfolio',$data);
$this->load->view('templates/footer', $data);
}

///// Estas paginas requieren de la funcion __construc que etsa localizada abajo, si se llegase a borrar, estas, dejaran de funcionar y/o mostrar informacion de la database
public function categorias(){

$data['title'] = 'Categorias';
// Siempre poner minusculas al poner nombre de un model //
$data['categorias'] = $this->categorias_model->get_categorias();


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/categorias',$data);
$this->load->view('templates/footer', $data);
}


public function paginas(){

$data['title'] = 'Paginas';
// Siempre poner minusculas al poner nombre de un model //
$data['about'] = $this->about_model->get_about();
$data['cookies'] = $this->cookies_model->get_cookies();
$data['home'] = $this->news_model->get_home();
$data['privacy'] = $this->privacy_model->get_privacy();
$data['terms'] = $this->terms_model->get_terms();


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/paginas',$data);
$this->load->view('templates/footer', $data);
}


public function skills(){

$data['title'] = 'Skills';
// Siempre poner minusculas al poner nombre de un model //
$data['skills'] = $this->skills_model->get_skills();


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/skills',$data);
$this->load->view('templates/footer', $data);
}


public function profesion(){

$data['title'] = 'Profesion';
// Siempre poner minusculas al poner nombre de un model //
$data['profesionalismo'] = $this->profesion_model->get_profesion();


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/profesion',$data);
$this->load->view('templates/footer', $data);
}




///////////////////////////////////////////////////////////////////////////////////////////////////////////// Slider ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Crear slider ///
public function crearslider(){
$data['title'] = 'Crear Slider';



$this->form_validation->set_rules('titulo','Titulo', 'required');
$this->form_validation->set_rules('imagen','Imagen', 'required');
$this->form_validation->set_rules('descripcion','Descripcion', 'required');
$this->form_validation->set_rules('link','link', 'required');

if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearslider',$data);
$this->load->view('templates/footer', $data);

} else{
$this->slider_model->crearslider();
redirect('admin/sliders');
}
}

// Borrar slider //
public function borrarslider($id){
$this->slider_model->borrarslider($id);
redirect('admin/sliders');
}

// Editar slider //
public function editarslider($slug){
$data['slider']=$this->slider_model->get_slider($slug);

if(empty($data['slider'])){
show_404();
}
$data['title']='Editar slider';

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarslider',$data);
$this->load->view('templates/footer', $data);
}

// Actualizar slider //
public function actualizarslider(){
$this->slider_model->actualizarslider();
redirect('admin/sliders');
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////// BLOG /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Crear Post ///
public function crearpost(){
$data['title'] = 'Crear Post';
$data['categorias'] = $this->categorias_model->get_categorias();


$this->form_validation->set_rules('titulo','Titulo', 'required');
$this->form_validation->set_rules('fecha','Fecha', 'required');
$this->form_validation->set_rules('imagen','Imagen', 'required');
$this->form_validation->set_rules('categoria_id','Categoria', 'required');
$this->form_validation->set_rules('contenido','Contenido', 'required');

if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearpost',$data);
$this->load->view('templates/footer', $data);

} else{
$this->blog_model->crear_post();
redirect('admin/posts');
}
}

// Borrar post //
public function borrar($id){
$this->blog_model->delete_post($id);
redirect('admin/posts');
}

// Editar Post //
public function editarpost($slug){
$data['blog']=$this->blog_model->get_blog($slug);
$data['categorias'] = $this->categorias_model->get_categorias();

if(empty($data['blog'])){
show_404();
}
$data['title']='Editar Post';



$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarpost',$data);
$this->load->view('templates/footer', $data);
}

// Actualizar Post //
public function actualizarpost(){
$this->blog_model->update_post();
redirect('admin/posts');
}


////////////////////////////////////////////////////////////////////////// Portfolio ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




// Crear Portfolio ///
public function crearportfolio(){
$data['title'] = 'Crear Portfolio';


$this->form_validation->set_rules('titulo','Titulo', 'required');
$this->form_validation->set_rules('fecha','Fecha', 'required');
$this->form_validation->set_rules('imagen','Imagen', 'required');
$this->form_validation->set_rules('thumbnail','Thumbnail', 'required');
$this->form_validation->set_rules('categoria_id','Categoria', 'required');
$this->form_validation->set_rules('descripcion','Descripcion', 'required');
$this->form_validation->set_rules('contenido','Contenido', 'required');
$this->form_validation->set_rules('changelog','Changelog');
$this->form_validation->set_rules('precio','Precio', 'required');
$this->form_validation->set_rules('preview','Preview', 'required');
$this->form_validation->set_rules('download','Download', 'required');

if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearportfolio',$data);
$this->load->view('templates/footer', $data);

} else{
$this->portfolio_model->crear_post();
redirect('admin/portfolio');
}
}

// Borrar portfolio //
public function delete($id){
$this->portfolio_model->delete_post($id);
redirect('admin/portfolio');
}


// Editar Portfolio //
public function editarportfolio($slug){
$data['portfolio']=$this->portfolio_model->get_portfolio($slug);


if(empty($data['portfolio'])){
show_404();
}
$data['title']='Editar Portfolio';


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarportfolio',$data);
$this->load->view('templates/footer', $data);
}


// Actualizar Portfolio //
public function actualizarportfolio(){
$this->portfolio_model->update_post();
redirect('admin/portfolio');
}


/////////////////////////////////////////////////////////////////////////////////// Categorias /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Crear categorias ///
public function crearcategory(){
$data['title'] = 'Crear Categoria';
$data['categorias'] = $this->categorias_model->get_categorias();

$this->form_validation->set_rules('nombre','Titulo', 'required');
$this->form_validation->set_rules('creado_en','Fecha', 'required');



if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearcategory',$data);
$this->load->view('templates/footer', $data);

} else{
$this->categorias_model->crear_post();
redirect('admin/categorias');
}
}

// Borrar categorias //
public function erase($id){
$this->categorias_model->delete_post($id);
redirect('admin/categorias');
}

// Editar categoria //
public function editarcategoria($slug){
$data['categorias'] = $this->categorias_model->get_categorias($slug);

if(empty($data['categorias'])){
show_404();
}
$data['title']='Editar Categoria';


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarcategoria',$data);
$this->load->view('templates/footer', $data);
}


// Actualizar categoria //
public function actualizarcategory(){
$this->categorias_model->update_post();
redirect('admin/categorias');
}


//////////////////////////////////////////////////////////////// Skills ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



// Crear skill ///
public function crearskill(){
$data['title'] = 'Crear Skill';
$data['skills'] = $this->skills_model->get_skills();


$this->form_validation->set_rules('titulo','Titulo', 'required');
$this->form_validation->set_rules('porcentaje','Porcentaje', 'required');
$this->form_validation->set_rules('color_1','Color Primario', 'required');
$this->form_validation->set_rules('color_2','Color Secundario', 'required');


if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearskill',$data);
$this->load->view('templates/footer', $data);

} else{
$this->skills_model->crearskill();
redirect('admin/skills');
}
}

// Borrar skill //
public function erase_skill($id){
$this->skills_model->erase_skill($id);
redirect('admin/skills');
}

// Editar skill //
public function editarskill($slug){
$data['skills'] = $this->skills_model->get_skills($slug);

if(empty($data['skills'])){
show_404();
}
$data['title']='Editar Skill';


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarskill',$data);
$this->load->view('templates/footer', $data);
}


// Actualizar skill //
public function actualizarskills(){
$this->skills_model->update_post();
redirect('admin/skills');
}



//////////////////////////////////////////////////////////////// Profesionalismo ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



// Crear profesion ///
public function crearprofesion(){
$data['title'] = 'Crear Skill';
$data['profesionalismo'] = $this->profesion_model->get_profesion();


$this->form_validation->set_rules('titulo','Titulo', 'required');
$this->form_validation->set_rules('numero','Numero', 'required');



if($this->form_validation->run()===FALSE){

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/crearprofesion',$data);
$this->load->view('templates/footer', $data);

} else{
$this->profesion_model->crearprofesion();
redirect('admin/profesion');
}
}

// Borrar profesion //
public function erase_profesion($id){
$this->profesion_model->erase_profesion($id);
redirect('admin/profesion');
}

// Editar profesion //
public function editarprofesion($slug){
$data['profesionalismo'] = $this->profesion_model->get_profesion($slug);

if(empty($data['profesionalismo'])){
show_404();
}
$data['title']='Editar Profesion';


$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarprofesion',$data);
$this->load->view('templates/footer', $data);
}


// Actualizar profesion //
public function actualizarprofesion(){
$this->profesion_model->update_post();
redirect('admin/profesion');
}





//////////////////////////////////////////////////////////////// Editar paginas globales ///////////////////////////////////////////////////////////////////////////////////////////////////////

/// Pagina Global About
public function editarpagina_about($slug){


$data['title']='Editar Pagina About';
$data['about'] = $this->about_model->get_about($slug);

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarpagina_about',$data);
$this->load->view('templates/footer', $data);

}



/// Actualizar pagina global about ///
public function actualizarpagina_about(){
$this->about_model->update_about();
redirect('admin/paginas');
}

/// Pagina Global Cookies
public function editarpagina_cookies($slug){


$data['title']='Editar Pagina cookies';
$data['cookies'] = $this->cookies_model->get_cookies($slug);

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarpagina_cookies',$data);
$this->load->view('templates/footer', $data);

}



/// Actualizar pagina global cookies ///
public function actualizarpagina_cookies(){
$this->cookies_model->update_cookies();
redirect('admin/paginas');
}

/// Pagina Global Privacy
public function editarpagina_privacy($slug){


$data['title']='Editar Pagina Privacy';
$data['privacy'] = $this->privacy_model->get_privacy($slug);

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarpagina_privacy',$data);
$this->load->view('templates/footer', $data);

}

/// Actualizar pagina global Privacy ///
public function actualizarpagina_privacy(){
$this->privacy_model->update_privacy();
redirect('admin/paginas');
}


/// Pagina Global Terms
public function editarpagina_terms($slug){


$data['title']='Editar Pagina Terms';
$data['terms'] = $this->terms_model->get_terms($slug);

$this->load->view('templates/head', $data);
$this->load->view('templates/navbar', $data);
$this->load->view('admin/editarpagina_terms',$data);
$this->load->view('templates/footer', $data);

}



/// Actualizar pagina global terms ///
public function actualizarpagina_terms(){
$this->terms_model->update_terms();
redirect('admin/paginas');
}


}
?>

I tried to put this on my function __construct , but it still not working :/ .

        public function __construct()
        {
                parent::__construct();
$this->load->model('about_model');
$this->load->model('blog_model');
$this->load->model('categorias_model');
$this->load->model('cookies_model');
$this->load->model('news_model');
$this->load->model('portfolio_model');
$this->load->model('privacy_model');
$this->load->model('terms_model');
$this->load->model('skills_model');
$this->load->model('profesion_model');
$this->load->model('slider_model');
$this->load->library('pagination');




//// Block access to admin pages ////


       //Here you check ip allowed or not
            if (!in_array($this->input->ip_address(), array('107.208.103.39')))
            {
               // Either show 404
               show_404();
  


               // OR redirect somewhere else
               redirect('news/home');
            }






        }

is there a way to block them to the public at least with HTACCESS ?

Performance image scanning

$
0
0

Hi,

 

I'm writing a script that scans images for numberplate edges in different angles. The below script works and picks up the edges in ~2 seconds. I'm curious if I can improve this to find the edges even faster.

 

real    0m1.917s
user    0m1.767s
sys     0m0.125s

<?php

require __DIR__ . '/../vendor/autoload.php';

use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\PointInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\Point;

$topLeft = $bottomLeft = [99999, 0];
$topRight = $bottomRight = [0, 99999];

$gatherer = function (ColorInterface $color, PointInterface $point, ImageInterface $image) use (&$topLeft, &$topRight, &$bottomLeft, &$bottomRight) {

    if ($color->getAlpha() == 0) {
        return;
    }

    $x = $point->getX();
    $y = $point->getY();

    $top    = $image->getColorAt(new Point($x, $y - 1))->isOpaque();
    $bottom = $image->getColorAt(new Point($x, $y + 1))->isOpaque();
    $left   = $image->getColorAt(new Point($x - 1, $y))->isOpaque();
    $right  = $image->getColorAt(new Point($x + 1, $y))->isOpaque();

    if (!$top && !$left && $bottom && $right && $x < $topLeft[0]) {
        $topLeft = [$x, $y];
    }

    if (!$top && !$right && $bottom && $left && $x > $topRight[0]) {
        $topRight = [$x, $y];
    }

    if (!$bottom && !$left && $top && $right && $x < $bottomLeft[0]) {
        $bottomLeft = [$x, $y];
    }

    if (!$bottom && !$right && $top && $left && $x > $bottomRight[0]) {
        $bottomRight = [$x, $y];
    }
};

//$img = (new \Imagine\Gd\Imagine())->open(__DIR__ . '/numberplate-test.png');
$img = (new \Imagine\Gd\Imagine())->open(__DIR__ . '/numberplate-test2.png');

for ($top = 640; $top < 900; $top++) {
    for ($left = 340; $left < 1580; $left++) {
        $point = new Point($left, $top);

        $gatherer($img->getColorAt($point), $point, $img);
    }
}

var_dump($topLeft, $topRight, $bottomLeft, $bottomRight);

Attached Thumbnails

  • numberplate-test.png
  • numberplate-test2.png

error upload

$
0
0

Hi everyone,

 

I am doing a work to unzip files and then choose some of them with checkebox and upload but when unzip, the $_FILES['files']['name'] stays with the name of the folder and the name of the file, so it cant upload well. I attach a file with images, how it looks like. I don't know what its wrong in  the code.   Can you help me? Please!

 

Thanks in advace for your help!

 

 

 

 

 

 

 

 

Attached Files

php hashtags

$
0
0

So i got this pulling twitter data raw i cant for the life of me figure out how to explode items $text(tweet body

and seperate the hashtags and enter them into a database (database hase 3 fields for hashtags)

<?php
/** database cred **/
        define('DBHOST','localhost');
        define('DBUSERNAME','***');
        define('DBPASSWORD','**');
        define('DBNAME','roguebro_tweet');
        define('TWEETTABLE','twitter');
/** end database cred **/


        /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
        require_once('TwitterAPIExchange.php');
        $settings = array(
        'oauth_access_token' => "831981818408677377-FexWOmvCyaZYWt3TYwmodmx3gMmFIqx",
        'oauth_access_token_secret' => "L1vwbaBjsUivKn5NYVmGgve6V1lSP5THvjBk3LiadHyOj",
        'consumer_key' => "t31OianjtopHhDEdeBAjWPqj3",
        'consumer_secret' => "zFZpwrMl31BShY6CluYapaZl0K1CQPpsagBjVCMkTs2GtWHhRm"
        );

        /** end Twitter Credentials **/
        $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
        $requestMethod = "GET";
        $getfield = '?screen_name=MCoCTrucos&entities=on&count=20 -rt';
        $twitter = new TwitterAPIExchange($settings);
        $string = json_decode($twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest(),$assoc = TRUE);
        if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a             problem.</h3><p>Twitter returned the following error message:</p><p>     <em>".$string[errors][0]["message"]."</em></p>";exit();}
        foreach($string as $items)
        {
            echo "Tweeted by: ". $items['user']['name']."<br />";
            echo "Screen name: ". $items['user']['screen_name']."<br />";
            echo "Tweet: ". $items['text']."<br />";
            echo "Time and Date of Tweet: ".$items['created_at']."<br />";
            echo "Tweet ID: ".$items['id_str']."<br />";
            echo "Followers: ". $items['user']['followers_count']."<br /><hr />";
            echo insertTweets($items['user']['name'],$items['user']['screen_name'],$items['text'],$items['created_at'],$items['id_str'],$items['user']['followers_count']);

$tags = $items['text'];

$hashtags = explode("#", $tags);





        }

        function insertTweets($name,$screen_name,$text,$created_at,$id_str,$followers_count){
            $mysqli = new mysqli(DBHOST, DBUSERNAME, DBPASSWORD, DBNAME);
            if ($mysqli->connect_errno) {
                return 'Failed to connect to Database: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
            }
            $prepareStmt='INSERT INTO '.DBNAME.'.'.TWEETTABLE.' (name, screen_name, text, created_at, id_str, followers_count) VALUES (?,?,?,?,?,?);';
            if ($insert_stmt = $mysqli->prepare($prepareStmt)){
                $insert_stmt->bind_param('ssssid', $name,$screen_name,$text,$created_at,$id_str,$followers_count);
                if (!$insert_stmt->execute()) {
                    $insert_stmt->close();
                    return 'Tweet Creation cannot be done at this moment.';
                }elseif($insert_stmt->affected_rows>0){
                    $insert_stmt->close();
                    return 'Tweet Added.<br><br>';
                }else{
                    $insert_stmt->close();
                    return 'No Tweet were Added.';
                }
            }else{
                return 'Prepare failed: (' . $mysqli->errno . ') ' . $mysqli->error;
            }
        }              ?>

Getting "parse error" Any ideas?

$
0
0

Greetings experts,

 

I am trying to give our users the ability opportunity to preview their data before submitting to the database.

 

So, we have contacts.php with the following:

                       <div class="bs-example">
						<form class="form-inline" action="<?php echo get_option('siteurl'); ?>/form/preview.php" id="contactForm" role="form" method="post">
                         <div class="form-group">
                             <label  for="employeename">Employee Name</label><br>
								<input type="text" name="employeename" id="employeename" style="width:375px;"  placeholder="your name..." class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
				            </div>
		                    <div class="form-group">
                             <label for="ttitle">Title</label><br>
								<input type="text" name="ttitle" id="ttitle" style="width:375px;"  placeholder="Your title..." class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
							</div><br><br>

    <script id="row-template" type="text/x-handlebars-template">
	<div>
		  <!--reseed attribute IDs in case of gap resulting from deletions -->
	     <input type="hidden" name="rowIDs" value="{{rowNumber}}" />
	    <div class="form-group">

								<input type="text" name="sourcename1{{rowNumber}}" id="sourcename1{{rowNumber}}" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
						    </div>
		                    <div class="form-group">
								<input type="text" name="sourceaddress1" id="sourceaddress1{{rowNumber}}" style="width:250px;" class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
							</div>
	                        <div class="form-group">
								<input type="text" name="income1{{rowNumber}}" id="income1{{rowNumber}}" style="width:250px;"  class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
	    </div>
	    <input id="Button{{rowNumber}}" type="button" rel="remove-row" value="Remove" />
	</div>
	</script>
	<div id="addrow">
	    <div>
	    <!--reseed attribute IDs in case of gap resulting from deletions -->
	       <input type="hidden" name="rowIDs" value="{{rowNumber}}" />
	    <div class="form-group">
	        <label for="sourcename1">Name</label><br>
								<input type="text" name="sourcename1" id="sourcename1" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
						    </div>
		                    <div class="form-group">
		                	    <label for="sourceaddress1">Address</label><br>
								<input type="text" name="sourceaddress1" id="sourceaddress1" style="width:250px;" class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
							</div>
	                        <div class="form-group">
	                          <label for="income1">Income</label><br>
								<input type="text" name="income1{{rowNumber}}" id="income1" style="width:250px;"  class="form-control" value="" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
	                <input type="button" value="Add More" rel="add-row" />
	        </div>
	    </div>
	</div><br><br>

There is a whole lot more code than this. I am just trying to simplify.

 

When the user clicks submit, s/he is taken to the preview.php code with following:

<?php
echo "<p>Employee Name: <b>" .$_POST["employeename"]. "</b></p>";
echo "<p>Title: <b>" .$_POST["ttitle"]. "</b></p>";
$rowIDs = $_POST['rowIDs'];
foreach ($rowIDs as $id) {
 echo "Source Name: <b>" $sourcename1 = $_POST['sourcename1' . $id] "</b></p>";

 echo "Source Address: <b> <b>" $sourceaddress1 = $_POST['sourceaddress1' . $id] "</b></p>";
 echo "Income Source:" $income1 = $_POST['income1' . $id] "</b></p>";
}
echo "<input type='hidden' name='employeename[]' value='".$sourcename1."' />";
echo "<input type='hidden' name='ttitle[]' value='".$sourceaddress1."' />";
echo "<input type='hidden' name='sourcename1[]' value='".$income1."' />";

Right now, I am getting an error on the preview.php that says:

 

Parse error: in C:\forms\preview.php on line 2

 

​which is this line:

echo "<p>Employee Name: <b>" .$_POST["employeename"]. "</b></p>";

​It might be obvious but I can't see it.

 

Can you please help?

 

Thanks in advance
 

Help Please

$
0
0

Hey everyone!

 

I have been working on a text based mafia game, and one of the pages is "Weed Farm".

In simple terms, Users can plant seeds and grow them. They can also upgrade there farm, the better the farm, the more they can grow.

Everything works perfect, other than when you plant the seeds, and wait 24 hours, when you go back to sell them, it says you have 0.

 

I guess for some of you guys it'll be simple code, but not for a Noob like me. Any help i will be thankful off. 

 

I have attached the necessary files, many thanks. 

Attached Files

Using SESSIONS in Change Password Script

$
0
0

I am having difficulty finding out what is wrong with these scripts.

When a user logs on a session is started in the logon script:

Login.php:

<?php # - login.php
// This is the login page for the site.
session_start();

require_once ('includes/config.inc.php');
$page_title = 'Login';
include ('includes/header1.html');


if (isset($_POST['submitted'])) {
	require_once('includes/Connect_login.php');


	// Validate the email address:
	if (!empty($_POST['email'])) {
		$e = mysqli_real_escape_string ($dbc, $_POST['email']);
	} else {
		$e = FALSE;
		echo '<p class="error">You forgot to enter your email address!</p>';
	}

	// Validate the password:
	if (!empty($_POST['pass'])) {
		$p = mysqli_real_escape_string ($dbc, $_POST['pass']);
	} else {
		$p = FALSE;
		echo '<p class="error">You forgot to enter your password!</p>';
	}

	// Validate the BMFA No:
	if (!empty($_POST['BMFA'])) {
		$b = mysqli_real_escape_string ($dbc, $_POST['BMFA']);
	} else {
		$b = FALSE;
		echo '<p class="error">You forgot to enter your BMFA number!</p>';
	}

	if ($e && $p && $b) { // If everything's OK.

		// Query the database:
		$q = "SELECT user_id, first_name, user_level, BMFA_No FROM users WHERE (email='$e' AND pass=SHA1('$p') AND BMFA_No= ('$b')) AND active IS NULL";
		$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

		if (@mysqli_num_rows($r) == 1) { // A match was made.

			// Register the values & redirect:
			$_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
			$_SESSION['loggedin']=$_POST['user_id'];
			echo $_POST['user_id'];
			mysqli_free_result($r);
			mysqli_close($dbc);

			$url = BASE_URL . 'mempage.php'; // Define the URL:
			ob_end_clean(); // Delete the buffer.
			header("Location: $url");
			exit(); // Quit the script.

		} else { // No match was made.
			echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>';

		}

	} else { // If everything wasn't OK.
		echo '<p class="error">Please try again.</p>';
	}

	mysqli_close($dbc);

} // End of SUBMIT conditional.

?>

<h1>Login</h1>
<p>Your browser must allow cookies in order to log in.</p>

<form action="login.php" method="post">
	<fieldset>
	<p><b>Email Address:</b> <input type="text" name="email" size="20" maxlength="40" /></p>
	<p><b>Password:</b> <input type="password" name="pass" size="20" maxlength="20" /></p>
	<p><b>BMFA No:</b> <input type="text" name="BMFA" size="20" maxlength="20" /></p>
	<div align="center"><input type="submit" name="submit" value="Login" /></div>
	<input type="hidden" name="submitted" value="TRUE" />
	</fieldset>
</form>
<h2>Forgot your password?  Click on this link:<a href="forgot_password.php"target="_blank">Forgot Password</a></h2>
<?php // Include the HTML footer.
include ('includes/footer1.html');
?>

I am using output buffering, so that I can include files and only send to the server when the form is submitted.

Would this screw up the sessions?

I'm not sure if the way I have set the session is correct on line 48 as there is a session which is saving the array of the MYSQL query.

I am using a book for this example, so I don't understand  how the first session statement is saving the array, if it is not named?

 

The script allows me to login OK and on the page it redirects to I have put a button that allows the user to change their password.

This runs the change_password.php script.

<?php #  Change_password.php
// This page allows a logged-in user to change their password.
session_start();
ob_start;
require_once ('includes/config.inc.php');
$page_title = 'Change Your Password';
include ('includes/header1.html');

// If no first_name session variable exists, redirect the user:
if (!isset($_SESSION['email'])) {

	$url = BASE_URL . 'index.php'; // Define the URL.
	ob_end_clean(); // Delete the buffer.
	header("Location: $url");
	exit(); // Quit the script.
}
print_r($_POST);
if (isset($_POST['submitted'])) {
	require_once('includes/Connect_login.php');

	// Check for a new password and match against the confirmed password:
	$p = FALSE;
	if (preg_match ('/^(\w){4,20}$/', $_POST['password1']) ) {
		if ($_POST['password1'] == $_POST['password2']) {
			$p = mysqli_real_escape_string ($dbc, $_POST['password1']);
		} else {
			echo '<p class="error">Your password did not match the confirmed password!</p>';
		}
	} else {
		echo '<p class="error">Please enter a valid password!</p>';
	}

	if ($p) { // If everything's OK.

		// Make the query.
		$q = "UPDATE users SET pass=SHA1('$p') WHERE user_id={$_SESSION=$_POST['user_id']";
		$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
		if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.

			// Send an email, if desired.
			echo '<h3>Your password has been changed.</h3>';
			mysqli_close($dbc); // Close the database connection.
			include ('includes/footer.html'); // Include the HTML footer.
			exit();

		} else { // If it did not run OK.

			echo '<p class="error">Your password was not changed. Make sure your new password is different than the current password. Contact the system administrator if you think an error occurred.</p>';

		}

	} else { // Failed the validation test.
		echo '<p class="error">Please try again.</p>';
	}

	mysqli_close($dbc); // Close the database connection.

} // End of the main Submit conditional.

?>

<h1>Change Your Password</h1>
<form action="change_password.php" method="post">
	<fieldset>
	<p><b>New Password:</b> <input type="password" name="password1" size="20" maxlength="20" /> <small>Use only letters, numbers, and the underscore. Must be between 4 and 20 characters long.</small></p>
	<p><b>Confirm New Password:</b> <input type="password" name="password2" size="20" maxlength="20" /></p>
	</fieldset>
	<div align="center"><input type="submit" name="submit" value="Change My Password" /></div>
	<input type="hidden" name="submitted" value="TRUE" />
</form>

<?php
include ('includes/footer1.html');
?>

When this runs all I get is a blank page and not the message that the password has been changed.

As there are no error messages I am not sure where the script is wrong.

 

Can someone tell me where I am going wrong?

 

Using websockets between webbrowser client and ReactPHP sockets server

$
0
0

How can I access a ReactPHP sockets server?  Not looking for client side assistance (I will need it be it is a question for another forum) but the server side.  Don't even know where to start. I know the IP and port where the socket server is running.  I saw a client side tutorial which showed creating the connection as websocket = new WebSocket("ws://echo.websocket.org/");. What happens in between?  Thanks 

Can you store $con into an array?

$
0
0

I'm looking for a temporary solution to a database issue.  Eventually, I will put an end to all of this nonsense, so for all those would reply "Why in the world would you do that?"... I didn't.  Someone else did.  I'm just looking for a temporary fix.

 

I have a set of databases all on the same server, same fields, same log in credentials.  I simply want to create a $con array because based on user selection, there may only be one database, or there could be as many as 10 (all of which I would use UNION to join them).

 

I know this is a syntax error on my part, I cannot seem to Google the right information to understand how to do this properly.

$con = array();
$arrlength = count($statedb);
echo "$arrlength<br />";
for ($x = 0; $x < $arrlength; $x++) {
    $con($x) = new mysqli($DBServer, $DBUser, $DBPass, $statedb($x));
    echo $con($x);
}

So in the example above, let's say California was selected, there are 10 databases (all identical in login, layout, but different information).  I'd like there to basically be $con x 10.

 

I think the code above is pretty self explanatory.

Viewing all 13200 articles
Browse latest View live