Cron job script not working - php

So basically I have this cronjob script which worked on godaddy php 5.4, but in different host it does not work, tried different php versions too. I have correct path to cron, the host support said I did, even presented me with logs. Maybe there is some problem with this script? It basically adds energy points to user account.
<?php
include "../core.php";
//Fuel Refill (by default every 10 minutes)
$sqlusers = mysql_query("SELECT * FROM users WHERE banned='No'");
while ($rowuser = mysql_fetch_assoc($sqlusers)) {
if ($rowuser['fuel'] < $rowuser['fuelcapacity']) {
$userfuelrefill = mysql_query("UPDATE users SET fuel=fuel+1 WHERE username='$rowuser[username]'");
}
}
echo '<meta http-equiv="refresh" content="0;url=../garage">';
?>

mysql extensions are deprecated so try this PDO approach:
<?php
require [full/script/path/]core.php;
$PDO = new PDO([INSERT CONNECTION STRING]);
$result = $PDO->query("SELECT * FROM users WHERE banned='No'")->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row)
{
if ($row['fuel'] < $row['fuelcapacity']) {
$query = "UPDATE users SET fuel=fuel+1 WHERE username= :username";
$query = $PDO->prepare($query);
if ($query->execute(array(':username' => $row[username]))) {
} else { throw new Exception('SQL Query Failed [' . $query->errorCode . ']'); }
}
}
echo '<meta http-equiv="refresh" content="0;url=../garage">';
Now of course there are some things you will have to replace like the connection string and full path but this should work with PHP PDO enabled.

Related

Connecting desktop app to online database via php

I've read a lot of posts on this general subject but I still can't seem to figure it out.
I'm building a Mac/PC desktop application. When a user first authorizes the app, I want to store their info in an online Mysql database. I'm using the JUCE library to call and handle a php file online which in turn handles the updating of the online database. On my desktop app:
String url = "http://www.syntorial.com/onlinePHPFileToCall.php?email=" + email + "&computer=" + SystemStats::getComputerName();
URL authURL(url);
InputStream *input = authURL.createInputStream(true);
String result = input->readString();
And the php file:
<?php
$result = "";
$mysqli = new mysqli('localhost','username','password','dbname');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$mysqli->select_db("UserInfo");
$email = $_GET['email'];
$computer = $_GET['computer'];
$query = "UPDATE UserInfo SET computer = '$computer' WHERE email = '$email'";
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
?>
The result comes back "true" on my desktop app, but the information doesn't actually get saved into the database. If instead of
InputStream *input = authURL.createInputStream(true);
I use:
authURL.launchInDefaultBrowser();
it opens up the php file in a browser and everything works fine. Any ideas what I'm doing wrong?
Joe,
Seems like one of your first question on this forum. So Welcome. You mentioned you want to store information in an online database. But while connecting you added db information about your local via
mysqli('localhost',
. Update localhost to point to an online database by finding its ip address/servername, username and password. Also you will have to ensure the computer where you run this application can connect to that online db.
Here is what I am ran on my local and worked for me.
<?php
$result = "";
$mysqli = new mysqli('localhost','root','','test');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$email = "xyz#yahoo.com";
$computer = "1mycomp";
$query = "UPDATE so1 SET computer = '$computer' WHERE email = '$email'";
/*
Printing the query to check what is being executed.
Remove the below line after program works.
*/
echo $query;
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
Turns out the "true" argument in CreateInputStream was telling it to use POST data instead of GET so the call was ignoring the GET data. Thanks the help.

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

PHP code included in HTML won't update

I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.

PHP seems to be refusing to connect to MySQL

<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.

PHP, Email and Cron

Let me rephrase my question, I have a mysql database that is holding emails to be sent, on a shared host. I would like to run a cron job that will read the database and sent out any messages in the database every 10 minutes or so.
Now my question is, what is the best way with php to read my database and send out the emails in small batched so that I don't overwhelm the shared host.
Assuming the use of PDO, and making some accommodation for not knowing your schema, it might look something like this:
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbuser', 'dbpass');
$msgh = $dbh->prepare('SELECT subject, body from message where listname = :listname');
$msgh->bindParam(':listname', $listname, PDO::PARAM_STR);
$msgh->execute();
$msg = $msgh->fetch(PDO::FETCH_ASSOC);
$usrh = $dbh->prepare('SELECT recipient from userlist where is_subscribed_to = :listname');
$usrh->bindParam(':listname', $listname, PDO::PARAM_STR);
$usrh->execute();
while ($recipient = $usrh->fetch(PDO::FETCH_ASSOC)) {
mail($recipient, $msg['subject'], $msg['body']);
if ($over_throttle) {
sleep(THROTTLE_SLEEP_SECONDS);
$over_throttle = 0;
}
++$over_throttle;
}
As for 'prewritten', you might take a look at phplist.
I would leave the throttling to the email server. Ie, run an email server locally, and have your PHP code relay all these messages to that. Then configure the email server itself to only send out at a certain rate.
Well I came up with this solution similar to the PDO one. Are there any unforeseen problems with running this as a cron job?
<?php
$con = mysql_connect("localhost","root","123456");
$throttle = 0;
$batch = 50;
$pause = 10; // seconds
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("maildb", $con);
// Message Table
$MSGresult = mysql_query("SELECT * FROM msgs");
// User Table
$USERresult = mysql_query("SELECT * FROM members");
while($MSGrow = mysql_fetch_array($MSGresult))
{
while($USERrow = mysql_fetch_array($USERresult))
{
mail($USERrow['email'],$MSGrow['subject'],$MSGrow['body']);
$throttle += 1;
if ($throttle > $batch ) { sleep($pause); $throttle = 0;}
}
mysql_data_seek($USERresult,0);
}
mysql_close($con);
?>

Categories