How to read variables using PHP from a python file? - php

Trying to figure out the best way to do this and I'm getting very odd results. Long story short, we put application config parameters in the backend which is python, the front end PHP used hardcoded parameters and I'm trying to tie that back to the single python file so I don't have to change important config parameters in multiple places, for example to deploy to a different server.
The python file (defaults.py):
import time
#------------------------------------------------------
#Processing Options
#------------------------------------------------------
perform_tests = False
today = time.time()
#------------------------------------------------------
#MySQL Config
#------------------------------------------------------
host = "somehostname.com"
port = 3526
user = "someuser"
pw = "somepass"
db = "someDB"
bulk = 500
table = "Some_table"
The PHP code trying to gather the config variables from it (testing code mostly):
<?php
function db_connect() {
$config_file = fopen("../modules/defaults.py", "r");
if ($config_file) {
while (($line = fgets($config_file)) !== false) {
echo "<script>alert(". (string)$line. ");</script>";
// process the line read.
if(substr($line, 0, 4) === "host"){
//$servername = trim(explode("=",$line)[1]);
$servername = "somehostname.com";
}
}
fclose($handle);
}
echo "<script>alert(". $servername. ");</script>";
//$servername = "somehostname.com";
$username = "someuser";
$password = "somepass";
$dbname = "someDB";
$port = 3526;
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
?>
As you can see, I'm looping thru the python file trying to reassign my hardcoded variables with the variables from the file... there is a good bit of debugging code in there.
So at the moment when you run it it will alert back to you each line from the file... the VERY odd result is that its not alerting the full line (it's alerting "somehostname.com", 3526, "someuser", etc... it's also not alerting the import time line or the commented out lines. This is very odd to me, I expected it to read the lines as strings but fgets appears to me interpreting the code in a very strange way.
I'd like to know what's really happening here and if there is a better way to go about this... without modifying the python file, because the backend uses it everywhere.
Thanks.

This looks much like java .properties file. Despite the fact there is some method invoked in line:
today = time.time()
But you can read those properties as string, you can find some help in this question regarding to reading properties files: Read .properties files using PHP
Once you have all data loaded you would have to evaluate lines with code - hopefully you would recognize them by keys. I know this is only general idea, but I hope you can proceed further on your own.

Related

Php redirct each data to each url

I have a database where I am storing data. Here every full link has a offer link. What I am trying to do? I want to redirect every single data to every different URL. But I failed.
Example:1
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fgoogle.com
redirect link: google.com
Example 2
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fyoutube.com
redirect link: youtube.com
Someone when visiting the full link it should redirect each offer link
Database
Data Insert
PHP Code
You should really post code instead of images. You can post code blocks by posting your code between 3 backticks (`) at the top, and three backticks at the bottom.
However, I tried to copy the code, and edited it. I don’t understand exactly what you are trying to do, but I just made some changes.
Data Insert
<?php
include 'db.php’;
$first = "http://localhost/LearnPHP/test/short2.php/redir&q=";
$magic = urlencode($_POST["longUrl"]);
if($magic) {
$finalUrl = $first . $magic;
$stmt = $conn->prepare("INSERT INTO url (offer_link, full_link) VALUES (?, ?)");
$stmt->bind_param("ss", $magic, $finalUrl);
$stmt->execute();
} else {
$finalUrl = '';
}
?>
In the above code, you can obviously tell I changed some things. First, I don’t have a checking statement inside the insert file. I have put it directly inside of the db.php file. I will post the code for it.
Next, I patched the vulnerability of mySQL injection (https://portswigger.net/web-security/sql-injection) using prepared statements.
db.php
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
For the last bit, can you please tell me exactly what you need to do? Your post isn’t that helpful. Do you want to use $_GET[‘’] for the redirection? Please edit your code. Read this as well: https://stackoverflow.com/help/how-to-ask
For redirection part you can do something like this:
if(isset($_GET['q'])) // if q param available
{
$redirectUrl = urldecode($_GET['q']); // get link
header("Location: $redirectUrl"); // redirect
}
I think that your problem is related to URL decode / encode: LINK

How to Use/Start Laravel Services in "ConfigureLogging" Overridden File?

I have to create separate log files for the companies Laravel 5. I have already done this in Laravel by just putting my logic in global.php file. This makes it easy to trace the errors if a specific company admin puts a complaint. Anyway, in Laravel 5 the whole structure is changed for the framework.
I've tried to override Illuminate\Foundation\Bootstrap\ConfigureLogging class in app/bootstrap directory. Every thing is going fine but when I try to get Company::find($id);, which I needed there, Laravel thrown error Call to a member function connection() on null which means I'm trying to use Laravel services before they get started.
So, I used mysqli PHP library to get company name. Now it's working fine. But somehow I want to use Eloquent instead of mysqli. But don't know how can I use Eloquent in other words starting Laravel Services in such scenarios.
Here is my code:
$companyId = isset($_COOKIE['companyId'])?$_COOKIE['companyId']:null;
if(!(is_null($companyId))){
$today = date('d-m-Y');
if(!file_exists(storage_path().'/logs/'.$today)){
// I've created the Filesystem instance as File Facade was not working here.
$file = new Filesystem;
$file->makeDirectory(storage_path(). '/logs/' . $today, 0777);
} // No problem till here
// I need to get company name from db and want to use the following two lines But...
$company = Company::find($id);
$companyName = str_replace(' ', '_', $company->name).'_'.$companyId;
// ... as laravel services are not yet started I have to use the following mysqli block (13 lines) from mysqli_connect() to mysqli_close()
// ENDING MYSQLI BLOCK
$link = mysqli_connect('localhost', 'root', 'pass', 'myDb', '3306');
if (!$link) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
mysqli_query($link, 'SET NAMES \'utf8\'');
$sql = 'SELECT name FROM companies WHERE id='.$companyId;
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$companyName = $row['name'];
}
}
mysqli_close($link);
// ENDING MYSQLI BLOCK
$log->useDailyFiles(storage_path().'/logs/'.$today.'/'.$companyName.'.log', $app->make('config')->get('app.log_max_files', 5));
}elseif(is_null($companyId)){
$log->useDailyFiles(storagePath().'/logs/laravel.log', $app->make('config')->get('app.log_max_files', 5));
}
Should I change Logging behavior in any other way i.e. using Service Providers or something else? Please help me in this regard.

mysqli_error() expects parameter 1 to be mysqli, null given

I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.

Transferred to new hosting/server - Now having issues with using MySQL for form validation

I'm having a lot of problems with the new hosting, but the more I look at it, it seems that they're all related to doing checks in my database when validating logins, registrations, and submissions. Here's an example of one.
I use jQuery to validate forms. One I use to determine if a username actually exists when a user is trying to log in (don't worry, I also check server side). On my development server, this works flawlessly. If you're not familiar with jQuery Validation, basically this returns a true or false back to the server in a form of some kind of JSON, but I'm not entirely knowledgeable on that part.
The code:
//Database Information vars (removed)
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT username FROM registerusers WHERE username='$username';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
The problem with this is that it always refers to the first clause and returns true, even if the username does not exist. For whatever reason, I think it's always returning 1 for mysql_num_rows($res).
This EXACT code (except for new database vars which I've checked a hundred times to be accurate) works as intended on my development server still. I can only assume that it has something to do with the new server, and that's why I'm asking Stack Overflow, because I have no clue.
The problem is that register_globals is enabled.
This poses a high security problem which is why it is disabled and deprecated.
Changing $login_username to $_GET['login_username']solves the problem.
Using the $_GET and $_POST super global arrays is not a security problem, but you should always sanitize your input (like you do with mysql_real_escape_string()).
Have you tried setting the MySQL connection to a variable, then calling the connection variable as the second parameter inside of the mysql_query? This has sometimes given me an issue on some servers, especially if they have certain debugging methods, errors, and warnings shut off by default:
//Database Information vars (removed)
$connect = mysql_connect ($dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT `username` FROM `registerusers` WHERE `username` = '".$username."';";
$res = mysql_query($query, $connect);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
I've also changed the $query to a concatenated string with the variable, as some servers I have worked on sometimes are finicky in terms of putting variables inside of a string without delimiting them with "..".

Create and import mysql database on shared host in php

I'm trying to write php script that would:
connect to mysql
create database
create user and password
add user to database
import prepared sql file to database
The thing is that it'll be on shared host (and I'm trying to make it universal and work with different hosts). I guess database and db user will be prefixed with my account name (what I use for ftp, to login to control panel, etc) on shared hosts? Something like mylogin_dbname and mylogin_dbuser. It's visible for example in cpanel - when I add database I enter its name and after it's created cpanel shows it as mylogin_somedb. How do I make my script work with this on multiple different shared hosts - add my prefix automatically depending on my main login?
Now working with such code (don't have a clue if it works, that's just what came to my mind):
<?php
mysql_connect("host", "user", "password"); // Connection to MySQL
$query = "CREATE DATABASE somedb;
USE somedb;
SOURCE path/to/sqlfile.sql;
CREATE USER someuser IDENTIFIED BY PASSWORD 'somepass';
GRANT SELECT,INSERT,UPDATE,DELETE ON somedb.* TO 'someuser'#'host';";
$arr= explode( ';', $query );
foreach( $arr as $command )
{
mysql_query( $command );
}
mysql_close(); // Disconnection from MySQL
?>
KISS principle: just use phpMyAdmin? It's almost certainly installed. If it's not, install it.
Its import capability is magnificent. If your database is by any chance too big, gzip it. If it's still to big, try splitting it up in a few pieces. I doubt you need to transfer it as a single big transaction. Do you?
After the explanation in first comment, well, here goes. This is my very simplistic script which does what you want. Except it doesn't take a look at the separators: one query == one line.
<link rel="stylesheet" href="style/contents.css"/>
<?
function timesanitize($v) {
if ($v > 0)
return round($v, 4);
else
return 0;
}
$startmt = microtime();
include_once 'include/db.php';
$f = fopen("db.sql","r");
echo dbGetEngine() . "<br>";
echo "<ul>";
do {
$l = rtrim(fgets($f));
if (strlen($l) == 0)
continue;
if (substr($l, 0, 1) == '#')
continue;
$l = str_replace(
array("\\n"),
array("\n"),
$l);
if (dbGetEngine() == "pgsql")
$l = str_replace(
array("IF NOT EXISTS", "LONGBLOB"),
array("", "TEXT"),
$l);
try {
echo "<li>".nl2br(htmlspecialchars($l));
$mt = microtime();
$db->query($l);
echo "<ul><li>ok - " . timesanitize(microtime() - $mt) . "</ul>";
} catch (PDOException $e) {
echo "<ul><li>".$e->getMessage() . "</ul>";
}
} while (!feof($f));
fclose($f);
echo 'total: ' . timesanitize(microtime() - $startmt);
?>
It also outputs a small statistic of how long each query took. It's based around PDO; I believe PDO was introduced in PHP5.1 or PHP5.2. I think it should be trivial to modify it to work directly with mysql_*() functions, if for some reason you prefer that.
And once again: yes, I know it sucks. But as long as it Works For Me (tm), and possibly You... :-)
To complete the code, here are include/db.php and a sample include/config.php:
include/db.php:
<?
include_once 'include/config.php';
try {
$attribs =
array(
PDO::ATTR_PERSISTENT => $config['db']['persistent'],
PDO::ATTR_ERRMODE => $config['db']['errormode']
);
$db = new PDO(
$config['db']['uri'],
$config['db']['user'],
$config['db']['pass'],
$attribs
);
$db->query("SET NAMES 'utf8'");
$db->query("SET CHARACTER SET 'utf8'");
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
function dbGetEngine() {
global $config;
return substr($config['db']['uri'], 0, strpos($config['db']['uri'], ':'));
}
?>
include/config.php:
<?
//$config['db']['uri'] = 'sqlite:' . realpath('.') . '/site.db'; // PDO's database access URI
$config['db']['uri'] = 'mysql:host=localhost;dbname=sitedb'; // server should be : 195.78.32.7
//$config['db']['uri'] = 'pgsql:host=localhost;dbname=sitedb';
$config['db']['user'] = 'user_goes_here'; // database username
$config['db']['pass'] = 'pass_goes_here'; // database password
$config['db']['persistent'] = false; // should the connection be persistent
$config['db']['errormode'] = PDO::ERRMODE_EXCEPTION; // PDO's error mode
?>
Included are sample connection strings for SQLite, MySQL and PostgreSQL.
The fact that this is on a shared host shouldn't make that much of a difference in my opinion. Whatever your environment, you'll have to use your username and either the database name gets prefixed with that or it doesn't according to hosting setup. That said it is probably smart to adopt a naming convention with your username as a prefix or some other prefix naming convention.
As to what you're trying to do I have some suggestions:
You should run each statement separately (as you do) but add error checking between each step so you don't attempt to source the file if the database wasn't created for instance.
Maybe create separate functions for each kind of operation and send in parameters for the values. This would clean up the code in the longer run.
If you have a situation where something is automatically prefixed to the name you provide and you have to detect the final name, you can probably do a "show databases;" query and search for the name you gave in the results. Then use the complete name for the resulting queries.
Use mysql_error()
http://us3.php.net/manual/en/function.mysql-error.php
So you can see what went wrong.
eg:
if (mysql_query( $command ) === false) {
echo mysql_error();
die;
}
The same for mysql_connect()
if (($link = mysql_connect("host", "user", "password")) === false) {
echo mysql_error();
die;
}
You have to make sure the user you are using has privileges to create databases.
For CPanel I believe you have to use your account username and pass. Then like you said prefix your db name with your username, or it will fail to create.
Regarding import, if upload limit is an issue, there are at least one alternative to phpMyAdmin that allows you to select a file on the webserver instead of uploading it. For example adminer (adminer.org) allows that. In adminer, click "SQL command" and then click "from server"

Categories