优化PHP脚本以防止max_execution_time限制

时间:2011-09-13 19:23:45

标签: php downloading-website-files

我在本地服务器上编写了一个PHP脚本来循环播放一系列电影标题,然后使用http://www.imdbapi.com/下拉相关的元数据。

for ($i=0; $i < count($files['Film']); $i++) { 
    // get data from IMDB based on file title
    $imdb_data = json_decode(file_get_contents('http://www.imdbapi.com/?t='.urlencode($files['Film'][$i]['title'])), true);

    // save poster image
    $img_name = trim(strtolower($imdb_data['Title'])).'.jpg';
    file_put_contents('img/posters/'.$img_name, file_get_contents($imdb_data['Poster']));

    // set film data
    $files['Film'][$i]['year'] = $imdb_data['Year'];
    $files['Film'][$i]['runtime'] = $imdb_data['Runtime'];
    $files['Film'][$i]['rating'] = $imdb_data['Rating'];
    $files['Film'][$i]['summary'] = $imdb_data['Plot'];
    $files['Film'][$i]['image'] = $img_name;
    $files['Film'][$i]['location_id'] = $this->data['Film']['location_id']; 
}

我在启动file_put_contents的行上点击了php max_execution_time。我注意到有一些图像被下载,我也得到了一个不完整的图像所以我猜我在下载图像时达到了时间限制。

我可以做些什么来改进我的脚本以防止这种情况发生?我真的不喜欢增加时间限制的解决方法,如果有一些基本的东西可以优化脚本。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用AJAX在很短的时间间隔内加载每个项目。

您可以在javascript中使用间隔调用函数,而不是在PHP内部使用for,这将加载返回的php调用内容。

答案 1 :(得分:0)

您可以使用set_time_limit()函数重置max_execution_time。

http://www.php.net/manual/en/function.set-time-limit.php

答案 2 :(得分:0)

这主要是一个项目的复制粘贴(从异步加载mysql的数据)我在一个月前工作。我根据你的需要稍微改了一下,我给你写了一些评论,并创建了一个新文件(getData.php)。

我没有完全详细地下载电影,但它下载图像并上传,几乎相同的过程,希望你可以根据自己的需要进行调整。

将这两个文件放在一个目录中并运行index.php

这是第一个文件:index.php

    <html>
    <head>
    <script type="text/javascript">

    var request = false;
    try { 
      request = new XMLHttpRequest(); 
    } catch (trymicrosoft) {                         
      try { 
        request = new ActiveXObject("Msxml2.XMLHTTP"); 
      } catch (othermicrosoft) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {                  
          request = false;       
        }
      }
    }

    if (!request) 
      alert("Error initializing XMLHttpRequest!"); 
    </script>

    <script type="text/javascript">
       function getData() 
       {

        //inform the user for to wait a little bit
        var txt=document.getElementById("messageBox")
        txt.innerHTML="Please wait for the image to download...";

            //we will call asychronously getData.php 
            var url = "getData.php";
            var params = "";//no url parameters

            request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer 

            //Some http headers must be set along with any POST request.
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
            request.setRequestHeader("Content-length", params.length);
            request.setRequestHeader("Connection", "close");

            request.onreadystatechange = updatePage;
            request.send(params);

       }////////////////////

       //You're looking for a status code of 200 which simply means okay.
       function updatePage() {
         if (request.readyState == 4) {
           if (request.status == 200) 
           {  
                //getData.php sends as the image size, get it
                var r=request.responseText.split("$");//$ is a custom data separator I use  

                //inform the user
                var txt=document.getElementById("messageBox")
                txt.innerHTML="The file was downloaded! Its size is:"+r[0]+"x"+r[1]+" the name is:"+r[2];

                /*r is a javascript array, 0=width, 1=height, 2=file name
                */

                //display the image 
                 document.getElementById("imageBox").style.width = r[0] + 'px';
                 document.getElementById("imageBox").style.height = r[1] + 'px';
                document.getElementById("imageBox").style.backgroundImage = "url("+r[2]+")";

           } 
           else{
             //alert("status is " + request.status);
             }
         }
       }

    </script>
    </head>
    <body onload="getData();">

    <div id='messageBox'></div>
    <div id='imageBox'></div>

<font color=red>
    You see I am under the image but I am already loaded cause 
    I don't have to wait for the image to load cause it loads asychronously.
    Whenever the image is ready the xmlhttp mechanism will let the page
    know and the associated javascript function will update the dom and will
    update the page without reloading it!
    </font>
    </body>
    </html>

这是第二个文件getData.php

<?PHP

//make a name for the file
$file_name = rand(1,9999).'.jpg';

//download the file
file_put_contents($file_name, file_get_contents('http://chachatelier.fr/programmation/images/mozodojo-original-image.jpg'));


//get the size of the image
$size = getimagesize($file_name);


//send asycnhronously the width, height, and the name
echo $size[0],'$',$size[1],'$',$file_name;

?>