Jump to content

PHP command line include variables - how to access from root page?


Greywacke
 Share

Recommended Posts

hi all,i have set up cronjobs on cPanel X to execute the following php documents: cronjob_canopyxchange.php & cronjob_reminder.phpit executes the script, and sends the correct mails via PHPMailer, however it seems that variables are not persisted into the main page from the include.how could i enable this? in the cronjobs, the connection is a require_once and that the variables defined are not being persisted. however, this exact same include, in the rest of the site - persists the variables without warnings.how could i resolve this? i guess i would need to set the namespace of the cronjob - let me google on this solong...

Link to comment
Share on other sites

variables defined and set inside the connection include, as array and the connection (link). these warnings do not appear if the pages are called manually from a web browser, however - the following warnings are sent with the cronjobs, which otherwise execute as intended. basically the two variables defined in the connection include at the top of the page.php -q -f /virtual path to/cronjob_reminder.php

<br /><b>Warning</b>:  mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'dwtphovu_f3rr37y'@'localhost' (using password: YES) in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>7</b><br /> <br /><b>Warning</b>:  array_push() [<a href='function.array-push'>function.array-push</a>]: First argument should be an array in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>10</b><br /> <br /><b>Warning</b>:  mysql_select_db(): supplied argument is not a valid MySQL-Link resource in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>49</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Access denied for user 'dwtphovu'@'localhost' (using password: NO) in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>15</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>15</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Access denied for user 'dwtphovu'@'localhost' (using password: NO) in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_reminder.php</b> on line <b>6</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_reminder.php</b> on line <b>6</b><br /> <br /><b>Warning</b>:  mysql_close(): supplied argument is not a valid MySQL-Link resource in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_reminder.php</b> on line <b>36</b><br />

php -q -f /virtual path to/cronjob_canopyxchange.php

<br /><b>Warning</b>:  mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'dwtphovu_f3rr37y'@'localhost' (using password: YES) in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>7</b><br /> <br /><b>Warning</b>:  array_push() [<a href='function.array-push'>function.array-push</a>]: First argument should be an array in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>10</b><br /> <br /><b>Warning</b>:  mysql_select_db(): supplied argument is not a valid MySQL-Link resource in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>49</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Access denied for user 'dwtphovu'@'localhost' (using password: NO) in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>15</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>15</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Access denied for user 'dwtphovu'@'localhost' (using password: NO) in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_canopyxchange.php</b> on line <b>6</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_canopyxchange.php</b> on line <b>6</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Access denied for user 'dwtphovu'@'localhost' (using password: NO) in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_canopyxchange.php</b> on line <b>40</b><br /> <br /><b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_canopyxchange.php</b> on line <b>40</b><br /> <br /><b>Warning</b>:  mysql_close(): supplied argument is not a valid MySQL-Link resource in <b>/home/dwtphovu/public_html/ferrety/fab/public/cronjob_canopyxchange.php</b> on line <b>72</b><br />

Link to comment
Share on other sites

Err, variables aren't persistent in PHP. Only certain superglobals survive from page-to-page. The errors above simply indicate that the script couldn't connect to the database, which could happen for a variety of reasons.

Link to comment
Share on other sites

what i am saying is:the same connection include file that works over the sites pages, generates these errors in the crontasks.is there a way to alternately reference them perhaps? should i refer to these two as $GLOBALS["sql"] and $GLOBALS["conn"] in the cronjob pages? these variables are available in the php pages down through includes, just not in the cronjobs. i'm not talking about session variables or superglobals - merely about the difference in referring to variables in a crontask php doc as opposed to a public webserved php document, these are two distinct crontasks, no "sharing" variables, except the ones within the include - they cascade down on the regular pages without errors. the connection include creates the connection and contains the mysql error handling function as well as mysql timezone setting for retrieval of dates to south african standard time.

Edited by Pierre 'Greywacke' du Toit
Link to comment
Share on other sites

i believe it's likely that too stringent security measures were included with cronjobs. i have made arrangements to let the hosting provider know about this. they recently upgraded their servers and these errors have only started since then.

Link to comment
Share on other sites

According to the Apollo RCA problem-solving process, you're not understanding the problem. You're assuming that the problem is that variables are not persisting. Have you tested that? What happens if you print one of the variables? Does it have the correct value? You can use the error_log function to send anything to the defined error log. Since you're seeing HTML error messages, you probably want to adjust the settings for the CGI script to use different settings than the web stuff. You can disable HTML error messages, for example, so it leaves out the HTML tags from the error messages. You can also redirect all errors to an error log instead of going to standard output, and then you can use the error_log function manually to send debug information to the same log. I noticed this in the error message, for example:<b>Warning</b>: mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'dwtphovu_f3rr37y'@'localhost' (using password: YES) in <b>/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php</b> on line <b>7</b><br /> <br />So it found the username and password, is that part of the information from the include files? The error message only indicates that access was denied for that user, I'm not sure if it's wise to conclude from just that evidence that data in variables is not in the same scope when you use an include file. If that were the case, you should at least be able to find a note about it on the manual for the include statement. The manual page clearly states that the included code inherits the same scope, it doesn't make any exceptions for the CGI version.

Link to comment
Share on other sites

okay, i know the connect include works, because it works on all the other pages of the site that use it without these errors.only the cronjobs started generating these errors since they've upgraded the server. the errors are being generated with the cronjobs. i am not that familiar with cronjobs, i am quite sure they might not have adjusted some setting that refuses include top level variables to persist outside the include (in the calling PHP document).the cronjobs do connect and retrieve variables (i know this because i receive a BCC of the intended mails), despite throwing these errors to the mail address set to receive them in cPanel X.unfortunately i cannot udjust the settings - only the hosting administrators can...yes that is one line in the connection include. to connect with the username and password set on the database in cPanelX. there is only one include - the connection include, and its the include which is spitting these warnings only from the cronjobs.

Link to comment
Share on other sites

There's nothing really special about cron per se, you can run the same script yourself manually without cron through the shell if you want to test it. Cron is basically a tool to automatically run a shell script, but it's still just running a shell script like you can do through SSH or something like that. I use a program called Putty to do telnet and SSH stuff on my server.You can see a list of the differences between the command line and other PHP APIs here:http://www.php.net/manual/en/features.comm...differences.phpOne thing I notice there is that html errors are specifically disabled, but they show up in your output. Are you sure you're running this on the command line? What does your cron command look like? I also notice that it doesn't change the working directory, are you using relative paths to include things? Are you using any error suppression?

Link to comment
Share on other sites

i am afraid i do have a clue which command line cPanelX uses for running cronjobs... it's an html based site which one administrates through.the error handling is set to default on the apache server to DISPLAY_ALL. i would be taking a wild guess if i was to assume that it's the apache console these cronjobs are run through.here's a screenshot of the cronjobs as they have been set up since before the errors started (after the host moved to upgraded servers).cPanel X cronjobs.below are the files used as cronjobs (reminders and cannopyxchange):

<?PHP/*CANOPYXCHANGE BRANDED EXPIRED TRIAL SUPPLIERS NOTIFICATIONVersion 2.0.1*/include("/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php");include("/home/dwtphovu/public_html/ferrety/fab/includes/mailer/class.phpmailer.php");	// include PHPMailer class$sql = "SELECT text_SupplierName, text_ContactFirstName, text_ContactSurname, `text_ContactE-mail`, CURRENT_TIMESTAMP AS timestamp_Current FROM 5_suppliers WHERE smallint_SupplierStatus = 2 AND CURRENT_TIMESTAMP > timestamp_DateEnd";$result = mysql_query_errors($sql, $conn , __FILE__ , __LINE__ , false);$logourl = "http://www.canopyxchange.za.net/canopyxchange.gif";if ($result) {	while ($row = mysql_fetch_array($result)) {		$suppliers .= "<strong>".$row["text_SupplierName"]."</strong> - ".$row["text_ContactFirstName"]." ".$row["text_ContactSurname"]." (".$row["text_ContactE-mail"].")<br />\n";		$timestamp = $row["timestamp_Current"];	}}if (strlen($suppliers) > 0) {	$body             	= getFile("/home/dwtphovu/public_html/ferrety/fab/templat/reminder.html");	// load mail template	$mail				= new PHPMailer();							// create a new object	$body				= str_replace("%LOGOURL%",$logourl,$body);				// insert logo url	$body				= str_replace("%TIMESTAMP%",$timestamp,$body);				// insert logo url	$body				= str_replace("%SUPPLIERS%",$suppliers,$body);				// insert suppliers still prospecting	$body 				= str_replace("%COPYRIGHT%","CanopyXchange",$body);			// insert copyright owner	$body 				= str_replace("%YEAR%",date("Y"),$body);				// insert copyright year	require("/home/dwtphovu/public_html/ferrety/fab/includes/mailer/dwtphovu_auth.php");			// include mailer auth	$mail->From			= "canopy@canopyxchange.za.net";					// set from email	$mail->FromName			= "CanopyXchange";							// set from name	$mail->Subject			= getSubText($body,"<title>","</title>");				// set subject to template page title	$mail->AddBCC("pierre@greywacke.co.za","Pierre \"Greywacke\" du Toit");					// add the developer to the BCC list	$mail->ClearAttachments();										// clears attachments	$mail->MsgHTML($body);											// set HTML Body	$mail->AltBody = strip_tags(html_entity_decode(getSubText($body,					// set Text Body	"<body>","</body>")));	$mail->AddAddress("jaap.venter@ananzi.co.za", "Jaap Venter");						// add recipient	$mail->IsHTML(true);											// set send as HTML	$mail->Send();												// if attempt sending failed}//echo mysql_real_escape_string((count($sql)>0)?join("\n",$sql):"");mysql_close($conn);?>

<?PHP/*CANOPYXCHANGE BRANDED CREDIT LIMIT SUPPLIER NOTIFICATIONVersion 2.0.1*/include("/home/dwtphovu/public_html/ferrety/fab/includes/content/dwtphovu_f3rr37y.php");include("/home/dwtphovu/public_html/ferrety/fab/includes/mailer/class.phpmailer.php");	// include PHPMailer class$sql = "SELECT * FROM 5_suppliers WHERE bigint_CurrentBalance <= smallint_CreditUpperLimit AND bigint_CurrentBalance > smallint_CreditLowerLimit AND smallint_SupplierStatus = 0";$result = mysql_query_errors($sql, $conn , __FILE__ , __LINE__ , false);$logourl = "http://www.canopyxchange.za.net/canopyxchange.gif";if ($result) {	while ($row = mysql_fetch_array($result)) {		$body             		= getFile("/home/dwtphovu/public_html/ferrety/fab/templat/cronjob.html");	// load mail template		$recipient			= $row["text_ContactFirstName"]." ".$row["text_ContactSurname"];		// get contact name		$recipientemail			= $row["text_ContactE-mail"];							// get contact e-mail		$message			= $row["text_CreditUpperMsg"];							// get suppliers upper limit message		$balance			= $row["bigint_CurrentBalance"];						// get suppliers current balance		$limit				= "UPPER";									// set limit message		$mail				= new PHPMailer();								// create a new object		$body				= str_replace("%CONTACTNAME%",$recipient,$body);				// insert contact name		$body				= str_replace("%BALANCE%",$balance,$body);					// insert supplier balance		$body				= str_replace("%LIMIT%",$limit,$body);						// insert limit type		$body				= str_replace("%MESSAGE%",$message,$body);					// insert message		$body				= str_replace("%LOGOURL%",$logourl,$body);					// insert logo url		$body 				= str_replace("%COPYRIGHT%","CanopyXchange",$body);				// insert copyright owner		$body 				= str_replace("%YEAR%",date("Y"),$body);					// insert copyright year		require("/home/dwtphovu/public_html/ferrety/fab/includes/mailer/dwtphovu_auth.php");				// include mailer auth		$mail->From			= "canopy@canopyxchange.za.net";						// set from email		$mail->FromName			= "CanopyXchange";								// set from name		$mail->Subject			= getSubText($body,"<title>","</title>");					// set subject to template page title		$mail->AddBCC("pierre@greywacke.co.za", "Pierre \"Greywacke\" du Toit");					// add the developer to the BCC list		$mail->AddBCC($row["text_AccMgrE-mail"], $row["text_AccMgr"]);							// add the owner to the BCC list		$mail->ClearAttachments();											// clears attachments		$mail->MsgHTML($body);												// set HTML Body		$mail->AltBody = strip_tags(html_entity_decode(getSubText($body,						// set Text Body		"<body>","</body>")));		$mail->AddAddress($recipientemail,$recipient);									// add recipient		$mail->IsHTML(true);												// set send as HTML		$mail->Send();													// attempt sending	}}$sql = "SELECT * FROM 5_suppliers WHERE bigint_CurrentBalance <= smallint_CreditLowerLimit AND smallint_SupplierStatus = 0";$result = mysql_query_errors($sql, $conn , __FILE__ , __LINE__ , false);if ($result) {	while ($row = mysql_fetch_array($result)) {		$body             		= getFile("/home/dwtphovu/public_html/ferrety/fab/templat/cronjob.html");	// load mail template		$recipient			= $row["text_ContactFirstName"]." ".$row["text_ContactSurname"];		// get contact name		$recipientemail			= $row["text_ContactE-mail"];							// get contact e-mail		$message			= $row["text_CreditLowerMsg"];							// get suppliers upper limit message		$balance			= $row["bigint_CurrentBalance"];						// get suppliers current balance		$limit				= "LOWER";									// set limit message		$mail				= new PHPMailer();								// create a new object		$body				= str_replace("%CONTACTNAME%",$recipient,$body);				// insert contact name		$body				= str_replace("%BALANCE%",$balance,$body);					// insert supplier balance		$body				= str_replace("%LIMIT%",$limit,$body);						// insert limit type		$body				= str_replace("%MESSAGE%",$message,$body);					// insert message		$body				= str_replace("%LOGOURL%",$logourl,$body);					// insert logo url		$body 				= str_replace("%COPYRIGHT%","CanopyXchange",$body);				// insert copyright owner		$body 				= str_replace("%YEAR%",date("Y"),$body);					// insert copyright year		require("/home/dwtphovu/public_html/ferrety/fab/includes/mailer/dwtphovu_auth.php");				// include mailer auth		$mail->From			= "canopy@canopyxchange.za.net";						// set from email		$mail->FromName		= "CanopyXchange";									// set from name		$mail->Subject		= getSubText($body,"<title>","</title>");						// set subject to template page title		$mail->AddBCC("pierre@greywacke.co.za", "Pierre \"Greywacke\" du Toit");					// add the developer to the BCC list		$mail->AddBCC($row["text_AccMgrE-mail"], $row["text_AccMgr"]);							// add the owner to the BCC list		$mail->ClearAttachments();											// clears attachments		$mail->MsgHTML($body);												// set HTML Body		$mail->AltBody = strip_tags(html_entity_decode(getSubText($body,						// set Text Body		"<body>","</body>")));		$mail->AddAddress($recipientemail,$recipient);									// add recipient		$mail->IsHTML(true);												// set send as HTML		$mail->Send();													// attempt sending	}}//echo mysql_real_escape_string((count($sql)>0)?join("\n",$sql):"");mysql_close($conn);?>

okay i believe on closer inspection these cronjobs run in the *nix command line (unix).

Edited by Pierre 'Greywacke' du Toit
Link to comment
Share on other sites

On that screenshot, the text you see in the command column is the command being run on the shell. This isn't Apache or cPanel, it just executes that command on the Linux command line. cPanel just gives a web interface to edit the existing crontab program on Linux. So that command executes the php program with the -f and -q switches, and gives it the path to the script to execute. Both scripts are including the file with the errors first, using the full path. The majority of the error messages are in that include file, not the parent file. We have to go back to the errors, so the first error is that access was denied for the user trying to connect to MySQL. That is the problem, the problem is that PHP cannot connect to MySQL from the command line, it doesn't have anything to do with variables or include files. You should be able to verify that by creating a file where the only thing it does is connect to MySQL, then open up a shell and run it with a command similar to the one you see in the screenshot. You should see the same error. It sounds like a setting that needs to be changed on MySQL to allow shell connections, or maybe you need to use a different host name when connecting to MySQL from a command line (unlikely, since MySQL does in fact give a response). All of the other errors listed are based around not being able to connect in the first place.

Link to comment
Share on other sites

hang on, let me check if the database has the localhost allowed or denied access to use the database... :)okay the database access list had %localhost in so i added a %localhost% and 127.0.0.1. will see tomorrow at 7am what happens regarding the script :) i can't run it any other time because these scripts send mails out to the suppliers and they get duplicates. i think that might be the solution to the problem :)

Edited by Pierre 'Greywacke' du Toit
Link to comment
Share on other sites

as i said, i am not that experienced with crontasks.however, i tested this line with the correct username and password - and received the following output from the server in mail:

Error in argument 1, char 2: option not found rUsage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]	   php <file> [args...]  -a			   Run interactively  -C			   Do not chdir to the script's directory  -c <path>|<file> Look for php.ini file in this directory  -n			   No php.ini file will be used  -d foo[=bar]	 Define INI entry foo with value 'bar'  -e			   Generate extended information for debugger/profiler  -f <file>		Parse <file>.  Implies `-q'  -h			   This help  -i			   PHP information  -l			   Syntax check only (lint)  -m			   Show compiled in modules  -q			   Quiet-mode.  Suppress HTTP Header output.  -s			   Display colour syntax highlighted source.  -v			   Version number  -w			   Display source with stripped comments and whitespace.  -z <file>		Load Zend extension <file>.

Link to comment
Share on other sites

I'm trying to explain that what we're doing here doesn't have anything to do with cron. These are just system commands. Cron is simply an interface to run a system command on a schedule. You don't need to use cron in order to run a system command. This is similar to opening a DOS prompt on Windows and typing commands there. If you have your account username and password for your server, you can use a tool like Putty to connect via telnet or SSH, and then just type the commands to run them (e.g., on a Linux system "ls" lists the contents of a directory, "cd" changes the current directory, etc). The "php" command executes PHP with whatever other options you give it. The output you're seeing is what PHP prints when it's executed with an incorrect set of options. It says it doesn't like the -r option. I'm not sure why it would say that, because it's definitely listed here:http://www.php.net/manual/en/features.comm...ine.options.phpThe note on that page says that the -r option is not available in the CGI binary, only the CLI binary. I'm not sure why executing php would run the CGI instead of CLI, I was assuming that would run the CLI binary. That also explains the HTML error messages, the CGI binary will output HTML content unless you tell it otherwise.In any case, use the -f switch to tell it which file to load. Like I mentioned, I advise creating a small script which only connects to MySQL in order to test, and log in with Putty to run it (unless you want to put it on a schedule and wait for it to run, which is going to be a pain for testing).

Link to comment
Share on other sites

thanks for being so patient with me, justsomeguy :) i will get Putty and try it out...at the moment there are more urgent issues however that need attending to.

Link to comment
Share on other sites

  • 2 weeks later...

hi, been a while since on this issue - but it has been resolved by the isp. it turns out they did not carry all the mysql user permissions over to the new server.this issue is now resolved :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...