I am attempting to download images saved in a url to a local folder, and have made the following attempt at doing so with curl. I would like to know if it is necessary to include curl or download it seperateley, or if my function will just work. I would like to know if there are any obvious problems with my implementation below. I am aware of the sql vulnerability and I am switching to prepared statements. I have trimmed non relevant parts of the code for brevity.
edit: the function is out of the while loop. The page displays if I comment out the call the the function, otherwise I only get a blank page. Why is this
<?php
header("Content-Type: text/html; charset=utf-8");
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","someuser","notreal");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("somedb",$con);
if($cmd=="GetAuctionData")
{
$sql="SELECT * FROM AUCTIONS WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM AUCTIONS WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
$result = mysql_query($sql);
function savePicture($imageUrl) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $lastImg);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
curl_close($ch);
$newImg = imagecreatefromstring($fileContents);
return imagejpeg($newImg, "./{$pk}.jpg",100);
}
while ($row = mysql_fetch_array($result))
{
$lastImg = $row['PIC_URL'];
savePicture($lastImg);
<div id='rightlayer'>
<img src='./".$pk.".jpg' width='".$outputWidth."' height='".$outputHeight."'>
</div>
</div>
</div>";
}
}
mysql_free_result($result);
You’ll get an error if you declare a function inside a loop when the loop is run more than one time. So you should declare the savePicture function outside while.
I'd take the function definition out of the while block.
In my opinion your using curl for the sake of using curl here, a simpler method would be to use file get contents.
Related
I have a php script that is checking the result of a virustotal scan. If the scan returns positive for malicious code it changes the value to 0 in the db. I have another php script which checks the value and if it is 0 it removes the entry from the db and then removes the file from the directory. When I run this through the command line it works perfectly, however when cron runs it, it does remove the db entry as it should however it does not delete the file from the directory.
Any help would be much appreciated.
Here is the end of the php file with the unlink:
else{
// if not it deletes the image
$hash = $row['hash'];
$result2 = mysqli_query($connection, "DELETE FROM userUploads WHERE hash = '$hash' ");
// need due to dir structure
$pat = str_replace('../','', $row['fileName']);
unlink ($pat);
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
For reference, here is the full file:
<?php
function VirusTotalCheckHashOfSubmitedFile($hash){
$debug = false;
$post = array('apikey' => '','resource'=>$hash);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.virustotal.com/vtapi/v2/file/report');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); // please compress data
curl_setopt($ch, CURLOPT_USERAGENT, "gzip, My php curl client");
curl_setopt($ch, CURLOPT_VERBOSE, 1); // remove this if your not debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code == 200) { // OK
$js = json_decode($result, true);
if($debug){echo "<pre>";}
if($debug){print_r($js);}
if($js["positives"]==0){
// clean
return true;
}else{
// malware
return false;
}
} else { // Error occured
print($result);
}
curl_close ($ch);
}
$connection = mysqli_connect("");
if (!$connection) {
trigger_error("Could not reach database!<br/>");
}
$db_selected = mysqli_select_db($connection, "seclog");
if (!$db_selected) {
trigger_error("Could not reach database!<br/>");
}
// Selecs images that have not been marked as clean by virus total
$result = mysqli_query($connection, "Select hash, fileName FROM userUploads WHERE scanResult = 0");
if (! $result){
echo('Database error: ' . mysqli_error($connection));
}
while ($row = mysqli_fetch_assoc($result)) {
// checks for results on scanned images
if(VirusTotalCheckHashOfSubmitedFile($row['hash'])){
// if report returns image is malware free we update its virusFree attribute to true
$hash = $row['hash'];
$result2 = mysqli_query($connection, "UPDATE userUploads SET scanResult = 1 WHERE hash = '$hash'");
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
}else{
// if not it deletes the image
$hash = $row['hash'];
$result2 = mysqli_query($connection, "DELETE FROM userUploads WHERE hash = '$hash' ");
// need due to dir structure
$pat = str_replace('../','', $row['fileName']);
unlink ($pat);
if (! $result2){
echo('Database error: ' . mysqli_error($connection));
}
}
}
?>
The problem almost certainly is the path $pat = str_replace('../','', $row['fileName']);. Crons execute PHP cli, that is not the same PHP that Apache executes, also is another context. Try setting absolute path:
$pat = "/var/www/myfolder/myscript.some";
If for some reason you need a variable because folder structure depends of the context (e.g. development, production) you could pass the variable as a parameter when the cron executes PHP:
//this is the cron
30 17 * * 1 myscript.php myvar
Inside myscript.php $argv[1] is myvar.
I'm having some problems looping this script through a large database of 1m+ items. The script returns the size of an image in bytes from it's url and inserts the result into a database.
I get the browser error Error code: ERR_EMPTY_RESPONSE on my test attempt. This doesn't bode well. Am I trying to loop through too many records with a while loop? Any methods for a fix?
<?php
error_reporting(E_ALL);
mysql_connect('xxxx', 'xxxx', 'xxxx') or die("Unable to connect to MySQL");
mysql_select_db('xxxx') or die("Could not select database");
$result = mysql_query("SELECT * FROM items");
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result)) {
$ch = curl_init($row['bigimg']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
mysql_query("UPDATE items SET imgsize = '" . $info . "' WHERE id=" . $row['id'] . " LIMIT 1");
}
}
?>
I think your issue might be related to the fact you are trying to call eachtime curl_exec. You might want to change your code to this in 2 parts: first retrieve the data from the database and then make the curl calls.
I am using Magento's event-observer model at an event sales_order_place_after. From that I catch order No. Then now I want to pass that order no. which is store in a variable to another external php file say external.php.
This external.php contains connection to Magento database which fetches data based on Order No. so I want to pass this order No. to that query & also I have to include this external.php file in that Observer.php
so my ultimate aim is that once customer press Place Order tab, external.php file must get executed as it will get order No. & it fires query on database & do the needful job.
So plz help me to pass variable from one page to other external.php & also how to include/execute that external.php file at customer place order event(sales_order_place_after)..
My Observer.php-:
<?php
include("connection/Final/external.php");
class Sample_Event_Model_Observer {
public function Mytestmethod($observer) {
$event = $observer->getEvent(); //Fetches the current event
$eventmsg = "Current Event Triggered : <I>" . $event->getName() . "</I>";
echo Mage::getSingleton('checkout/session')->addSuccess($eventmsg);
$Id = $observer->getEvent()->getOrder()->getId();
$incrementid = $observer->getEvent()->getOrder()->getIncrementId();
$ordermsg1 = "Current order Id : <I>" . $Id . "</I>";
echo Mage::getSingleton('checkout/session')->addSuccess($ordermsg1);
$ordermsg2 = "Current increment Id : <I>" . $incrementid . "</I>";
echo Mage::getSingleton('checkout/session')->addSuccess($ordermsg2);
$p = new testDatabase();
$p -> setId($incrementid);
$p -> dbConnect();
} } ?>
My external.php-:
<?php class testDatabase {
public function setId($getId)
{
$incrementid=$getId;
echo $incrementid;
}
public function dbConnect() {
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con) {
die('Could not connect: ' . mysql_error()); }
$seldb = mysql_select_db($db_name, $con);
If ($seldb) {
echo "Database Found ";
$query = "INSERT INTO sample(id) VALUES($incrementid)" ;
$result = mysql_query($query);
print "id is added to the database";
mysql_close($seldb);
} else {
echo "Database NOT Found ";
}
} }
How can I access variable $incrementid in Function1.php? So problem is I am unable to access $incrementid as it is unable to insert in my sample table. I have catched sales_order_place_after event. So that once customer press PLACE ORDER, I can include Function1.php & it will take increment/order id & I can able to access Functions in it that will do needful job...
My updated files-:
http://www.sample.com/magento/app/code/local/Sample/Event/Model/Observer.php
Observer.php
<?php
class Sample_Event_Model_Observer {
public function Mytestmethod($observer) {
$Id = $observer->getEvent()->getOrder()->getId();
$incrementid = $observer->getEvent()->getOrder()->getIncrementId();
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, "http://www.sample.com/magento/connection/Final/external.php?order_id=<?php echo $incrementid ?>");
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_exec($cURL);
curl_close($cURL);
}
}
?>
Path-: http://www.sample.com/magento/connection/Final/external.php
external.php
<?php
echo "Hi";
$orderID = $_GET['incrementid'];
echo $orderID;
?>
I need to use this value of $orderID variable in below function? HOw to do the same?
Plaese help me...
Using curl you can do this
$data => array('data'); // array of your data
$ExternalLibPath => 'your extenal file page';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "$username:$passsword");
curl_setopt($ch, CURLOPT_URL, $ExternalLibPath);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
So simple... You can use GET method in external.php.
In observer page
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, "http://www.example.com/external.php?order_id=<?php echo $orderId ?>");
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_exec($cURL);
curl_close($cURL);
In external.php, you can get variable value by GET method which we sent it by URL parameter.
$orderID = $_GET['order_id'];
I have designed a url loader for my site, it's working fine but have little problem that it cant delete url at end after loading.
<?php
// set time 1000
set_time_limit(1000);
// connect to db
include ("../../config.php");
// select data from database target domain and T2 table
$result = mysql_query( "SELECT * FROM domain" ) or die("SELECT Error: ".mysql_error());
$resultx = mysql_query( "SELECT * FROM worth" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_query($result);
$num_rowsx = mysql_query($resultx);
// fetching data
while ($get_infox = mysql_fetch_assoc($resultx) && $get_info = mysql_fetch_assoc($result))
{
$domax="www.".$get_infox[domain];
$doma=$get_info[domain];
if ($doma != $domax[domain])
{
// load urls
$url="http://www.w3db.org/".$doma."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$index=curl_exec($ch);
$error=curl_error($ch);
curl_close($ch);
// deleting current loaded url
echo "url loaded and deleted ".$url."<br />";
mysql_query("DELETE FROM domain WHERE domain=".$doma.""); // problem here
}
else
{
echo "url skiped and deleted ".$url."<br />";
mysql_query("DELETE FROM domain WHERE domain=".$doma.""); // problem here
}
}
mysql_close($con);
?>
I do not know why it can't delete, code is ok, no error. I do not know why, please help.
For test
Table 1 :: domain having column domain
Table 2 :: T1 having column domain
Task
Take url from (table 1) domain, compare with (Table 2) domain url. If not match fetch with curl and then delete, else skip loading url and delete it.
The url is fetched, but it isn't deleted at the end.
Most likely the query fails because $doma is a string that's not inside quotes, that is, your query is ... WHERE domain=foo when it should be ... WHERE domain='foo'.
mysql_query("DELETE FROM domain WHERE domain='".$doma."'") or die( mysql_error() );
(Remember the mysql_error() part, it'll help you debug a lot of issues later on.)
It is possible your query is missing single quotes around $doma ... try this instead ...
"DELETE FROM domain WHERE domain='".$doma."'"
mysql_query("DELETE FROM domain WHERE domain='".$doma."'"); // problem here
assuming $doma is a string ..
I have a little problem. I need to execute an script that execute 5000 URL in php.
$con = mysql_connect("localhost","user","psswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);
print "connected";
$result = mysql_query ("SELECT name, uid FROM obinndocusers");
// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}
Any idea??
Thx.
use CURL
LIKE :
$ch = curl_init();
while ($row = mysql_fetch_array($result)) {
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
}
// close cURL resource, and free up system resources
curl_close($ch);
Use cURL
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
First thing: header() is a primitive to send http headers to browser. It must be called before any stdout output (like 'print' or 'echo').
Second thing: "Location: " header will tell your browser to redirect to that URL. You can not specify more that one URL.
If you need your script to do http queries, use curl or fopen, and do not call your script from your browser.
The best way would be with CURL (see other answer by Haim Evgi), but if the server doesn't have the curl extension, then this will also work.
<?
$con = mysql_connect("localhost","user","psswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);
print "connected";
$result = mysql_query ("SELECT name, uid FROM obinndocusers");
// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
file_get_contents("http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
}