Problem in PHP Code with installation of system - php

Hello i'm having trouble with the install script for my system.
Currectly i try to solve some issues, but now it left me to skip this part and make installation correctly. Can someone help me to solve the code to be correct way.
So i'm struggling in this zone: if ($action == 'result') {
So i skip check the website adress and so one and go directly to install.
But after i enter dbname, host, user, pass, admin, password it does not install the .sql file and gives me error "Database Credential is Not Valid"
<?php
$itemName = 'playlab';
error_reporting(0);
$action = isset($_GET['action']) ? $_GET['action'] : '';
function appUrl()
{
$current = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$exp = explode('?action', $current);
$url = str_replace('index.php', '', $exp[0]);
$url = substr($url, 0, -8);
return $url;
}
if ($action == 'requirements') {
$passed = [];
$failed = [];
$requiredPHP = 8.1;
$currentPHP = explode('.', PHP_VERSION)[0] . '.' . explode('.', PHP_VERSION)[1];
if ($requiredPHP == $currentPHP) {
$passed[] = 'PHP version 8.1 is required';
} else {
$failed[] = 'PHP version 8.1 is required. Your current PHP version is ' . $currentPHP;
}
$extensions = ['BCMath', 'Ctype', 'cURL', 'DOM', 'Fileinfo', 'GD', 'JSON', 'Mbstring', 'OpenSSL', 'PCRE', 'PDO', 'pdo_mysql', 'Tokenizer', 'XML'];
foreach ($extensions as $extension) {
if (extension_loaded($extension)) {
$passed[] = strtoupper($extension) . ' PHP Extension is required';
} else {
$failed[] = strtoupper($extension) . ' PHP Extension is required';
}
}
if (function_exists('curl_version')) {
$passed[] = 'Curl via PHP is required';
} else {
$failed[] = 'Curl via PHP is required';
}
if (file_get_contents(__FILE__)) {
$passed[] = 'file_get_contents() is required';
} else {
$failed[] = 'file_get_contents() is required';
}
if (ini_get('allow_url_fopen')) {
$passed[] = 'allow_url_fopen() is required';
} else {
$failed[] = 'allow_url_fopen() is required';
}
$dirs = ['../core/bootstrap/cache/', '../core/storage/', '../core/storage/app/', '../core/storage/framework/', '../core/storage/logs/'];
foreach ($dirs as $dir) {
$perm = substr(sprintf('%o', fileperms($dir)), -4);
if ($perm >= '0775') {
$passed[] = str_replace("../", "", $dir) . ' is required 0775 permission';
} else {
$failed[] = str_replace("../", "", $dir) . ' is required 0775 permission. Current Permisiion is ' . $perm;
}
}
if (file_exists('database.sql')) {
$passed[] = 'database.sql should be available';
} else {
$failed[] = 'database.sql should be available';
}
if (file_exists('../.htaccess')) {
$passed[] = '".htaccess" should be available in root directory';
} else {
$failed[] = '".htaccess" should be available in root directory';
}
}
if ($action == 'result') {
$url = 'https://license.viserlab.com/';
$params = $_POST;
$params['product'] = $itemName;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
$response = array('error' => 'ok', 'message' => 'Valid license!');
if (#$response['error'] == 'ok') {
try {
$db = new PDO("mysql:host=$_POST[db_host];dbname=$_POST[db_name]", $_POST['db_user'], $_POST['db_pass']);
$dbinfo = $db->query('SELECT VERSION()')->fetchColumn();
$engine = #explode('-', $dbinfo)[1];
$version = #explode('.', $dbinfo)[0] . '.' . #explode('.', $dbinfo)[1];
if (strtolower($engine) == 'mariadb') {
if ($version < 10.3) {
$response['error'] = 'error';
$response['message'] = 'MariaDB 10.3+ Or MySQL 5.7+ Required. <br> Your current PHP version is MariaDB ' . $version;
}
} else {
if ($version < 5.7) {
$response['error'] = 'error';
$response['message'] = 'MariaDB 10.3+ Or MySQL 5.7+ Required. <br> Your current PHP version is MySQL ' . $version;
}
}
} catch (Exception $e) {
$response['error'] = 'error';
$response['message'] = 'Database Credential is Not Valid';
}
}
if (#$response['error'] == 'ok') {
try {
$query = file_get_contents("database.sql");
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->closeCursor();
} catch (Exception $e) {
$response['error'] = 'error';
$response['message'] = 'Problem Occurred When Importing Database!<br>Please Make Sure The Database is Empty.';
}
}
if (#$response['error'] == 'ok') {
try {
$db_name = $_POST['db_name'];
$db_host = $_POST['db_host'];
$db_user = $_POST['db_user'];
$db_pass = $_POST['db_pass'];
$email = $_POST['email'];
$siteurl = appUrl();
$app_key = base64_encode(random_bytes(32));
$envcontent = "
APP_NAME=Laravel
APP_ENV=production
APP_KEY=base64:$app_key
APP_DEBUG=false
APP_URL=$siteurl
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=$db_host
DB_PORT=3306
DB_DATABASE=$db_name
DB_USERNAME=$db_user
DB_PASSWORD=$db_pass
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME='${APP_NAME}'
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY='${PUSHER_APP_KEY}'
MIX_PUSHER_APP_CLUSTER='${PUSHER_APP_CLUSTER}'
";
$envpath = dirname(__DIR__, 1) . '\core\.env';
file_put_contents($envpath, $envcontent);
} catch (Exception $e) {
$response['error'] = 'error';
$response['message'] = 'Problem Occurred When Writing Environment File.';
}
}
if (#$response['error'] == 'ok') {
try {
$db->query("UPDATE admins SET email='" . $_POST['email'] . "', username='" . $_POST['admin_user'] . "', password='" . password_hash($_POST['admin_pass'], PASSWORD_DEFAULT) . "' WHERE username='admin'");
} catch (Exception $e) {
$response['message'] = 'EasyInstaller was unable to set the credentials of admin.';
}
}
}
$sectionTitle = empty($action) ? 'Terms of Use' : $action;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Easy Installer by ViserLab</title>
<link rel="stylesheet" href="../assets/global/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/global/css/all.min.css">
<link rel="stylesheet" href="../assets/global/css/installer.css">
<link rel="shortcut icon" href="https://license.viserlab.com/external/favicon.png" type="image/x-icon">
</head>
<body>
<header class="py-3 border-bottom border-primary bg--dark">
<div class="container">
<div class="d-flex align-items-center justify-content-between header gap-3">
<img class="logo" src="https://license.viserlab.com/external/logo.png" alt="ViserLab">
<h3 class="title">Easy Installer</h3>
</div>
</div>
</header>
<div class="installation-section padding-bottom padding-top">
<div class="container">
<div class="installation-wrapper">
<div class="install-content-area">
<div class="install-item">
<h3 class="title text-center"><?php echo $sectionTitle; ?></h3>
<div class="box-item">
<?php
if ($action == 'result') {
echo '<div class="success-area text-center">';
if (#$response['error'] == 'ok') {
echo '<h2 class="text-success text-uppercase mb-3">Your system has been installed successfully!</h2>';
if (#$response['message']) {
echo '<h5 class="text-warning mb-3">' . $response['message'] . '</h5>';
}
echo '<p class="text-danger lead my-5">Please delete the "install" folder from the server.</p>';
echo '<div class="warning">Go to website and Activate</div>';
} else {
if (#$response['message']) {
echo '<h3 class="text-danger mb-3">' . $response['message'] . '</h3>';
} else {
echo '<h3 class="text-danger mb-3">Your Server is not Capable to Handle the Request.</h3>';
}
echo '<div class="warning mt-2"><h5 class="mb-4 fw-normal">You can ask for support by creating a support ticket.</h5>create ticket</div>';
}
echo '</div>';
} elseif ($action == 'information') {
?>
<form action="?action=result" method="post" class="information-form-area mb--20">
<div class="info-item">
<h5 class="font-weight-normal mb-2">Website URL</h5>
<div class="row">
<div class="information-form-group col-12">
<input name="url" value="<?php echo appUrl(); ?>" type="text" required>
</div>
</div>
</div>
<div class="info-item">
<h5 class="font-weight-normal mb-2">Database Details</h5>
<div class="row">
<div class="information-form-group col-sm-6">
<input type="text" name="db_name" placeholder="Database Name" required>
</div>
<div class="information-form-group col-sm-6">
<input type="text" name="db_host" placeholder="Database Host" required>
</div>
<div class="information-form-group col-sm-6">
<input type="text" name="db_user" placeholder="Database User" required>
</div>
<div class="information-form-group col-sm-6">
<input type="text" name="db_pass" placeholder="Database Password">
</div>
</div>
</div>
<div class="info-item">
<h5 class="font-weight-normal mb-3">Admin Credential</h5>
<div class="row">
<div class="information-form-group col-lg-3 col-sm-6">
<label>Username</label>
<input name="admin_user" type="text" placeholder="Admin Username" required>
</div>
<div class="information-form-group col-lg-3 col-sm-6">
<label>Password</label>
<input name="admin_pass" type="text" placeholder="Admin Password" required>
</div>
<div class="information-form-group col-lg-6">
<label>Email Address</label>
<input name="email" placeholder="Your Email address" type="email" required>
</div>
</div>
</div>
<div class="info-item">
<div class="information-form-group text-end">
<button type="submit" class="theme-button choto">Install Now</button>
</div>
</div>
</form>
<?php
} elseif ($action == 'requirements') {
$btnText = 'View Detailed Check Result';
if (count($failed)) {
$btnText = 'View Passed Check';
echo '<div class="item table-area"><table class="requirment-table">';
foreach ($failed as $fail) {
echo "<tr><td>$fail</td><td><i class='fas fa-times'></i></td></tr>";
}
echo '</table></div>';
}
if (!count($failed)) {
echo '<div class="text-center"><i class="far fa-check-circle success-icon text-success"></i><h5 class="my-3">Requirements Check Passed!</h5></div>';
}
if (count($passed)) {
echo '<div class="text-center my-3"><button class="btn passed-btn" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePassed" aria-expanded="false" aria-controls="collapsePassed">' . $btnText . '</button></div>';
echo '<div class="collapse mb-4" id="collapsePassed"><div class="item table-area"><table class="requirment-table">';
foreach ($passed as $pass) {
echo "<tr><td>$pass</td><td><i class='fas fa-check'></i></td></tr>";
}
echo '</table></div></div>';
}
echo '<div class="item text-end mt-3">';
if (count($failed)) {
echo '<a class="theme-button btn-warning choto" href="?action=requirements">ReCheck <i class="fa fa-sync-alt"></i></a>';
} else {
echo '<a class="theme-button choto" href="?action=information">Next Step <i class="fa fa-angle-double-right"></i></a>';
}
echo '</div>';
} else {
?>
<div class="item">
<h4 class="subtitle">License to be used on one(1) domain(website) only!</h4>
<p> The Regular license is for one website or domain only. If you want to use it on multiple websites or domains you have to purchase more licenses (1 website = 1 license). The Regular License grants you an ongoing, non-exclusive, worldwide license to make use of the item.</p>
</div>
<div class="item">
<h5 class="subtitle font-weight-bold">You Can:</h5>
<ul class="check-list">
<li> Use on one(1) domain only. </li>
<li> Modify or edit as you want. </li>
<li> Translate to your choice of language(s).</li>
</ul>
<span class="text-warning"><i class="fas fa-exclamation-triangle"></i> If any issue or error occurred for your modification on our code/database, we will not be responsible for that. </span>
</div>
<div class="item">
<h5 class="subtitle font-weight-bold">You Cannot: </h5>
<ul class="check-list">
<li class="no"> Resell, distribute, give away, or trade by any means to any third party or individual. </li>
<li class="no"> Include this product into other products sold on any market or affiliate websites. </li>
<li class="no"> Use on more than one(1) domain. </li>
</ul>
</div>
<div class="item">
<p class="info">For more information, Please Check The License FAQ</p>
</div>
<div class="item text-end">
I Agree, Next Step
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="py-3 text-center bg--dark border-top border-primary">
<div class="container">
<p class="m-0 font-weight-bold">©<?php echo Date('Y') ?> - All Right Reserved by ViserLab</p>
</div>
</footer>
<script src="../assets/global/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Related

How to display data from mysql using php to html page

Hi I'm learning php and mysql and creating simple user system. Now I wan't to display user data from mysql to the page using PHP. But I'm struggling with that because I can't get data from databasa even though user correctly sign in. I don't know what is wrong with the code, can't find problem and I was trying difference ways to grab data and display but nothing is working and always variable with data is empty.
login-process.php
<?php
include('connection.php');
$error = array();
$email = $_POST['email'];
if(empty($email)){
$error[] = 'Email can not be empty!';
}
$password = $_POST['password'];
if(empty($password)){
$error[] = 'Password can not be empty!';
}
if(empty($error)){
// query
$query = "SELECT userID, firstName, lastName, email, password, profileImage FROM user WHERE email=?";
$q = mysqli_stmt_init($conn);
mysqli_stmt_prepare($q, $query);
mysqli_stmt_bind_param($q, 's', $email);
mysqli_stmt_execute($q);
// store result
$result = mysqli_stmt_get_result($q);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(!empty($row)){
// checking password
// unhasing password
if(password_verify($password, $row['password'])){
header('location: user-profile.php');
exit();
} else {
echo "You are not a member";
}
}
}
// get user info
function get_user_info($con, $userID){
$query = "SELECT firstName, lastName, email, profileImage FROM user WHERE userID=?";
$q = mysqli_stmt_init($con);
mysqli_stmt_prepare($q, $query);
// bind the statement
mysqli_stmt_bind_param($q, 'i', $userID);
// execute sql statement
mysqli_stmt_execute($q);
$result = mysqli_stmt_get_result($q);
$row = mysqli_fetch_array($result);
return empty($row) ? false : $row;
}
user-profile.php
<?php
session_start();
include ('header.php');
$user = array();
if(isset($_SESSION['userID'])){
require ('mysqli_connect.php');
$user = get_user_info($con, $_SESSION['userID']);
}
?>
<section id="main-site">
<div class="container py-5">
<div class="row">
<div class="col-4 offset-4 shadow py-4">
<div class="upload-profile-image d-flex justify-content-center pb-5">
<div class="text-center">
<img class="img rounded-circle" style="width: 200px; height: 200px;" src="<?php echo isset($user['profileImage']) ? $user['profileImage'] : './assets/profile/beard.png'; ?>" alt="">
<h4 class="py-3">
<?php
if(isset($user['firstName'])){
printf('%s %s', $user['firstName'], $user['lastName'] );
}
?>
</h4>
</div>
</div>
<div class="user-info px-3">
<ul class="font-ubuntu navbar-nav">
<li class="nav-link"><b>First Name: </b><span><?php echo isset($user['firstName']) ? $user['firstName'] : ''; ?></span></li>
<li class="nav-link"><b>Last Name: </b><span><?php echo isset($user['lastName']) ? $user['lastName'] : ''; ?></span></li>
<li class="nav-link"><b>Email: </b><span><?php echo isset($user['email']) ? $user['email'] : ''; ?></span></li>
</ul>
</div>
</div>
</div>
</div>
</section>
<?php
include "footer.php";
?>
login.php
<?php
session_start();
include ('header.php');
include('login-process.php');
?>
<?php
$user = array();
require ('connection.php');
if(isset($_SESSION['userID'])){
$user = get_user_info($conn, $_SESSION['userID']);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
require ('login-process.php');
}
?>
<section id="register">
<nav class="navbar nav">
<img src="./image/logo.png" width="150px" height="150px" alt="">
</nav>
<div class="row ml-5 m-0">
<div class="col-lg-4 offset-lg-1">
<div class="text-center pb-5">
<h1 class="login-title text-white">Sign in.</h1>
<p class="p-1 m-0 font-poppins text-white-50">Welcome back! Please enter your details.</p>
</div>
<div class="upload-profile-image d-flex justify-content-center pb-5">
<div class="text-center">
<div class="d-flex justify-content-center">
<img class="camera-icon" src="./image/camera.png" alt="camera">
</div>
<img src=<?php echo isset($user['profileImage']) ? $user['profileImage']: "./assets/profile-picture/avatar.jpg"; ?> style="width: 200px; height: 200px" class="img rounded-circle" alt="profile">
<small class="form-text text-white-50">Choose Image</small>
<input type="file" form="reg-form" class="form-control-file" name="profileUpload" id="upload-profile">
</div>
</div>
<div class="d-flex justify-content-center">
<form action="login.php" method="post" enctype="multipart/form-data" id="reg-form">
<div class="form-row my-4">
<div class="col">
<input type="email" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" required name="email" id="email" class="form-control" placeholder="Email*">
</div>
</div>
<div class="form-row my-4">
<div class="col">
<input type="password" required name="password" id="password" class="form-control" placeholder="Password*">
</div>
</div>
<small id="login-error" class="text-danger">hi</small>
<div class="form-inline">
<input type="checkbox" name="agreement" class="form-check-input">
<label for="agreement" class="form-check-label pr-3 font-poppins text-white-50">Remember for 30 days</label>
Forgot password
</div>
<div class="submit-btn text-center my-5">
<button type="submit" onclick="confirmPassword(event)" class="btn btn-dark rounded-pill text-white px-5 py-3">Create account</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
include ('footer.php');
?>
register-process.php
<?php
include ('connection.php');
//data from the form
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$files = $_FILES['profileUpload'];
$profileImage = upload_profile("./assets/profile-picture", $files);
//sending data from input to the database
$sql = "INSERT INTO user VALUES (DEFAULT , '$firstName', '$lastName', '$email', '$password', '$profileImage', NOW())";
if (mysqli_query($conn, $sql)) {
session_start();
$_SESSION['userID'] = mysqli_insert_id($con);
header('location:login.php');
exit();
} else {
echo "ERROR";
echo mysqli_error($conn);
}
//image
function upload_profile($path, $file){
$targetDir = $path;
$default = "avatar.jpg";
$filename = basename($file['name']);
$targetFilePath = $targetDir.$filename;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(!empty($filename)){
// file format
$allowType = array('jpg', 'png', 'gif', 'jpeg');
if(in_array($fileType, $allowType)){
// send file to the folder
if(move_uploaded_file($file['tmp_name'], $targetFilePath)){
return $targetFilePath;
};
}
}
//if user does not load picture return the default one
return $path .$default;
}
I would like to ask for code example how to display data from database into website when I have ID
You're not setting $_SESSION['userId'] when a user logs in successfully, so the part
if(isset($_SESSION['userID'])){
$user = get_user_info($conn, $_SESSION['userID']);
}
will not trigger and $user will not be set.
Change
if(password_verify($password, $row['password'])){
header('location: user-profile.php');
exit();
} else {
echo "You are not a member";
}
to
if(password_verify($password, $row['password'])){
$_SESSION['userId'] = $row['userId']
header('location: user-profile.php');
exit();
} else {
echo "You are not a member";
}
You haven't set the value for $_SESSION['userID']
use this
session_start();
$user_id = $_SESSION['userID'];
hope it will solve your problem

How do i post a $_GET variable value using a REQUEST METHOD

I am trying to post a $_GET value so it cant insert the variable value into the database using $_SERVER["REQUEST_METHOD"].
<?php require_once("../includes/initialize.php"); ?>
<?php include("../includes/form_validation_card.php"); ?>
<?php $username = $_SESSION['username']; ?>
<?php
if(!isset($_GET['total']) && !isset($_GET['order_id'])){
redirect_to('order_summary.php');
}
$total = $_GET['total'];
$order = $_GET['order_id'];
?>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<br/><br/><?php echo output_message($message); ?>
</div>
<div class="row ">
<div class="jumbo jumbotron-fluid mx-auto d-block" style="height: 500px; width: 440px; background-color:#DCDCDC; border-radius: 5px;" >
<div class="text-center" style="margin: 3px;"><img src="logo/eden_petshop_logo.png" width="32" height="32"/><?php echo $found_user['first_name']; ?> <?php echo $found_user['last_name']; ?></div>
<p class="text-center">order id: #<?php echo $order; ?></p>
<h4 class="display-4 lead text-center">N<?php echo $total; ?></h4>
<div class="col-sm-6 col-sm-offset-3 mx-auto d-block">
<?php echo output_message($message); ?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<div class="col">
<input type="text" name="card_number" onchange="trim(this)" placeholder="Card Number" class="form-control" id="card_number"/>
<span style="color: #EA4335"><?= $card_number_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" name="mm_yy" class="form-control" onchange="trim(this)" placeholder="MM/YY">
<span style="color: #EA4335"><?= $mm_yy_error; ?></span>
</div>
<div class="col">
<input type="password" name="cvv" class="form-control" onchange="trim(this)" placeholder="CVV">
<span style="color: #EA4335"><?= $cvv_error; ?></span>
</div>
</div>
</div>
<div class="col-sm-12 col-sm-push-3">
<button type="submit" name="submit" value="Pay" class="btn bg-info btn-sm btn-block" onClick="return confirm('Are you sure your details are correct?');">Pay</button>
</div>
</form>
</div>
</div>
</div>
<?php include_layout_template('footer2.php'); ?>
This is the input display page but i am trying to the $total and $order $_GET variables insert into the database... Please note that every other part of the code assignment is working fine.
<?php
//define variables and set them to empty values
$total_error = $order_error = $card_number_error = $mm_yy_error = $cvv_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["card_number"])){
$card_number_error = "<div class=''>Card number is required</div>";
}else{
$card_number = test_input($_POST["card_number"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{16,}$/",$card_number)){
$card_number_error = "<div>Only 16 numbers allowed</div>";
}
}
if(empty($_POST["mm_yy"])){
$mm_yy_error = "<div class=''>Card expiry is required</div>";
}else{
$mm_yy = test_input($_POST["mm_yy"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$mm_yy)){
$mm_yy_error = "<div class=''>Only numbers allowed</div>";
}
}
if(empty($_POST["cvv"])){
$cvv_error = "<div class=''>Card verification is required</div>";
}else {
$cvv = test_input($_POST["cvv"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$cvv)){
$cvv_error = "<div class=''>Card verification must not be more than 3 numbers</div>";
}
}
if($card_number_error == "" && $mm_yy_error == "" && $cvv_error == ""){
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968350124';
$token = str_shuffle($token);
$token = substr($token, 0, 15);
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
$email = $found_user['email_address'];
$pay = new Payment();
$pay->username = $username;
$pay->order_id = $order;
$pay->total = $total;
$pay->card_number = $card_number;
$pay->expiry = $mm_yy;
$pay->cvv = $cvv;
$pay->transaction_id = $token;
$pay->status = 0;
$pay->created_at = $timestamp;
if($pay->save()){
//$mail = new Mail();
//$mail->email_address = $email_address;
//$mail->send_transaction_confirmation();
unset($_SESSION['shopping_cart']);
$session->message('<div class="btn bg-success">Congratulations!!! Your order has been processed.</div>');
redirect_to('photos.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
Please note that my $order and total are not getting inserted into my database... Any assistance on my preg_match would be appreciated... Thanks in advance.
You need to use $_POST in your broken code instead of $_GET. Notice your working code used $_POST instead, which is why it works.

files wont upload to server

Hi I am having trouble uploading files to my server, they enter the database fine and the path is correct but for some reason the files just wont go in.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_FILES['ppt']['name'] AS $name) {
$i = 1;
$ppt = strtolower(str_replace(' ', '_', $name.$i));
$pathinfo = pathinfo($name, PATHINFO_EXTENSION);
$data = array(
'eid' => $_GET['id'],
'ppt_filename' => $name.$i,
'ppt_extension' => $pathinfo
);
$db::table('ppts')
->insert($data);
if ($_FILES['ppt']['tmp_name']) {
try {
move_uploaded_file($_FILES['ppt']['tmp_name'], DOCROOT . '/_data/ppt/' . $name . '.' . $pathinfo);
} catch (Exception $e) {
echo 'broken';
exit;
}
$i++;
}
}
}
This is the PHP im using to handle the post.
<div class="card bg-grey">
<h4 class="card-header bg-blue text-white text-bold">Uploads</h4>
<div class="card-block">
<div id="<?php echo $field_name; ?>" class="form-group <?php echo $_ERROR[$field_name] ? ' has-danger' : ''; ?>">
<input <?php echo ($_SESSION['level'] == 1 || $event->created_by == $_SESSION['id'] ? '' : 'readonly="readonly"'); ?> type="file" name="ppt[]" class="form-control" placeholder=""/>
<label>Powerpoint</label>
</div>
</div>
</div>
This is the HTML where I am submitting the file

Header location not work

Hello I have a method to added text on picture:
class Generate
{
public function image($name, $surname, $city){
if (empty($_GET['name'])) {
return header("Location: https://wsaib.pl/index.php?error=name&surname=$surname&city=$city");
//exit();
} elseif(strlen(mb_strlen($_GET['name'])) > 20){
return header("Location: index.php?error=longname&surname=$surname&city=$city");
//exit();
} elseif($_GET['surname'] === null) {
return header("Location: index.php?error=surname&name=$name&city=$city");
//exit();
} elseif (strlen(mb_strlen($_GET['surname'])) > 20){
return header("Location: index.php?error=longsurname&name=$name&city=$city");
//exit();
} elseif($_GET['city'] === null) {
return header("Location: index.php?error=city&name=$name&surname=$surname");
//exit();
} elseif (strlen(mb_strlen($_GET['city'])) > 15){
return header("Location: index.php?error=longcity&name=$name&surname=$surname");
//exit();
} else {
if ((isset($_GET['send']) && $_GET['send'] == 'card') && (isset($_GET['name']) && $_GET['name'] == $name) && (isset($_GET['surname']) && $_GET['surname'] == $surname) && (isset($_GET['city']) && $_GET['city'] == $city)) {
$getName = $name;
$getSurname = $surname;
$getCity = $city;
//$getWishes = "";
$today = date("d.m.Y");
$text_length = 38;
//$textName = wordwrap($getName, $text_length, "<br />", true);
$textSurname= wordwrap($getSurname, 18, "-<br />", true);
$textCity = wordwrap($getCity, 11, "-<br />", true);
//$textN = str_replace('<br />', "\n", $textName);
$textS = str_replace('<br />', "\n", $textSurname);
$textC = str_replace('<br />', "\n", $textCity);
$picture = imagecreatefrompng("merry-christmas.png");
//$black = imagecolorallocate($picture, 0, 0, 0);
$white = imagecolorallocate($picture, 0xFF, 0xFF, 0xFF);
// zyczenia
//imagettftext($picture, 18, 2, 20, 60, $white, 'fonts/Courgette/Courgette-Regular.ttf', trim(ucfirst($textW)));
// imie i nazwisko
if (strlen($getName) >= 15 ) {
imagettftext($picture, 35, 5, 280, 540, $white, 'fonts/Cookie/Cookie-Regular.ttf', trim(ucfirst($getName)));
imagettftext($picture, 35, 5, 280, 590, $white, 'fonts/Cookie/Cookie-Regular.ttf', trim(ucfirst($textS)));
} else {
imagettftext($picture, 35, 5, 280, 540, $white, 'fonts/Cookie/Cookie-Regular.ttf', trim(ucfirst($getName . " " . $textS)));
}
// data
imagettftext($picture, 20, 0, 530, 710, $white, 'fonts/Cookie/Cookie-Regular.ttf', trim(ucfirst($textC.", ".$today)));
header("Content-type: image/png");
$generateImage = imagepng($picture, "kartka_swiateczna_wsaib.png");
//imagedestroy($picture, "kartka_swiateczna_wsaib.png");
}
}
}
public function location($getName, $getSurname, $getCity){
return header("Location: index.php?query=done&name=$getName&surname=$getSurname&city=$getCity");
}
And file form:
<?php
require_once "generator.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Kartka Świąteczna</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="Stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="./bootstrap-3.3.7-dist/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="./bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="./bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body style="background-color: #c13213">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
#$getName = $_GET['name'];
#$getSurname = $_GET['surname'];
#$getCity = $_GET['city'];
if ( (isset($_GET['send']) && $_GET['send'] === 'card') && (isset($_GET['name']) && $_GET['name'] === $getName) && (isset($_GET['surname']) && $_GET['surname'] === $getSurname) && (isset($_GET['city']) && $_GET['city'] === $getCity)) {
$image = new Generate();
$image->image($getName, $getSurname, $getCity); // zamiana !!!!!!!
$image->location($getName, $getSurname, $getCity); // zamiana !!!!!!!
} if (isset($_GET['query']) && $_GET['query'] === 'done'){
$saveFile = "kartka_swiateczna_wsaib.png";
echo '<img src="' . $saveFile . '" id="kartka-photo" width="100%" height="100%"/>'; ?>
<p><a class="btn btn-success" href="kartka_swiateczna_wsaib.png" download="kartka_swiateczna_wsaib.png">Pobierz kartkę</a></p>
<?php } else { ?>
<img src="merry-christmas.png" id="kartka-photo" width="100%" height="100%">
<?php }
?>
</div>
<div class="col-md-4">
<p id="title">Zaprojektuj kartkę</p>
<form action="index.php" method="get">
<input type="text" class="form-control" placeholder="Podaj imię" id="name" name="name" value="<?php echo $getName; ?>"><div id="counterName"></div><br />
<?php if (isset($_GET['error']) && $_GET['error'] === 'name') { ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Nie podałeś imienia.</strong>
</div>
<?php } elseif (isset($_GET['error']) && $_GET['error'] === 'longname'){ ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Maksymalna długość imienia to 20 znaków.</strong>
</div>
<?php } ?>
<input type="text" class="form-control" placeholder="Podaj nazwisko" id="surname" name="surname" value="<?php echo $getSurname; ?>"><div id="counterSurname"></div><br />
<?php if (isset($_GET['error']) && $_GET['error'] === 'surname') { ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Nie podałeś nazwiska.</strong>
</div>
<?php } elseif (isset($_GET['error']) && $_GET['error'] === 'longsurname'){ ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Maksymalna długość nazwiska to 20 znaków.</strong>
</div>
<?php } ?>
<input type="text" class="form-control" placeholder="Podaj miasto" id="city" name="city" value="<?php echo $getCity; ?>"><div id="counterCity"></div><br />
<?php if (isset($_GET['error']) && $_GET['error'] === 'city') { ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Nie podałeś nazwy miasta.</strong>
</div>
<?php } elseif (isset($_GET['error']) && $_GET['error'] === 'longcity'){ ?>
<div class="alert alert-danger fade in">
×
<strong><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Maksymalna długość miasta to 15 znaków.</strong>
</div>
<?php } ?>
<button type="submit" class="btn btn-info" name="send" id="send" value="card" style="margin-bottom: 20px;">Generuj</button>
Odśwież
<?php
if (isset($_GET['query']) && $_GET['query'] === 'done') { ?>
<div class="alert alert-success fade in">
×
<strong><span class="glyphicon glyphicon-ok" aria-hidden="true"></span> Grafika została wygenerowana poprawnie, możesz ją teraz pobrać kikając na przycisk <i>Pobierz kartkę</i>.</strong>
</div>
<?php } ?>
</form>
</div>
</div>
</div>
<script type="text/javascript">
var minName = 20;
document.querySelector('#name').onkeyup = function(e){
document.querySelector('#counterName').innerHTML =
this.value.length <= minName
? 'Pozostało '+(minName - this.value.length)+' znaków.'
: 'Imię zbyt długie!';
}
var minSurname = 20;
document.querySelector('#surname').onkeyup = function(e){
document.querySelector('#counterSurname').innerHTML =
this.value.length <= minSurname
? 'Pozostało '+(minSurname - this.value.length)+' znaków.'
: 'Nazwisko zbyt długie!';
}
var minCity = 15;
document.querySelector('#city').onkeyup = function(e){
document.querySelector('#counterCity').innerHTML =
this.value.length <= minCity
? 'Pozostało '+(minCity - this.value.length)+' znaków.'
: 'Nazwa miasta zbyt długa!';
}
</script>
The problem is with function Header Location:
return header("Location: index.php?error=longcity&name=$name&surname=$surname");
In GET (in url) I have ONLY name=$name&surname=$surname but function header not returned error=longcity. Where is the problem ? When I added to url for example ?query=done script work ok. I don't know were is the error.
I found solution. I have to add at the beginning of the file index.php:
<?php ob_start(); ?>
http://php.net/manual/en/function.ob-start.php
This is very good answer: How to fix "Headers already sent" error in PHP

delete image ins database mysql from dashboard php

hi i need help i have problem in my code and i can't figure the solutions please help me .
this is the dashboard:
image dashboard
and this is problem after click on delete:
delete problem
and this is my code php of posts file:
<?php
/*
===========================================================
=== Manage Members Page ===
=== You can add | edit | delete Members from here ===
===========================================================
*/
session_start();
if (isset($_SESSION['Username'])) {
include 'init.php';
$pageTitle = 'Posts';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage' ;
//Start Manage Page
if ($do == 'Manage'){ // Manage Members Page
$sort = 'ASC';
$sort_arry = array('ASC', 'DESC');
if(isset($_GET['sort']) && in_array($_GET['sort'], $sort_arry)) {
$sort = $_GET['sort'];
}
$stmt2 = $con->prepare("SELECT * FROM posts ORDER BY Ordering $sort");
$stmt2->execute();
$rows = $stmt2->fetchAll();
?>
<h1 class="text-center"> Manage Posts </h1>
<div class="container categories">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-edit"></i> Manage Posts
<div class="ordering pull-right">
<i class="fa fa-sort"> </i>Ordering: [
<a class="<?php if ($sort == 'ASC') { echo 'active'; } ?>" href="?sort=ASC">Asc </a> |
<a class="<?php if ($sort == 'DESC') { echo 'active'; } ?>" href="?sort=DESC">Desc </a>
]
</div>
</div>
<div class="row">
<?php
foreach ($rows as $image) {
echo '<div class="col-md-3 col-sm-4 "><div class="thumbnail">';
echo '<h2 class="h4">'.$image['Name']. '</h2><div class="main">';
echo '<img src="data:image;base64,'.$image['Image'].' " alt="image name" title="image title" width="255" heigth="255">';
echo '</div>';
echo '<table class="table table-bordered">';
echo '<tr>';
echo '<td>' . "<a href='posts.php?do=Edit&id=". $image['ID'] ."' class='btn btn-xs btn-primary'><i class='fa fa-edit'></i> edit</a>" . '</td>';
echo '<td>' . "<a href='posts.php?do=Delete&id=". $image['ID'] ."' class='btn btn-xs btn-danger'><i class='fa fa-close'></i> Delete</a>" . '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
echo '</div>';
}
?>
</div>
<?php } elseif ($do == 'Add') { //add Member page ?>
<h1 class="text-center"> ajouter un nouveau post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Insert" method="POST">
<!-- start Username fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="image-name" class="form-control" autocomplete="off" placeholder="username pour se connecter dans le site Web" required />
</div>
</div>
<!-- end Username fieled -->
<!-- start Password fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" placeholder="mot de passe doit être difficile et complexe" required/>
</div>
</div>
<!-- end Password fieled -->
<!-- start Full name fieled -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- end Full name fieled -->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Ajouter" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</form>
</div>
<?php
} elseif ($do == 'Insert') {
//insert Members Page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h1 class='text-center'> insert an post </h1>";
echo "<div class='container'>";
// Get variable from the form
$name = $_POST['image-name'];
$image= addslashes($_FILES['image']['tmp_name']);
$image= file_get_contents($image);
$image= base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (strlen($name) < 4) {
$formErrors[] = "title name cant be less then <strong> 4 caracter</strong>";
}
if (strlen($name) > 20) {
$formErrors[] = "title name cant be More then <strong> 20 caracter</strong>";
}
if (empty($name)) {
$formErrors[] = "Username Cant Be <strong>Empty</strong>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo "<div class='alert alert-danger'>" . $Error . "</div>";
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// check if user exist in database
$check = checkItem("Username", "users", $user);
if ($check == 1) {
$theMsg = "<div class='alert alert-danger'> Sorry this user is exist </div>";
redirectHome($theMsg, 'back');
} else {
// Insert User info into database
$stmt = $con->prepare("INSERT INTO posts(Name, Image, Cat_id)
VALUES (:name, :image, :cat)");
$stmt->execute(array(
'name' => $name,
'image' => $image,
'cat' => $cat,
));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Inserted </div> ';
redirectHome($theMsg, 'back', 5);
}
}
} else {
echo "<div class='container'>";
$theMsg = '<div class="alert alert-danger"> Sorry you cant browse this page directely </div>';
redirectHome($theMsg, 'back', 5); // 6 is secend of redirect to page in function
echo "</div>";
}
echo "</div>";
} elseif ($do == 'Edit') { // Edit Page
//check if GET request userid Is numeric & Get The integer value of it
$post = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$stmt = $con->prepare("SELECT * FROM posts WHERE ID = ? LIMIT 1");
// execute Query
$stmt->execute(array($post));
//fetch the Data
$row = $stmt->fetch();
// The row count
$count = $stmt->rowCount();
// If Ther's Such Id show The Form
if ($count > 0) { ?>
<h1 class="text-center"> Modifier Post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Update" method="POST">
<div class="col-md-6 col-md-offset-3 panel">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<!-- start title fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="name" class="form-control" autocomplete="off" required value="<?php echo $row['Name']; ?>" >
</div>
</div>
<!-- end title field -->
<!-- start image filed -->
<div class="form-group">
<label class="col-sm-2 control-label">image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" />
</div>
</div>
<!-- end image filed -->
<!-- start Categories filed -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- Categories end-->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="sauvegarder" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</div>
</form>
</div>
<?php
// if there's No Such id Show Error Message
} else {
echo "<div class='container'>";
$theMsg = "<div class='alert alert-danger'>Theres is no such Id</div>";
redirectHome($theMsg);
echo "</div>";
}
} elseif ($do == 'Update') {
echo "<h1 class='text-center'> mis a jour Membre </h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get variable from the form
$id = $_POST['id'];
$name = $_POST['name'];
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (empty($name)) {
$formErrors[] = "<div class='alert alert-danger'>Username Cant Be <strong>Empty</strong> </div>";
}
if (empty($image)) {
$formErrors[] = "<div class='alert alert-danger'>FullName Cant Be <strong>Empty</strong></div>";
}
if (empty($cat)) {
$formErrors[] = "<div class='alert alert-danger'>Email Cant Be <strong>Empty</strong></div>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo $Error;
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// Update The Database With This Info
$stmt = $con->prepare("UPDATE posts SET Name = ? , Image = ? , Cat_id = ? WHERE ID = ?");
$stmt->execute(array($name, $image, $cat, $id));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Updated </div> ';
redirectHome($theMsg, 'back');
}
} else {
$theMsg = '<div class="alert alert-danger">Sorry you cant browse this page directely </div>';
redirectHome($theMsg);
}
echo "</div>";
}
elseif ($do == 'Delete') { // Delete Member Page
echo "<h1 class='text-center'> Delete Membre </h1>";
echo "<div class='container'>";
//check if GET request userid Is numeric & Get The integer value of it
$id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$check = checkItem('id', 'posts', $id);
// If Ther's Such Id show The Form
if ($check > 0) {
$stmt = $con->prepare("DELETE FROM users WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Deleted </div> ';
redirectHome($theMsg);
} else {
$theMsg = "<div class='alert alert-danger'>This id not exist</div>";
redirectHome($theMsg);
}
echo "</div>";
}
include $tpl . 'footer.php';
} else {
header('Location: index.php') ;
exit();
}
from the error, id is the problem.
isset($_GET['id']) && is_numeric($_GET['id'])
i think what u want is
(isset($_GET['id']) && is_numeric($_GET['id']) )//close parantheses in wrong position

Categories