My cron job does not work and I was wandering if there is any PHP code which will stop it from forming.
I know how it works, but I want to know what kind go code will not read in PHP code.
One code I found out does not work is sessionstart() and $_SESSION because it saves it on the server like a cookie and cron job does not go through the server or something.
Therefore, is there any other code which will not work from your own knowledge like maybe file_get_contents or fopen() (I don't know if these don't work. Just giving ideas)
EDIT
<?php
$dbhost = "localhost";
$dbuser = "it32_2015";
$dbpass = "it32_2015";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT Title, Pubdate, Link FROM ytable';
mysql_select_db('it32_2015');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$status .= "速報ニュース:".
"{$row['Title']} : ".
"ここでチェック!".
"{$row['Link']}".
"時間:".
"{$row['Pubdate']}".
" #yahoonews END";
}
$statusarray = explode(" END",$status);
$result = mysql_query('SELECT MIN(ID) AS min, MAX(ID) AS max FROM ytable') or exit(mysql_error());
$row = mysql_fetch_assoc($result);
$check = file_get_contents('/home/www2/it32.lady2.itall.co.jp/www/counter.php');
if($check < $row['max']){
if (is_numeric($check)){
$counter = ++$check;
}
}
$fp = fopen('/home/www2/it32.lady2.itall.co.jp/www/counter.php',"w+");
fwrite($fp, $counter);
fclose($fp);
require("/home/www2/it32.lady2.itall.co.jp/www/tweet.php");
?>
Is there any code I cannot use for cron in my code.
Cron jobs i.e. scheduled tasks are scripts that run periodically. As such, the script isn't meant to be interfaced with by a user. It is just meant to carry out an action. So the reason sessions don't work with cron jobs is because there is no user to start a session for. Any PHP function that requires a user to work (e.g. setcookie(), session_start()) will not work. All other functions will.
Edit:
All the functions in your script will work as intended.
Related
I am coding a book store for a school project. We started last semester with html. This semester we are converting it to php for dynamic reasons. I modularized the code the best I can, but when I put the functional section of php in, it prevents all the following html in the php code from displaying. As far as I can tell, I have done everything correctly and can not find the issue.
This is the php call in my index.php
<aside class="lSideMenu">
<table>
<tr><td><h3>Categories</h3></td></tr>
<?php
include_once 'getGenres.php';
popGenres();
?>
<tr><td>Humor</td></tr>
</table>
</aside>
I left the table row after the call for testing and does not show, but when I look at the debug window the table and aside close tags are there. there is other code after that that does not populate as well and my css breaks.
This is the php funtions of getGenres.php
<?php
/**
* Created by PhpStorm.
* User: PoeDawg
* Date: 4/5/2017
* Time: 2:51 PM
*/
function db_connect(){
$host = 'localhost';
$uname = 'root';
$pass = 'root';
$link = new mysqli($host, $uname, $pass);
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
return $link;
}
function popGenres(){
$link = db_connect();
$dbname = 'volga_db';
$db_selected = mysqli_select_db($link, $dbname);
if (!$db_selected) {
die('Could not connect to database: ' . mysqli_error($link));
}
$query = 'SELECT * FROM tblgenres';
$result = mysqli_query($link, $query);
if ( $result ) {
while ( $row = $result->fetch_assoc() ) {
echo "<tr><td>" . $row['genreName'] . "</td></tr>";
}
$result->close();
}
mysqli_close()($link);
}
It does what it is supposed to in that it populates the list of genres, it just prevents the content below the function call from loading in the browser. If i take the php call section out, the page works as it should. Any help would be greatly appreciated.
Your last line of code should be like below,
mysqli_close($link);
I'm trying to insert values extracted from a csv file to a mysql table. It runs but the table is not populated. I've tried to debug for the last XXXX but just can't see my error. Echo-ing out the values give me the correct SQL but when it comes to the INSERT - no dice.
Thanks very much for your help.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
//////////////////////////////// EDIT ////////////////////////////////////
$redirect_num = 500; // Select how many rows to insert each time before refresh.
// More rows = faster insertion. However cannot be too high otherwise it will timeout.
$filename = "ps4_emails.csv"; // The file we are going to get the data from...
$table = "`ps4_emails`";
////////////////////////////// END EDIT //////////////////////////////////
$file = file($filename);
$lines = count($file);
// Have we just redirected?
$nextline = $_GET['nextline'];
if (!isset($nextline)){
$nextline = 0;
}
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
for ($line=$nextline; $line<=$lines; $line++){
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
mysql_query($query,$db);
}
if ($line % $redirect_num){
// something needs to go here
} else {
$nextline = $line+1;
exit ('<meta http-equiv="refresh" content="0;url=texttomysqlemails.php?nextline='.$nextline.'" />');
}
echo ( $line==$lines ) ? "Done" : "";
}
?>
Put your query inside loop in order use it with variable $final_line.
Try this :
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
mysql_query($query,$db);
}
Don't use mysql_*. It's deprecated and removed from PHP 7. Use mysqli_* or PDO.
This seems like a perfect script to run from the command line PHP CLI and therefore you can forget about all the refresh complexity.
If the file is huge, like your comment suggest, loading all the file into memory may also bring you up against the PHP memory limits, so it might be better to read a line at a time rather than the whole file using fgetcsv() which is intended for reading csv files.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
}
?>
You now just run this script from the command line/terminal like
>php script.php
And it can run for minutes/hours/days with no likleyhood of blowing any limits.
I have to mention this or someone will nag me for not saying it
Please dont use the mysql_ database extension, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
When you need to upload the real file, it would also be a good idea to add a restart mechanism, so you can restart the process from whereever a problem happened or someone shut the database down for a backup or some other unforseen hiccup.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$restart_from = 0;
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
// is it a restart?
if ( file_exists('restart.txt') ) {
// its a restart
$restart_from = file_get_contents('restart.txt');
// read up the file to the last good row inserted
for ( $i=0; $i<=$restart_from; $i++ ) {
$data = fget($handle, 1000);
}
}
$upd_cnt = restart_from;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
$upd_cnt++;
file_put_contents('restart.txt', $upd_cnt);
}
?>
The above restart code is not tested, but I have used something very like this in the past very successfully. So you will have to check I have not made any silly mistakes, but it should give you an idea of how to do a restart from the last row successfully updated before a crash.
You can use LOAD DATA INFILE to insert from file.
refer http://dev.mysql.com/doc/refman/5.7/en/load-data.html
insert csv file data into mysql
I have an application where each user gets their own database where each database has the same schema.
I have a script that performs migrations in this fashion:
SHOW databases
Iterate through databases
Execute sql statements
This can take a long time when there are complicated queries that take a lot of time (3 or more seconds)
Is there a way where I can run the sql statements for each database at the same time from one script? Is this dangerous/too resource intensive to do this?
The reason I want to do this, is to prevent downtime as much as possible.
Here is my script now:
<?php
ini_set('display_errors', 1);
set_time_limit(0);
$sql = file_get_contents('../update.sql');
$sql_queries = explode(";", $sql);
$exclude_dbs = array('horde','phppoint_forums','phppoint_site','roundcube', 'pos', 'bntennis_site', 'mysql', 'information_schema', 'performance_schema');
$conn = mysqli_connect("localhost", "root", "PASSWORD");
$show_db_query = mysqli_query($conn, 'SHOW databases');
$databases = array();
while ($row = mysqli_fetch_assoc($show_db_query))
{
if (!in_array($row['Database'], $exclude_dbs))
{
$databases[] = $row['Database'];
}
}
foreach($databases as $database)
{
mysqli_select_db($conn, $database);
echo "Running queries on $database\n***********************************\n";
foreach($sql_queries as $query)
{
if (!empty($query))
{
echo "$query;";
if (!mysqli_query($conn, $query))
{
echo "\n\nERROR: ".mysqli_error($conn)."\n\n";
}
}
}
echo "\n\n";
}
?>
I don't know if the database will hold for that load but basically I would fork the process or spawn it into the background, depending on language.
For php you can fork the process for each database basically running the migrations in parallel.
Hey, I already have a view counter coded, but i need help preventing people from just refreshing and refreshing to add more views. Normally, i Would mark this storing the ip, page name and date viewed in a SQL table where in php, i would run a search to see if someone with that ip has viewed the page within 24 hours, but I run a website that is mostly operated in schools and i want each computer in a computer lab to count as a view when they see the page. Again, i could use cookies but my server isn't sending out cookies right. It works fine on my testserver but not on the dedicated web hosting server. Is there any other way to prevent spam?
Heres my code
function connect() {
$domain = $_SERVER['HTTP_HOST'];
$dbhost = 'censored';
$dbname = 'censored';
$dbuser = 'censored';
$dbpass ='censored';
if ($domain == 'localhost'){
$dbhost = 'localhost';
$dbname = 'db1';
$dbuser = 'root';
$dbpass ='';
}
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$con){
trigger_error("Problem Connecting to the MySQL Server.");
}
$db = mysql_select_db($dbname, $con);
if(!$db){
trigger_error("Problem finding the Database!");
}
return $con;
}
function fetchdata($qry){
connect();
$result = mysql_query($qry);
return $fetch = mysql_fetch_assoc($result);
}
function addcounter($id) {
connect();
$counter = fetchdata("SELECT * FROM counter WHERE `path` = '$id';");
$counter = $counter['counter'];
if(isset($_COOKIE["counter_".$id.""])){
}else{
if ($counter === NULL) {
mysql_query("INSERT INTO counter VALUES (0, '" .$id. "');");
}
echo "<!-- submitting query -->";
mysql_query("UPDATE counter SET counter = `counter`+ 1 WHERE path = ".$id."") or die ('failupdate');
setcookie("counter_$id", "Playcookie_".$id."");
}
}
If you cannot use the user's IP address (presumably because they are behind NAT?) and you cannot use cookies, there's really not much you can do.
You could try to use the IP together with the user agent string (which might be different among different computers in the lab), but this would be both slower and of course far from guaranteed to work.
Other than that I think you 're out of options.
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);
?>