Executing PHP file with crontab - php

Hello I want executing a php file with crontab. This PHP file makes an update of the MySQL database and when I enter the URL in the browser I can execute the file but not as cronjob.
I add
*/5 * * * * php -f /var/www/html/.../update.php >/dev/null 2>&1
to the crontab, and other cronjobs are working well (3rd part extensions).
Do I need to add some code in my PHP file? Thank you.
Here whats inside the PHP file
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE pm_videos SET `description` = REPLACE( `description` ,'Instagram:', '')";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully with Facebook, ";
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "UPDATE pm_videos SET `description` = REPLACE( `description` ,'Facebook:', '')";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully with Facebook, ";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();

Typically, this is caused by a $PATH issue. Try adding this as the first line of your crontab via crontab -u root -e:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
If this doesn't fix it, you'll need to look in your code for places where you might be calling external commands, or depending on the values of environment variables. If this doesn't work, please edit your post and show the contents of update.php.

Related

Can't connect to MySQL via PHP "Name or service not known"

I have a website, which sends input data with AJAX via a PHP script to a MySQL database.
The JavaScript/AJAX part is working but the PHP script doesn't get executed, and if I paste the URL from the PHP script into my browser I get:
Connection failed:php_network_getaddresses: getaddrinfo failed: Name
or service not known
The host, server, password and database are 100% correct.
My PHP code is
<?php
$host = '';
$user = '';
$pswd = '';
$database = '';
$conn = new mysqli($host, $user, $pswd, $database);
if ($conn->connect_error) {
die ("Connection failed:" . $conn->connect_error);
}
echo "Connection successful";
$name = $_POST['name'];
$sql = "INSERT INTO Names(s) VALUES(?)";
if ($stmt = mysqli_prepare($conn, $sql)) {
$sql->bind_param('s', $name);
$stmt = mysqli_parse($conn, $sql);
$stmt->execute();
echo "Created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Besides the initial issue. You have it a bit jumbled up. The bind_param is off.
if ($stmt = mysqli_prepare($conn, $sql)) {
$stmt->bind_param('s', $name);
But, since you don't make it past die(), there is something wrong with either of $host, $user, $pswd, $database or maybe a firewall or DNS issue somewhere. Or the server might not be running as mentioned in the comments.

Is my hosting company messing me up here: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)?

I use the hosting company aPlus.net, and I can't seem to get past a connection error I'm getting when trying to process some php to write database content to a webpage, and I am curious as to if this is because my database appears to not be on the same server as the entire rest of my hosting account, and if there is a way to resolve this in my code? This is my first attempt at writing PHP, and it would be good to know if my code is wrong, or if my hosting company is messing me up. (and either way, how to fix it)
Here's the code that's failing to pull from the database:
{
$con = mysql_connect("localhost","2p5dq9vxmy240651","MY_PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("felineasthma_2p5dq9vxmy240651", $con);
$users_name = $_POST['name'];
$users_comment = $_POST['requests'];
$users_name = mysql_real_escape_string($users_name);
$users_comment = mysql_real_escape_string($users_comment);
$inputid = $_GET['id'];
$query = "
INSERT INTO `felineasthma_2p5dq9vxmy240651`.`submissions` (`id`,
`name`, `requests`, `inputid`) VALUES (NULL,
'$users_name', '$users_comment', '$inputid');";
mysql_query($query);
echo "<h2>Your request has been processed, reload page.</h2>";
mysql_close($con);
}
and here's some screen captures from inside my hosting account (links because I don't have enough posts here yet to upload images, sorry):
felineasthma_2p5dq9vxmy240651 doesn't appear in my hosting account
yet it clearly exists in MySQL Manager, but on a different server
I was even more confused while making the user for this database, as the control panel didn't allow me to make a username, it just randomly assigned one. Help? Advice?
I found a more modern tutorial to learn PHP with, and now everything works, I just need to add security measures now. Here's the working code snippets, if anyone ever comes here asking the same questions.
here's the form action that places the entries into the database:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = $_POST['name'];
$users_request = $_POST['requests'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO submissions (name, requests)
VALUES ('$users_name', '$users_request')";
if (mysqli_query($conn, $sql)) {
header("Location: clv.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
here's the include that puts the database entries onto the page:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, requests, name FROM submissions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "" . $row["requests"]. " - by " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Php command line script can't connect to server using MYSQLI

I have this command line script I am trying to use. It adds image to an already present database and table. The server has Wamp server installed on it and I can access it from a different computer. But everytime I run the script the script just hangs when connecting.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$filename = $argv[1];
//$filename="images/image10.jpg";
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
$servername="192.168.0.34";
$username="root";
$password="password";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection successful";
// insert into table
$sql = sprintf("insert into images(image_type, image, image_size, image_name) values('%s', '%s', '%d', '%s')",
mysql_real_escape_string($size['mime']),
mysql_real_escape_string($imgData),
$size[3],
mysql_real_escape_string($_FILES['userfile']['name']));
if($conn->query($sql) === TRUE) {
echo "Inserted new image successfully";
} else {
echo "Error inserting image: " . $conn->error;
}
echo "Closing the connection";
$conn = null;
?>
I have only installed php and php-mysql on the client. The client is running debian and the sever is running windows 7. Am I missing something else I need to install?
Thank you
You need to install mysqli on your system. See: http://php.net/manual/en/mysqli.installation.php

PHP script wont run on scueduled task (Windows 7)

Attempting to run a php script to update a database every hour with windows 7 Task Scheduler. The File updates when i open it up as a webpage but does not update when i run it from task scheduler . Under the trigger tab I have it set to run daily, and then repeat the task every hour for a duration of indefinetly. Under actions I have it set to Start Program. And the link to my file as C:\Users\jmac\Desktop\testdbconnection.php
Additionally under Start in box I have C:\Users\E15913\Desktop
I have no coditions that should be blcoking it from running. In addition when I test run the file it says it is completed succefully but the database is not updated. I will also post the code below, which once again works when I refresh it or pull it up in a web browser.
<?php
// Did modify login values for privacy
$servername = "10.100.";
$username = "myusername";
$password = "abc123";
$dbname = "informationdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("ALMGrade.csv","r");
while(! feof($file)){
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";\
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);
$conn->close();
?>

Scanning with scanimage from php from a linux host

Here's what the situation is: I am trying to use PHP to call scanimage on a Linux host, then save the resulting file to a web directory for future use.
The below code produces no errors, but when I check out the /tmp directory, file.pnm is blank, and the scanner never starts.
<?php
require('/var/www/olin/includes/functions.php');
$con = connect_db();
//setup the POST variables
if (isset($_POST['submit'])) {
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$license_no = mysqli_real_escape_string($con, $_POST['license_no']);
$comments = mysqli_real_escape_string($con, $_POST['comments']);
}
if ($license_no == '') {
$license_no = "None on File";
}
if ($fname == '' || $lname == '') {
echo '<h1 class="message">Can\'t submit visitor: you are missing information!</h1>';
} else {
//setup the query and prepare it for exection
$query= "insert into visitors (fname, lname, license_no, redsheet, comments)" .
" values (?, ?, ?, 'Allow', ?) on duplicate key update fname = values(fname)," .
"lname = values(lname), license_no = values(license_no), redsheet = values(redsheet)," .
"comments = values(comments)";
$stmnt= mysqli_prepare($con, $query);
//bind the statement parameters to variables
mysqli_stmt_bind_param($stmnt, "ssss", $fname, $lname, $license_no, $comments );
//execute, then close the statment
if (!mysqli_stmt_execute($stmnt)) {
echo "Failed to ececute the query: " . mysqli_error($con);
header('Refresh: 10; url=http://localhost/olin/visitor.php');
}
}
// we'll `try` to scan the license if the checkbox is selected
if (isset($_POST['pic_id'])) {
// get the info from the db
$query = 'select id from visitors where license_no = "'.$license_no.'"';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
// set up the path to save the id to (and put path into db for further look up
// and display)
$dir = ( $id % 30 );
$path = '/var/www/olin/images/licenses/'.$dir.'/'.$id.'-license.png';
$path = addslashes(mysqli_real_escape_string($con, $path));
$path1 = '/images/licenses/'.$dir.'/'.$id.'-license.png';
// start the scan, and save image
$command = '/home/jmd9qs/bin/scan.sh "'.$path.'"';
$update = 'update visitors set id_pic = "'.$path1.'" where id="'.$id.'"';
mysqli_query($con, $update) or die ('Error: ' . mysqli_error($con));
exec($command);
header('Location: http://localhost/olin/visitor.php');
}
}
?>
Can anybody provide any hints?
UPDATE:
I have the server running the command now (I know it's failing because of the Apache2 error log).
Here's the error I get:
scanimage: open of device brother3:bus2;dev1 failed: Invalid argument
I've tried adding the www-data user to the scanner and lp groups, but it seems to have no effect... The scanimage command I'm using works under my normal user and as root, so I'm now positive the command I'm using should work. I am still at a loss...
UPDATE (again):
I've fixed some errors in my code... now the server will scan and successfully save images! However, it only works once and then for some odd reason I have to run the scan.sh (which I put the scanimage command into) through my shell for it to run again... otherwise I get the same error message!
Very weird, I have NO clue why, suggestions wanted!

Categories